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: Agent Write Contract Suite - write sessions, decision panel, backend boundary, shared namespace (#72)
Sol Aitkenc3a2fcc6321e
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 87c594f2..fbd12525 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.40.0",+ "version": "0.41.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex e94ba581..97d71dda 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.40.0",+ "version": "0.41.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e34201be..88b8b302 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,59 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [0.41.0] - 2026-06-04++Agent Write Contract Suite: how external agents write into and+deliberate with the Brain without an LLM inside the core. One+file-backed write-session kernel gives callers a JSON-envelope+lifecycle - open a session, receive the generation prompt, submit the+artifact, get machine-readable correction errors without losing+state, and commit only when validation is clean. A multi-persona+decision panel rides the same kernel as a session kind, memory+import gains a pluggable backend boundary, and explicit+remember-writes can mirror into a cross-agent shared namespace with+fail-soft semantics. The calling agent generates every word; the+Brain sequences, validates, and commits. MCP grows by exactly one+tool (65 -> 66).++### Added++- **Write-session protocol** (`o2b brain session`, MCP+ `brain_write_session`). `open` returns a `needs-llm-step` envelope+ with a generation prompt, schema hints, and collision metadata when+ the target is occupied; `submit` validates fail-closed and returns+ `done`, `needs-correction` (coded `{code, path, message}` errors+ plus a compact correction prompt, retry cap default 3), or+ `needs-review` for operator-gated sessions (`approve` commits,+ `abandon` is terminal). Sessions persist as JSON under+ `Brain/.sessions/write/` with lazy TTL (default 24h) and a `sweep`+ op; `create` intent never overwrites, `merge` appends a+ session-stamped delimited section, reserved namespaces+ (`Brain/preferences/`, `Brain/log/`, `Brain/_brain.yaml`, dot-stores)+ are refused outright. Every terminal transition lands one+ `write-session` audit event in the Brain log.+- **Decision panel** (`o2b brain panel`). Distinct analytical lenses+ walk deterministic steps (`persona:<slug>` ... then `synthesis`) on+ the write-session kernel; persona definitions are operator-curated+ notes under `Brain/personas/` (built-in default set: technical,+ strategic, risk, user-experience), and the committed decision note+ lands under `Brain/decisions/panels/` with per-persona sections.+ The Brain supplies prompts and validation only - the calling agent+ authors every answer and the synthesis.+- **Memory backend boundary**. A `MemorySourceBackend` protocol+ (`discoverMemoryDir`, `parseMemoryFile`, `renderPreference`,+ `slugifyName`) with a frozen registry and config-driven selection+ (`memory_backend`, default `claude`); the Claude Code adapter+ delegates to the existing import modules byte-identically, and an+ unknown backend id fails with the registered list.+- **Cross-agent shared namespace**. The opt-in `shared_namespace`+ config key mirrors explicit remember-writes (feedback signals and+ narrative notes) into a second vault after the primary write+ succeeds, with agent plus `origin_vault` attribution. Mirroring is+ fail-soft by contract - a broken or self-pointing shared vault+ degrades to `mirror: "failed"` and the primary write is never+ affected; the key absent means zero behavior change.+## [0.40.0] - 2026-06-04Project History Suite: a linked project's git history and code@@ -4399,6 +4452,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[0.41.0]: https://github.com/itechmeat/open-second-brain/compare/v0.40.0...v0.41.0[0.40.0]: https://github.com/itechmeat/open-second-brain/compare/v0.39.0...v0.40.0[0.39.0]: https://github.com/itechmeat/open-second-brain/compare/v0.38.0...v0.39.0[0.38.0]: https://github.com/itechmeat/open-second-brain/compare/v0.37.0...v0.38.0diff --git a/README.md b/README.mdindex 169b6d17..04019ad6 100644--- a/README.md+++ b/README.md@@ -114,7 +114,7 @@ The capabilities you actually feel day to day:These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron with a complexity-to-thinking warning, cross-project pointers for shared vaults, transient pinned session context through `brain_pinned_context` / `Brain/pinned.md`, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, configurable Markdown-link presentation output, MCP output-contract checks for core agent-facing tools, private-region stripping with `<private>...</private>`, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`), the v0.17.0 Brain Lifecycle Review Suite (`intent-review`, `retention`, `monthly`, lifecycle schemas, and discipline complexity ratio), and the v0.18.0 MCP context economy (a per-tool preview budget that returns a bounded inline preview and parks the full payload in a vault-local artifact the agent fetches on demand with `brain_artifact_get`, plus a `recall_hint` one-liner on search results), and the v0.19.0 typed graph semantics (typed frontmatter relationships - `related` / `extends` / `contradicts` / `superseded_by` - that surface inline on search results, a `visibility:` scoping axis for `brain_search`, and a `brain_mcp_landscape` view of the Model Context Protocol servers configured across the vault), and the v0.20.0 Recall and Ranking Quality suite (a configurable Weibull recency-decay curve, structural query-intent classification that re-weights ranking by query shape, language-agnostic synonym expansion via local co-occurrence, per-memory and total recall character budgets for `brain_context_pack`, a persistent query cache that self-invalidates on a corpus-generation change, and a `brain_pre_compress_pack` tool that returns a budgeted top-preferences addendum for a host runtime to inject before context compression), and the v0.21.0 Brain Lifecycle Suite (a per-preference mutation audit trail keyed by preference id - create / promote / update / retire / merge with revision + content-hash before/after, via `o2b brain audit` and `brain_audit`; a multi-phase `dream` pipeline that names its close / reconcile / synthesize / heal / log seams and reports a structured per-phase summary without rewriting the proven internals; deterministic reconcile-phase domain classification that buckets contradictions into claims / entity / decisions / source-freshness, auto-resolves only the decisive source-freshness case, and surfaces the rest as open questions instead of forcing a merge; a budgeted `o2b brain morning-brief` / `brain_morning_brief` session-start summary of top preferences, recent open questions, and recent notes; language-agnostic ISO-8601 temporal extraction that fills preference validity windows from signal text; and opt-in heal-phase vault enrichment that links exact title mentions across user pages), and the v0.22.0 Vault portability + session economy suite (a deterministic lossless session codec - `expand(compress(x)) === x` for all input, opt-in on the signal store and exposed as `o2b brain codec`; an `o2b brain sources` / `brain_sources` read-only dashboard of signals by agent and source type; vault-map `{{role}}` tokens resolved via an optional `Brain/_vault-map.yaml` and wired into scan-inline read paths and graph import; named multi-vault profiles with `o2b vault profile` + a `brain_switch_vault` tool, activated by a pointer in config; and `o2b brain graph-export` / `graph-import` for moving a vault's knowledge graph between layouts with skip/overwrite/merge conflict modes). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.-The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record).+The v0.26.0 surface adds audited schema mutation/admin tools, real-time lifecycle capture hooks for prompt markers and `brain_feedback` tool calls, CJK-aware FTS recall, and `brain_watchdog` / `o2b brain watchdog` recovery probes. The v0.27.0 surface adds recall-control and trust tools: structured search query documents, session focus, MCP `brain_recall_gate`, polarity-aware context lanes, and opt-in evidence packs for CLI/MCP search. The v0.28.0 surface adds a deterministic prompt-injection guard for automatically surfaced Brain context, agent-blind `$secret:NAME` references, and preview foundations for source-scoped forget, privacy-scanned knowledge packs, and oversized payload externalization. The v0.29.0 surface adds opt-in context receipts and recall telemetry, read-only context budget presets, pre-compaction extraction, and a continuity-backed session recall DAG. The v0.33.0 surface adds the Recall Trust Suite: relation-aware recall polarity for typed memory edges, an explicit retrieval feedback loop with bounded learned weights (`o2b search feedback` / `weights`, MCP `brain_recall_feedback`), time-aware recall (`--since` / `--until` with natural-language ranges), verified multi-record recall (per-token union records, IDF-weighted coverage, rare-term abstention), and a search-completeness verdict with a false-absence guard. The v0.34.0 surface adds the Token Diet: a budgeted SessionStart injection of `Brain/active.md` (default 8,000 chars, `active.inject_budget_chars`) with the post-compaction path moved to the supported SessionStart `compact` matcher, a once-per-session post-write reminder cadence, frontmatter escape-amplification fixed at the parser with a one-shot `o2b brain upgrade --apply` repair for already-corrupted preference files, three consolidated read tools (`brain_brief`, `brain_analytics`, `schema_inspect`) with 18 hidden deprecated aliases, registry description caps with a contract guard, preview budgets by default, and a `scripts/measure-token-surface.ts` report. The v0.35.0 surface adds the Memory Integrity Suite: a canonical entity registry under `Brain/entities/` (one Markdown entity per `(category, name)` with alias resolution, archive/restore, typed relations, `o2b brain entity` CLI verbs, a read-only `brain_entity` MCP tool, doctor duplicate/relation lints, and alias-aware search boost with `entity_canonical` explanations), per-device Brain log shards (`Brain/log/<date>.<deviceId>.jsonl` + `.md` keyed by a device-local id, merged reads through `readLogDay`/`listLogDates`, no more Syncthing write conflicts, legacy days untouched), capture boundaries (a `sessions:` block with ignored/stateless session globs and message suppression regexes, applied before any extraction at both live-hook and import seams, counted but never stored raw; keep suppression regexes simple - they run on every message, and a catastrophic-backtracking pattern slows capture), and deterministic regex fact extraction (seven precision-first families over user turns, `source_type: extracted` signals with family-scoped dedup and canonical entity anchors). The v0.36.0 surface adds the Embedding Provider Suite: an offline `local` embedding provider (deterministic feature hashing, no cloud, no key, no model download - set `embedding_provider: local` for a privacy-first recall path), a CLI provider registry (`o2b search provider add | list | show | remove`, persisted to `Brain/search/embedding-providers.json` storing only environment-variable names, resolved after the built-ins so a configured key is never shadowed), an embedding cost gate (`embedding_cost_gate_usd`, default 0 = off; refuses an over-budget run unless `o2b search index --force-cost`) with the active `<provider>:<model>:<dimension>` signature and a refresh-cost estimate in `o2b search status`, and an opt-in Reciprocal Rank Fusion mode (`search_fusion_mode: rrf`, `search_rrf_k` default 60) that fuses the keyword and semantic lanes by rank position instead of weighted magnitude while the default `linear` mode stays bit-identical and storage remains SQLite + sqlite-vec + FTS5. The v0.37.0 surface adds the Agent Surface Suite: skills as callable MCP tools (`list_skills` / `get_skill` over the shipped `skills/` plus vault-local `Brain/skills/`), two-pass tool catalog hydration (a compact `catalog` scope where `tool_hydrate` returns the sorted catalog and per-name full schemas while every tool stays callable), five named tool-surface profiles with fail-open fallback (`mcp_tool_profile` / `o2b mcp --tool-profile`), deterministic BM25-style skill auto-attach (`skills_attach`, gated by `skill_auto_attach`), config-level capture role filtering (`session_capture_roles`), session-scoped search focus with SessionEnd auto-clear and gated context-pack promotion (`--session`, `focus_session`, `search_focus_context_pack`), operator-readable handoff notes (`o2b brain handoff`, gated SessionEnd generation via `session_handoff`), and scoped current-intention chains with a move-to-history lifecycle (`o2b brain intention`, MCP `brain_intention`). The v0.38.0 surface adds the Workspace Insight Suite: project vault pointers (`o2b brain project link | list | remove | status` writes a `.o2b-vault.json` into any project directory and `resolveVault` honours it from anywhere under that tree), read-only recall sources (`o2b brain source add | list | remove` with self/duplicate/circular validation and BROKEN flagging), cross-vault union search (`o2b search <query> --global`, `brain_search { global: true }` - origin-labelled results, external vaults never written to), a configurable wikilink path format (`wiki_link_format`: preserve/full/short plus `o2b brain links normalize`), a shell-native surface (`o2b brain profile` materializes `Brain/profile.md` + a `.o2bfs` root marker; `o2b brain sgrep` is grep-shaped semantic search), a grounded trigger queue with an anti-nag lifecycle (`o2b brain trigger scan | list | ack | dismiss | act | history`, MCP `brain_trigger`, cooldown-key dedup, morning-brief delivery once per `trigger_cooldown_days`), deep vault synthesis (`o2b brain deep-synthesis <topic>`, MCP `brain_deep_synthesis` - a deterministic dossier of agreements, contradictions, stale claims, and knowledge gaps), idea discovery (`o2b brain ideas`, MCP `brain_idea_discovery`), and opt-in recall-gate telemetry (`recall_gate_telemetry`, hashed prompts only, gate_list / gate_summary operations). The v0.39.0 surface adds the Memory Observability Suite: a contract-wide continuity schema version (`o2b.continuity.v1`, legacy records read as v1, dedup ids unchanged), a lazy gated telemetry emit kernel with structural no-consumer and fail-open guarantees across every gated surface, a continuity read-model with private-record masking shared by all read-side consumers, ATOF/ATIF trajectory export (`o2b brain continuity export --format atof|atif` - read-only, redaction honoured), a deterministic memory quality benchmark (`o2b brain bench memory` with checkpoint/resume and separate quality/latency/context-cost reporting), and the `docs/observability.md` contract enumerating every event kind, gate, and safety rule. The v0.40.0 surface adds the Project History Suite: git history as project memory (`o2b brain git ingest | status | find | mine` - a sanitized read-only reader lands commits, tags, and release ranges in a per-repo record store under `Brain/projects/git/<repo-key>/` with watermarked duplicate-free incremental runs, a deterministic FTS-discoverable digest note, store-only history queries that survive checkout deletion, and decision-shaped commits mined into draft ADR candidates under `Brain/decisions/candidates/` with sha-stable skip-existing identity), regeneration-safe architecture notes (`o2b brain architect <project-path>` - a stdlib-only deterministic scanner renders overview and per-module notes through paired `o2b:begin`/`o2b:end` sentinel regions, so operator prose survives every re-scan byte-for-byte and corrupted markers fail closed), and `brain_query` recall telemetry (per-call opt-in mirroring `brain_search`, kind-only payload - the supplied preference id, topic, or timestamp never lands in a continuity record). The v0.41.0 surface adds the Agent Write Contract Suite: provider-agnostic write sessions (`o2b brain session`, MCP `brain_write_session` - a file-backed JSON-envelope lifecycle where the calling agent generates, the Brain validates fail-closed with machine-readable correction errors and a retry cap, collisions never overwrite without explicit intent, operator review gates are opt-in, and every terminal transition is audited), a multi-persona decision panel riding the same kernel (`o2b brain panel` with operator-curated personas under `Brain/personas/` and committed decision notes under `Brain/decisions/panels/`), a pluggable memory backend boundary (`memory_backend` config key, Claude Code adapter byte-identical by default), and an opt-in cross-agent shared namespace (`shared_namespace` mirrors feedback signals and notes into a second vault fail-soft, with agent and origin attribution).## CLIdiff --git a/docs/brainstorm/agent-write-contract-suite/cli-output/claude.md b/docs/brainstorm/agent-write-contract-suite/cli-output/claude.mdnew file mode 100644index 00000000..11b14d00--- /dev/null+++ b/docs/brainstorm/agent-write-contract-suite/cli-output/claude.md@@ -0,0 +1,35 @@+### Variant 1: Unified session kernel+- **Approach**: Build one generic, file-backed write-session state machine in `core/brain/session/` (envelope with `status`/`session_id`/`step`, TTL + retry store, audit log) that is the literal deliverable of Task 1. Task 4's decision panel becomes a session *kind* (`panel`) riding the same kernel — OSB emits per-persona prompts as steps and validates the synthesis on submit — so it needs no parallel lifecycle. Task 2 stays a narrow `AgentBackend` boundary the session consults for render/validation strategy; Task 3 is an independent fail-soft mirror hooked at the existing `signal`/`note`/`preference-txn` chokepoints.+- **Trade-offs**:+ - Pro: TTL, retry cap, collision metadata, and audit log are built exactly once and shared by both agent-facing flows.+ - Pro: Task 4 collapses to persona-loading + a synthesis schema, since it inherits the correction loop and operator-gate (`needs-review`) for free.+ - Pro: Fewer new MCP tools (one session surface with a `kind` discriminator) keeps the 65-tool growth deliberate.+ - Con: Kernel must be generic enough on day one to serve both an artifact-write and a multi-step panel — some up-front design tax.+ - Con: Couples panel and write-session evolution; a panel-specific need could leak into the shared envelope.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Four independent modules sharing only contracts+- **Approach**: Ship each task as a self-contained module sharing nothing but type contracts (`SchemaValidationResult`, envelope types). Write-session, backend registry, shared-namespace mirror, and decision panel each own their store, surface, and tests; the panel calls the write-session as a library but persists to its own state. Each module maps one-to-one to a kanban task.+- **Trade-offs**:+ - Pro: Independently shippable, testable, and revertable — clean blast-radius isolation per task.+ - Pro: Strongly additive; no module reshapes another's write path, fitting the "additive-only" and fail-closed/fail-soft split naturally.+ - Pro: Lowest design risk — no premature generalization.+ - Con: Session lifecycle, TTL, retry, and audit logic get duplicated (or near-duplicated) between Task 1 and the panel.+ - Con: More MCP tools and two session-ish state machines that can drift apart over time.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Backend-protocol-first (everything is a backend capability)+- **Approach**: Make Task 2's `AgentBackend` protocol the central abstraction and route the write-session, persona panel, and shared-namespace mirroring through it as backend-dispatched capabilities. The Claude memory render becomes the first backend; selection is config-driven, and all agent-write behavior is expressed as capabilities a backend declares.+- **Trade-offs**:+ - Pro: Maximum extensibility — a future runtime gains write-session, panel, and mirror behavior through one seam.+ - Pro: Single dispatch point for all agent-facing format concerns.+ - Con: Over-abstraction when only one backend (Claude) exists; the deterministic-core rule means backends are format adapters, not generation engines, so the seam carries little real variation today.+ - Con: Largest refactor — pulls the `claude-memory-*` flow and core write paths under a new boundary, straining the "do not change existing public APIs / additive-only" constraint.+ - Con: High YAGNI risk; couples four independently-valuable tasks to one speculative abstraction.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1+**Rationale**: Task 4 is specified to run *as* a write-session, so a shared session kernel turns the panel into a thin persona-and-synthesis layer instead of a second state machine — the strongest reuse for the least surface, which directly serves the deliberate-MCP-growth and no-LLM-in-core constraints. It keeps Task 2 as a deliberately narrow render/validation boundary and Task 3 as a fail-soft hook at the existing chokepoints, avoiding both the duplication of Variant 2 and the premature, core-reshaping generalization of Variant 3.diff --git a/docs/brainstorm/agent-write-contract-suite/cli-output/prompt.md b/docs/brainstorm/agent-write-contract-suite/cli-output/prompt.mdnew file mode 100644index 00000000..1ac29481--- /dev/null+++ b/docs/brainstorm/agent-write-contract-suite/cli-output/prompt.md@@ -0,0 +1,75 @@+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++One PR ships four related kanban tasks as a single "Agent Write Contract Suite". Theme: how external agents write into and deliberate with the Brain without an LLM living inside the core.++## Task 1 (t_bc36a8a2) - Provider-agnostic Brain write-session protocol with correction loop++External agents need to propose structured Brain artifacts (schema-pack pages, handoffs, evidence summaries, curated notes). Today validation can reject malformed output, but there is no agent-facing lifecycle. Add a write-session protocol: a caller opens a session and receives a JSON envelope with `status`, `session_id`, `step`, generation `prompt`, schema hints; the caller produces the artifact, submits it back; OSB validates locally and returns either `done`, a `needs-correction` step with machine-readable errors plus a compact correction prompt, `needs-review` for operator-gated targets, or terminal `failed` after a retry cap. Sessions live in a store with TTL and retry count. Path collisions never overwrite without explicit overwrite/merge intent (existing-content metadata is returned). Completed sessions land in an audit log. Core Brain transitions remain deterministic; OSB never calls an LLM for this protocol.++## Task 2 (t_53f9f67f) - Pluggable backend boundary for memory rendering++OSB memory rendering is hardcoded to Claude via src/core/brain/claude-memory-render.ts (renderPreferenceFromMemory and the claude-memory-* parser/plan/manifest flow). Introduce a backend protocol boundary so brain operations that today assume Claude's memory format can support alternative agent runtimes without modifying core code. Upstream pattern (memclaw v1.2.0/v2.0.0): a pluggable AgentBackend protocol, each backend a self-contained module, selection by configuration, no changes to core/tools/handlers when adding a backend.++## Task 3 (t_936a1a61) - Cross-agent shared memory namespace++Opt-in cross-agent shared brain: a configuration key makes explicit remember-writes mirror to a shared namespace so facts learned by one agent become visible to other agents sharing that namespace. Per-agent attribution via source metadata. Mirror failures are swallowed - they must never break the primary write. Default off = zero behavior change. OSB context: multi-vault profiles exist (pointer-based, no symlinks, Syncthing-friendly), source-agent metadata exists.++## Task 4 (t_0cc6fdff) - Multi-persona decision panel++Structured multi-persona deliberation on a decision topic: distinct analytical lenses (technical, strategic, risk, user-experience) with synthesis into a structured output. OSB constraint: no LLM inside the core, so the panel must be provider-agnostic - plausible shape: persona definitions as markdown in Brain/personas/, and the panel runs AS a write-session (Task 1 protocol) where OSB returns per-persona prompts and the calling agent supplies per-persona answers plus a synthesis, which OSB validates and commits as a structured decision note.++# Project context++Open Second Brain - TypeScript on Bun, plus a thin Python provider layer. Markdown/Obsidian vault is the storage; an MCP server (65 advertised tools) and an `o2b` CLI are the surfaces. v0.40.0 just shipped (Project History Suite).++Recent commits:+7733f20 feat: Project History Suite - git history memory, ADR mining, architecture notes, query telemetry (#71)+8e8c0bc feat: Memory Observability Suite - versioned continuity contract, lazy telemetry, ATOF/ATIF export, recall benchmark (#70)+eb56c9f feat: Workspace Insight Suite - project pointers, cross-vault recall, trigger queue, proactive synthesis (#69)+707197a feat: Agent Surface Suite - skills over MCP, two-pass tool catalog, surface profiles, session lifecycle (#68)+eda202d feat: Embedding Provider Suite - local embedder, provider registry, cost gate, RRF fusion (#67)+dee5ab7 feat: Memory Integrity Suite - canonical entities, conflict-free log shards, capture boundaries, fact extraction (#66)++Related files:+- src/core/brain/claude-memory-render.ts (renderPreferenceFromMemory, slugifyMemoryName), claude-memory-parser.ts, claude-memory-plan.ts, claude-memory-manifest.ts, claude-memory-paths.ts+- src/core/brain/signal.ts (writeSignal -> Brain/inbox), note.ts + log.ts (appendLogEvent -> Brain/log/<date>.md + JSONL sidecar) - the single write chokepoints+- src/core/brain/preference-txn.ts (writePreferenceTxn: lockfile + expectation gates, the preference write chokepoint)+- src/core/brain/schema-pack.ts (loadSchemaPack from Brain/_brain.yaml), schema-contracts.ts (BrainSchemaContract, SchemaValidationResult {ok, errors[]})+- src/core/brain/payload-registry.ts (content-addressed blob store under Brain/.payloads/), continuity/store.ts (append-only JSONL shards, idempotent)+- src/core/config.ts (discoverConfig, parseSimpleYaml - dependency-free key:value parser, resolveVault), src/core/brain/portability/profiles.ts (multi-vault profiles.json, pointer-based activation)+- src/mcp/tools.ts (ToolDefinition, buildToolTable with scopes full/writer/catalog), src/mcp/brain-tools.ts+- src/cli/brain.ts + src/cli/brain/verbs/* + help-text.ts + command-manifest.ts (CLI verb pattern)++Conventions:+- Deterministic core: no LLM call inside OSB, ever. Agents do generation; OSB validates and commits.+- All vault writes atomic (temp + rename), append-only JSONL where possible, Syncthing-friendly (no symlinks, idempotent re-runs).+- On-disk JSON uses snake_case fields; TypeScript uses camelCase.+- Fail-soft on read (malformed lines skipped), fail-closed on write (validation before any byte lands).+- bun:test, fixtures in tmp vaults; every feature gets CLI + (where agent-facing) MCP surface + tests.+- MCP contract is additive-only; currently 65 advertised tools, growth must be deliberate.++Constraints:+- No new external dependencies (stdlib + Bun only).+- Do not change existing public APIs or record shapes; additive changes only.+- Sessions/state must survive process restarts (file-backed, not in-memory).+- Mirror/shared-namespace writes must be fail-soft; write-session commits must be fail-closed.+- The decision panel must not require any new LLM plumbing in OSB.++# 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/agent-write-contract-suite/design.md b/docs/brainstorm/agent-write-contract-suite/design.mdnew file mode 100644index 00000000..859be095--- /dev/null+++ b/docs/brainstorm/agent-write-contract-suite/design.md@@ -0,0 +1,56 @@+# Agent Write Contract Suite - provider-agnostic write sessions, backend boundary, shared namespace, decision panel++**Status:** accepted+**Author:** claude-dev-agent (via feature-release-playbook)+**Audience:** implementation++## Problem statement++External agents need to propose structured Brain artifacts, but OSB has no agent-facing write lifecycle: validation can reject malformed output, yet there is no session that tells the caller what to generate, returns machine-readable correction errors without losing state, caps retries, guards path collisions, and only commits when the artifact satisfies schema and safety rules. Three adjacent gaps share the same theme: memory rendering is hardcoded to the Claude format with no backend seam, writes by one agent are invisible to sibling agents even when the operator wants a shared substrate, and there is no structured multi-persona deliberation surface. All four must land without putting an LLM inside the deterministic core.++## Scope++- One file-backed write-session kernel (`src/core/brain/write-session/`): session store with TTL and retry cap, JSON envelopes (`needs-llm-step`, `needs-correction`, `needs-review`, `done`, `failed`), artifact validation with machine-readable errors and a compact correction prompt, path-collision guard requiring explicit overwrite/merge intent, operator approval step, audit trail through the existing log chokepoint. (t_bc36a8a2)+- Decision panel as a session kind riding the same kernel: persona definitions in `Brain/personas/` with a built-in default lens set, per-persona prompt steps, a synthesis step, and a committed structured decision note. The calling agent supplies every generated text; OSB sequences, validates, and commits. (t_0cc6fdff)+- Memory-source backend boundary (`src/core/brain/agent-backend/`): a `MemorySourceBackend` protocol plus registry, with the existing `claude-memory-*` flow wrapped as the first backend and config-driven selection. Behavior with the default backend is byte-identical to today. (t_53f9f67f)+- Cross-agent shared namespace (`src/core/brain/shared-namespace.ts`): an opt-in config key that mirrors explicit remember-writes (signals and notes) into a second vault namespace with per-agent attribution and origin metadata; mirror failures never break the primary write. (t_936a1a61)+- CLI verbs `o2b brain session ...` and `o2b brain panel ...`; one new MCP tool `brain_write_session` (kind discriminator covers artifact and panel sessions).++## Out of scope++- Any LLM call inside OSB - generation always belongs to the calling agent.+- Bidirectional sync or conflict resolution for the shared namespace (mirror is one-way, append-style).+- Non-Claude memory backends beyond the protocol + registry + Claude adapter (a second adapter ships when a real format is in hand).+- Merge semantics that rewrite existing artifact content (merge intent appends a clearly delimited section; full three-way merge is deferred).+- Schema-pack mutations or new validation grammar - sessions validate against the existing schema-pack vocabulary and frontmatter contracts.++## Chosen approach++Consultant Variant 1 (unified session kernel), accepted with containment refinements. One generic write-session state machine is the literal deliverable of t_bc36a8a2; the decision panel is a session kind on that kernel (persona loading plus a synthesis schema), not a second lifecycle. The backend boundary stays a deliberately narrow seam around the memory-import flow - the session kernel does NOT consult backends (refinement against speculative coupling). The shared namespace is an independent fail-soft hook at the existing `writeSignal`/`appendLogEvent` chokepoints, invoked by the surface handlers after the primary write succeeds.++## Design decisions++- **Session storage**: one JSON file per session under `Brain/.sessions/write/<id>.json` (snake_case fields), atomic writes, consistent with `Brain/.payloads/`. Survives restarts; Syncthing-friendly (no symlinks, no in-place rewrites beyond atomic replace).+- **Lazy TTL**: expiry is evaluated on read (an expired session reads as `failed` with reason `expired`); a `sweep` operation deletes terminal and expired files. No daemon.+- **Envelope grammar**: every operation returns `{status, session_id, kind, step, prompt, schema_hints, errors, attempts_left, expires_at, existing}` - stable JSON, documented, no optional surprises. `errors` entries are `{code, path, message}`.+- **Retry cap**: default 3 submits per step; exhaustion is terminal `failed`. Validation failure preserves session state (the correction loop never loses the target or schema).+- **Collision guard**: opening an artifact session against an existing path returns `existing` metadata (byte length, content hash, first heading); submit commits only when the session was opened with explicit `overwrite` or `merge` intent. Merge appends a delimited section, never rewrites existing bytes.+- **Reserved-deny and review policy**: targets must resolve inside `Brain/` with no traversal; `Brain/preferences/`, `Brain/log/`, `Brain/.sessions/`, `Brain/.payloads/`, and `Brain/_brain.yaml` are denied outright. A session opened with `require_review: true` stops at `needs-review` after validation; `approve` is a separate operator-side operation. Review is an explicit per-session flag, not a namespace list - panel sessions commit their own decision notes without review unless opened with the flag.+- **Audit**: terminal sessions (done, failed, abandoned, approved) append one `write_session` event through `appendLogEvent` - the JSONL sidecar and dream visibility come for free.+- **Panel personas**: `Brain/personas/<slug>.md` with frontmatter (`kind: persona`, `lens`); when the directory is absent the built-in default set (technical, strategic, risk, user-experience) is used. Panel steps are deterministic: personas in declared order, then `synthesis`. The committed note lands at `Brain/decisions/panels/panel-<date>-<topic-slug>.md` with per-persona sections and the synthesis.+- **Backend protocol**: `MemorySourceBackend` exposes `id`, `discoverMemoryPaths`, `parseMemories`, `renderPreference`. The registry is a frozen map; selection reads the `memory_backend` config key (default `claude`); an unknown id fails with the registered list. The Claude adapter delegates to the existing `claude-memory-*` modules - no logic moves, no public API changes.+- **Shared namespace key**: `shared_namespace: <absolute path>` in the device config (`config.yaml`), matching how `vault:` itself is device-level. Empty or missing means off - zero behavior change. Mirrored records carry `origin_vault` (basename of the primary vault) next to the existing agent attribution; mirror outcome surfaces as `mirror: "ok" | "failed" | "off"` in tool results but never throws.+- **MCP growth**: exactly one new tool (`brain_write_session`, op + kind discriminators), advertised count 65 -> 66. The panel gets CLI sugar (`o2b brain panel`), not a second tool.++## File changes++New: `src/core/brain/write-session/{types,store,validate,engine,panel,personas}.ts`, `src/core/brain/agent-backend/{types,registry,claude}.ts`, `src/core/brain/shared-namespace.ts`, `src/cli/brain/verbs/{session,panel}.ts`, tests under `tests/core/brain/write-session/`, `tests/core/brain/agent-backend.test.ts`, `tests/core/brain/shared-namespace.test.ts`, `tests/cli/{brain-session,brain-panel}.test.ts`, `tests/mcp/brain-write-session.test.ts`, `tests/e2e/agent-write-contract.integration.test.ts`.++Modified: `src/mcp/brain-tools.ts` (new tool), `src/mcp/tools.ts` (table), MCP contract tests asserting tool count, `src/cli/brain.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain/help-text.ts`, `src/cli/command-manifest.ts`, the import-claude-memory verb (backend selection seam, default unchanged), MCP `brain_feedback`/`brain_note` handlers and CLI feedback/note verbs (mirror hook), `README.md`, `CHANGELOG.md`, `docs/cli-reference.md`, `docs/how-it-works.md`.++## Risks and open questions++- The kernel must serve both artifact and panel flows without leaking panel needs into the envelope - mitigated by a `kind` discriminator and panel-only fields kept inside the session record, not the envelope grammar.+- Import-flow wiring through the backend registry must stay byte-identical for the default backend - covered by regression tests comparing rendered output before and after the seam.+- Mirror writes into a second vault could surprise dream passes there - mirrored records are ordinary signals/notes with attribution, which is exactly the upstream semantic (shared facts become first-class in the shared substrate).+- Session files are vault-synced; concurrent submits from two devices could race - last-write-wins on the session file is acceptable for v1 and recorded in docs; commits themselves stay atomic and validated.diff --git a/docs/brainstorm/agent-write-contract-suite/plan.md b/docs/brainstorm/agent-write-contract-suite/plan.mdnew file mode 100644index 00000000..01d4c58d--- /dev/null+++ b/docs/brainstorm/agent-write-contract-suite/plan.md@@ -0,0 +1,53 @@+# Agent Write Contract Suite - implementation plan++## Tasks++### Task 1: write-session store and types+- **Files**: `src/core/brain/write-session/types.ts`, `src/core/brain/write-session/store.ts`, `tests/core/brain/write-session/store.test.ts`+- **Acceptance**: session records round-trip through `Brain/.sessions/write/<id>.json` (snake_case on disk, camelCase in TS); id allocation is collision-safe; lazy TTL turns an expired record into terminal `failed` with reason `expired` on read; `sweepSessions` removes terminal and expired files; corrupted session files read as a probe error, never throw.+- **Depends on**: none++### Task 2: artifact validation and target policy+- **Files**: `src/core/brain/write-session/validate.ts`, `tests/core/brain/write-session/validate.test.ts`+- **Acceptance**: target paths must resolve inside `Brain/` (traversal and absolute escapes rejected); reserved namespaces (`Brain/preferences/`, `Brain/log/`, `Brain/.sessions/`, `Brain/.payloads/`, `Brain/_brain.yaml`) are denied with coded errors; artifacts validate frontmatter shape, declared schema-pack type/tag vocabulary, and size caps; every failure is `{code, path, message}`; a compact correction prompt is built from the error list.+- **Depends on**: Task 1++### Task 3: session engine - lifecycle, correction loop, collision guard, audit+- **Files**: `src/core/brain/write-session/engine.ts`, `tests/core/brain/write-session/engine.test.ts`+- **Acceptance**: `openArtifactSession` returns a `needs-llm-step` envelope with prompt and schema hints, and `existing` metadata (length, content hash, first heading) when the target exists; `submitArtifact` returns `needs-correction` with errors and decremented `attempts_left` on validation failure, terminal `failed` at the retry cap, `needs-review` when review is required, and `done` with an atomic commit otherwise; commits against an existing path require the session's explicit `overwrite` or `merge` intent (merge appends a delimited section); `approveSession` commits a reviewed artifact; `abandonSession` is terminal; every terminal transition appends one `write_session` event via `appendLogEvent`.+- **Depends on**: Tasks 1, 2++### Task 4: decision panel kind - personas, steps, synthesis, committed note+- **Files**: `src/core/brain/write-session/personas.ts`, `src/core/brain/write-session/panel.ts`, `tests/core/brain/write-session/panel.test.ts`+- **Acceptance**: personas load from `Brain/personas/*.md` (frontmatter `kind: persona`, `lens`) with the built-in default set (technical, strategic, risk, user-experience) when the directory is absent; `openPanelSession` walks deterministic steps `persona:<slug>` in order then `synthesis`, each envelope carrying that step's prompt; per-step submits validate non-empty bounded text and reuse the kernel correction loop; the final commit renders `Brain/decisions/panels/panel-<date>-<topic-slug>.md` with frontmatter, per-persona sections, and the synthesis; the panel adds no new envelope fields.+- **Depends on**: Task 3++### Task 5: memory-source backend boundary+- **Files**: `src/core/brain/agent-backend/types.ts`, `src/core/brain/agent-backend/registry.ts`, `src/core/brain/agent-backend/claude.ts`, `tests/core/brain/agent-backend.test.ts`+- **Acceptance**: `MemorySourceBackend` protocol (`id`, `discoverMemoryPaths`, `parseMemories`, `renderPreference`); frozen registry with `claude` registered; `resolveMemoryBackend` reads the `memory_backend` config key, defaults to `claude`, and fails on unknown ids with the registered list in the message; the Claude adapter delegates to existing `claude-memory-*` modules and its rendered output is byte-identical to calling them directly; the import flow resolves through the registry with unchanged default behavior.+- **Depends on**: none++### Task 6: cross-agent shared namespace mirror+- **Files**: `src/core/brain/shared-namespace.ts`, `tests/core/brain/shared-namespace.test.ts`, mirror hooks in `src/mcp/brain-tools.ts` (`brain_feedback`, `brain_note`) and `src/cli/brain/verbs/` feedback/note paths+- **Acceptance**: `resolveSharedNamespace` reads the `shared_namespace` config key (missing/empty = off); `mirrorSignal`/`mirrorNote` write the same record into the shared vault with `origin_vault` attribution alongside the agent identity; any mirror failure is swallowed and reported as `mirror: "failed"` while the primary write result is untouched; default-off means byte-identical behavior for existing setups; tool and CLI results carry `mirror: "ok" | "failed" | "off"` only when the feature is configured; unconfigured setups stay silent.+- **Depends on**: none++### Task 7: CLI verbs - session and panel+- **Files**: `src/cli/brain/verbs/session.ts`, `src/cli/brain/verbs/panel.ts`, `src/cli/brain/verbs/index.ts`, `src/cli/brain.ts`, `src/cli/brain/help-text.ts`, `src/cli/command-manifest.ts`, `tests/cli/brain-session.test.ts`, `tests/cli/brain-panel.test.ts`+- **Acceptance**: `o2b brain session open|submit|approve|abandon|status|list|sweep` and `o2b brain panel open|submit|status` drive the kernel end-to-end with `--json` envelopes; artifact bodies come from `--file` or stdin; errors exit 1 with the envelope on stdout; help text and command manifest list both verbs.+- **Depends on**: Tasks 3, 4++### Task 8: MCP tool brain_write_session+- **Files**: `src/mcp/brain-tools.ts`, `src/mcp/tools.ts`, contract tests asserting the advertised tool count, `tests/mcp/brain-write-session.test.ts`+- **Acceptance**: one tool with `op` (`open|submit|approve|abandon|status|list`) and `kind` (`artifact|panel`) discriminators returning the same envelopes as the CLI; advertised count moves 65 -> 66 in full scope and contract tests are updated deliberately; writer scope is unchanged.+- **Depends on**: Tasks 3, 4++### Task 9: end-to-end integration test+- **Files**: `tests/e2e/agent-write-contract.integration.test.ts`+- **Acceptance**: one flow per feature against a real tmp vault: artifact session open -> invalid submit -> correction envelope -> valid submit -> committed file plus audit event; panel open -> four persona submits -> synthesis -> committed decision note; backend registry resolves claude and renders a preference; shared namespace mirrors a signal and a note with attribution while a broken shared path degrades to `mirror: "failed"` without harming the primary write.+- **Depends on**: Tasks 3, 4, 5, 6++### Task 10: docs+- **Files**: `README.md`, `CHANGELOG.md`, `docs/cli-reference.md`, `docs/how-it-works.md`+- **Acceptance**: CHANGELOG `[0.41.0]` entry; README capability sentence; CLI reference section for `brain session` and `brain panel`; how-it-works section describing the write-session contract and the no-LLM-in-core rule it preserves.+- **Depends on**: Tasks 1-9diff --git a/docs/brainstorm/agent-write-contract-suite/variants.md b/docs/brainstorm/agent-write-contract-suite/variants.mdnew file mode 100644index 00000000..8d992fef--- /dev/null+++ b/docs/brainstorm/agent-write-contract-suite/variants.md@@ -0,0 +1,51 @@+# Agent Write Contract Suite - variants audit trail++Consultant: Claude Code (`claude -p`), primary, single run, no fallback needed.+Prompt: `cli-output/prompt.md`. Raw output: `cli-output/claude.md` (verbatim copy below).++## Consultant output (verbatim)++### Variant 1: Unified session kernel+- **Approach**: Build one generic, file-backed write-session state machine in `core/brain/session/` (envelope with `status`/`session_id`/`step`, TTL + retry store, audit log) that is the literal deliverable of Task 1. Task 4's decision panel becomes a session *kind* (`panel`) riding the same kernel - OSB emits per-persona prompts as steps and validates the synthesis on submit - so it needs no parallel lifecycle. Task 2 stays a narrow `AgentBackend` boundary the session consults for render/validation strategy; Task 3 is an independent fail-soft mirror hooked at the existing `signal`/`note`/`preference-txn` chokepoints.+- **Trade-offs**:+ - Pro: TTL, retry cap, collision metadata, and audit log are built exactly once and shared by both agent-facing flows.+ - Pro: Task 4 collapses to persona-loading + a synthesis schema, since it inherits the correction loop and operator-gate (`needs-review`) for free.+ - Pro: Fewer new MCP tools (one session surface with a `kind` discriminator) keeps the 65-tool growth deliberate.+ - Con: Kernel must be generic enough on day one to serve both an artifact-write and a multi-step panel - some up-front design tax.+ - Con: Couples panel and write-session evolution; a panel-specific need could leak into the shared envelope.+- **Complexity**: medium+- **Risk**: low++### Variant 2: Four independent modules sharing only contracts+- **Approach**: Ship each task as a self-contained module sharing nothing but type contracts (`SchemaValidationResult`, envelope types). Write-session, backend registry, shared-namespace mirror, and decision panel each own their store, surface, and tests; the panel calls the write-session as a library but persists to its own state. Each module maps one-to-one to a kanban task.+- **Trade-offs**:+ - Pro: Independently shippable, testable, and revertable - clean blast-radius isolation per task.+ - Pro: Strongly additive; no module reshapes another's write path, fitting the "additive-only" and fail-closed/fail-soft split naturally.+ - Pro: Lowest design risk - no premature generalization.+ - Con: Session lifecycle, TTL, retry, and audit logic get duplicated (or near-duplicated) between Task 1 and the panel.+ - Con: More MCP tools and two session-ish state machines that can drift apart over time.+- **Complexity**: medium+- **Risk**: low++### Variant 3: Backend-protocol-first (everything is a backend capability)+- **Approach**: Make Task 2's `AgentBackend` protocol the central abstraction and route the write-session, persona panel, and shared-namespace mirroring through it as backend-dispatched capabilities. The Claude memory render becomes the first backend; selection is config-driven, and all agent-write behavior is expressed as capabilities a backend declares.+- **Trade-offs**:+ - Pro: Maximum extensibility - a future runtime gains write-session, panel, and mirror behavior through one seam.+ - Pro: Single dispatch point for all agent-facing format concerns.+ - Con: Over-abstraction when only one backend (Claude) exists; the deterministic-core rule means backends are format adapters, not generation engines, so the seam carries little real variation today.+ - Con: Largest refactor - pulls the `claude-memory-*` flow and core write paths under a new boundary, straining the "do not change existing public APIs / additive-only" constraint.+ - Con: High YAGNI risk; couples four independently-valuable tasks to one speculative abstraction.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 1+**Rationale**: Task 4 is specified to run *as* a write-session, so a shared session kernel turns the panel into a thin persona-and-synthesis layer instead of a second state machine - the strongest reuse for the least surface, which directly serves the deliberate-MCP-growth and no-LLM-in-core constraints. It keeps Task 2 as a deliberately narrow render/validation boundary and Task 3 as a fail-soft hook at the existing chokepoints, avoiding both the duplication of Variant 2 and the premature, core-reshaping generalization of Variant 3.++## Orchestrator decision++Variant 1 accepted, with two containment refinements against the consultant's literal text:++1. **The session kernel does not consult backends.** The consultant suggested Task 2 as "a boundary the session consults for render/validation strategy" - that is speculative coupling with no consumer today. The backend boundary stays scoped to the memory-import flow (`claude-memory-*`); the write-session validates against schema-pack contracts directly. If a real second runtime ever needs format-specific session validation, the seam can grow then.+2. **Module path is `src/core/brain/write-session/`, not `core/brain/session/`.** The repo already has `session-lifecycle.ts`, `session-recall.ts`, `session-scope.ts`, and `sessions/` (import adapters); an unqualified `session/` directory would collide with that vocabulary.++Variant 2 was the runner-up; its decisive flaw is the duplicated lifecycle between the artifact flow and the panel (two TTL/retry/audit implementations drifting apart). Variant 3 was rejected on YAGNI and on the additive-only constraint it admits to straining.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex b574a0b4..6d887551 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -157,6 +157,21 @@ o2b brain architect <project-path> - deterministic stdlib-only projectAll flags accept `--vault V` and `--json`. The ingest never modifies the scanned repository; every caller-supplied sha is validated against the full-40-hex grammar before it can reach a git argument.+### Agent write sessions (since v0.41.0)++```text+o2b brain session open --target <Brain/...md> [--schema-type S] [--intent create|overwrite|merge] [--prompt P] [--require-review] [--retry-cap N] - open an artifact write session; the envelope carries the generation prompt, schema hints, and collision metadata for an occupied target+ submit <id> [--file F|-] - submit the generated artifact (stdin without --file); done | needs-correction with coded errors and a compact correction prompt | needs-review+ approve <id> - operator-side commit of a needs-review session+ abandon <id> - terminal abandon+ status <id> | list | sweep - inspect or clean the session store (Brain/.sessions/write/, lazy TTL default 24h)+o2b brain panel open <topic...> [--personas a,b,c] [--target T] [--require-review] - convene a decision panel; personas from Brain/personas/ (built-in defaults: technical, strategic, risk, user-experience)+ submit <id> [--file F|-] - answer the current persona step or the synthesis; the committed note lands under Brain/decisions/panels/+ status <id> - live envelope of a panel session+```++Envelopes are stable JSON with `--json` (`status`, `step`, `prompt`, `errors`, `attempts_left`, `expires_at`, `target_path`, `existing`) - the same contract the MCP `brain_write_session` tool returns. `create` intent never overwrites an existing target; `merge` appends a session-stamped delimited section; reserved namespaces (`Brain/preferences/`, `Brain/log/`, `Brain/_brain.yaml`, dot-stores) are refused. The Brain never generates content - the calling agent does.+## Vault scopeSingle exclusion policy for every vault walker.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 6eacb468..6d1832d6 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -933,6 +933,18 @@ observability gap v0.39.0 left open: `brain_query` now emits opt-inrecall telemetry with a kind-only payload, so the supplied preferenceid, topic, or timestamp never lands in a continuity record.+## The agent write contract (since v0.41.0)++The Brain core stays deterministic - no LLM ever runs inside it. The write-session protocol is how that rule survives contact with agents that need to PROPOSE structured artifacts: schema-typed notes, handoffs, curated summaries, panel deliberations.++A calling agent opens a session and receives a JSON envelope: what to generate (`prompt`), what shape it must satisfy (`schema_hints`), and what already occupies the target (`existing` with byte length, content hash, and first heading). The agent generates and submits; the Brain validates fail-closed. A failing submit returns machine-readable `{code, path, message}` errors plus a compact correction prompt - and the session keeps its state, so the agent fixes and resubmits without losing the target, the schema, or its attempt budget (default 3, then terminal `failed`). A clean submit commits atomically, or parks at `needs-review` when the session was opened with the operator gate. Sessions are plain JSON files under `Brain/.sessions/write/` with lazy TTL: they survive process restarts, sync with the vault, and expire on read instead of by daemon.++Three rules are enforced at the commit boundary, not by convention: `create` intent never overwrites an existing file, `merge` appends a session-stamped delimited section without touching existing bytes, and reserved namespaces (preferences, logs, the schema file, machine stores) are refused before a session even opens. Every terminal transition - committed, failed, abandoned, approved - lands exactly one `write-session` audit event in the Brain log.++The decision panel is the first consumer of the kernel: persona steps (operator-curated notes under `Brain/personas/`, or the built-in technical / strategic / risk / user-experience set) walk in declared order, the synthesis step sees every accepted answer, and the committed decision note under `Brain/decisions/panels/` records who argued what through which lens. The Brain contributes sequencing, validation, and the commit; every word of analysis comes from the calling agent.++Two adjacent seams complete the contract. The memory backend boundary (`memory_backend` config key) routes memory import through a format-adapter registry - the Claude Code adapter is the default and byte-identical to the pre-seam behavior, and a second runtime becomes one self-contained module. The shared namespace (`shared_namespace` config key) mirrors explicit remember-writes into a second vault after the primary write succeeds, attributed by agent and origin vault; mirroring is fail-soft by contract, so a broken shared vault degrades to a reported `mirror: "failed"` and the primary write never notices.+## Safety propertiesThese are invariants of the system, not configuration to enable.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 863fc2c6..00044276 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "0.40.0",+ "version": "0.41.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 138d2f0f..43e80899 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.40.0",+ "version": "0.41.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex ebe52026..c4ea9af2 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.40.0"+version: "0.41.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 5479908c..b12f1a25 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.40.0",+ "version": "0.41.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex ebe52026..c4ea9af2 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.40.0"+version: "0.41.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex c843eec2..d39a9a8d 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "0.40.0"+version = "0.41.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex c2b6afff..fd1a743d 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -61,6 +61,8 @@ import {cmdBrainBench,cmdBrainGit,cmdBrainArchitect,+ cmdBrainSession,+ cmdBrainPanel,cmdBrainTrigger,cmdBrainDeepSynthesis,cmdBrainIdeas,@@ -208,6 +210,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainGit(rest);case "architect":return await cmdBrainArchitect(rest);+ case "session":+ return await cmdBrainSession(rest);+ case "panel":+ return await cmdBrainPanel(rest);case "trigger":return await cmdBrainTrigger(rest);case "deep-synthesis":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 1bb0c7d9..92f70919 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -92,6 +92,8 @@ Brain verbs (observing memory):bench Memory quality benchmark over a disposable fixture vaultgit Git history as project memory: ingest, status, find, minearchitect Deterministic architecture notes for a code project+ session Agent write sessions: open, submit, approve, abandon, status, list, sweep+ panel Multi-persona decision panel riding the write-session kernelCommon flags:--vault <path> Override the configured vault@@ -546,6 +548,21 @@ export const VERB_HELP: Record<string, string> = {"Read-only trajectory export of the continuity store. atof renders one\n" +"JSONL event stream; atif renders one trajectory document per session.\n" +"Records flagged private are dropped; redacted text stays masked.\n",+ session:+ "usage: o2b brain session <open|submit|approve|abandon|status|list|sweep> [<session-id>] [flags]\n" ++ "open --target <Brain/...md> [--schema-type S] [--intent create|overwrite|merge]\n" ++ " [--prompt P] [--require-review] [--retry-cap N] open an artifact write session.\n" ++ "submit <id> [--file F|-] submit the generated artifact (stdin without --file).\n" ++ "approve <id> commit a needs-review session. abandon <id> terminal abandon.\n" ++ "status <id> | list | sweep inspect or clean the session store.\n" ++ "Envelopes are JSON with --json: status, step, prompt, errors, attempts_left.",+ panel:+ "usage: o2b brain panel <open <topic...>|submit <id>|status <id>> [flags]\n" ++ "open <topic> [--personas a,b,c] [--target T] [--require-review] convene a\n" ++ "decision panel; personas come from Brain/personas/ (built-in default set:\n" ++ "technical, strategic, risk, user-experience). Each submit answers the\n" ++ "current persona step; after synthesis the decision note commits under\n" ++ "Brain/decisions/panels/. The calling agent generates every word.",architect:"usage: o2b brain architect <project-path> [--vault V] [--json]\n" +"Scan a project tree deterministically (stdlib-only, no LLM) and\n" +diff --git a/src/cli/brain/verbs/feedback.ts b/src/cli/brain/verbs/feedback.tsindex de6b613a..194c2af7 100644--- a/src/cli/brain/verbs/feedback.ts+++ b/src/cli/brain/verbs/feedback.ts@@ -1,5 +1,6 @@import { readFileSync } from "node:fs";import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";+import { mirrorSignal, resolveSharedNamespace } from "../../../core/brain/shared-namespace.ts";import { writeSignal } from "../../../core/brain/signal.ts";import { appendLogEvent } from "../../../core/brain/log.ts";import { writePreference } from "../../../core/brain/preference.ts";@@ -60,23 +61,29 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {const date = (flags["date"] as string | undefined) ?? isoDate(now);const slug = (flags["slug"] as string | undefined) ?? String(flags["topic"]);+ const signalInput = {+ topic: String(flags["topic"]),+ signal: signalSign as "positive" | "negative",+ agent,+ principle: String(flags["principle"]),+ created_at: now.toISOString(),+ date,+ slug,+ ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),+ ...(flags["source"] ? { source: flags["source"] as string[] } : {}),+ ...(raw !== undefined ? { raw } : {}),+ };let sigResult;try {- sigResult = writeSignal(vault, {- topic: String(flags["topic"]),- signal: signalSign as "positive" | "negative",- agent,- principle: String(flags["principle"]),- created_at: now.toISOString(),- date,- slug,- ...(flags["scope"] ? { scope: String(flags["scope"]) } : {}),- ...(flags["source"] ? { source: flags["source"] as string[] } : {}),- ...(raw !== undefined ? { raw } : {}),- });+ sigResult = writeSignal(vault, signalInput);} catch (exc) {return fail(`failed to write signal: ${(exc as Error).message ?? exc}`);}+ // t_936a1a61: fail-soft mirror into the shared namespace AFTER the+ // primary write; surfaced only when the key is configured.+ const sharedNamespace = resolveSharedNamespace(config);+ const mirror =+ sharedNamespace === null ? undefined : mirrorSignal(sharedNamespace, vault, signalInput);try {appendLogEvent(vault, {@@ -134,12 +141,16 @@ export async function cmdBrainFeedback(argv: string[]): Promise<number> {okJson({signal_path: sigResult.path,signal_id: sigResult.id,+ ...(mirror !== undefined ? { mirror } : {}),...(prefResult ? { preference_path: prefResult.path, preference_id: prefResult.id } : {}),});return 0;}ok(`signal: ${sigResult.path}`);ok(`id: ${sigResult.id}`);+ if (mirror !== undefined) {+ ok(`mirror: ${mirror}`);+ }if (prefResult) {ok(`preference: ${prefResult.path}`);ok(`status: confirmed`);diff --git a/src/cli/brain/verbs/import-claude-memory.ts b/src/cli/brain/verbs/import-claude-memory.tsindex 88235578..7529ec97 100644--- a/src/cli/brain/verbs/import-claude-memory.ts+++ b/src/cli/brain/verbs/import-claude-memory.ts@@ -1,6 +1,6 @@import { defaultConfigPath } from "../../../core/config.ts";import { importClaudeMemory, ConflictsError } from "../../../core/brain/import-claude-memory.ts";-import { defaultMemoryDir } from "../../../core/brain/claude-memory-paths.ts";+import { resolveMemoryBackend } from "../../../core/brain/agent-backend/registry.ts";import { resolveBrainVault } from "../helpers.ts";export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number> {@@ -82,7 +82,11 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number}const vault = resolveBrainVault(vaultFlag, config);- const memDir = memory ?? defaultMemoryDir(vault);+ // t_53f9f67f: the memory-format backend is config-selected+ // (`memory_backend`, default claude) - unknown ids fail loudly here,+ // before any filesystem work.+ const backend = resolveMemoryBackend(config);+ const memDir = memory ?? backend.discoverMemoryDir(vault);try {const res = importClaudeMemory({@@ -90,6 +94,7 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<numbermemoryDir: memDir,mode,allowArbitraryMemoryPath: allowArbitrary,+ backend,});if (asJson) {process.stdout.write(JSON.stringify(res, null, 2) + "\n");diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 0a513769..e4c88a44 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -47,6 +47,8 @@ export { cmdBrainContinuity } from "./continuity.ts";export { cmdBrainBench } from "./bench.ts";export { cmdBrainGit } from "./git.ts";export { cmdBrainArchitect } from "./architect.ts";+export { cmdBrainSession } from "./session.ts";+export { cmdBrainPanel } from "./panel.ts";export { cmdBrainTrigger } from "./trigger.ts";export { cmdBrainDeepSynthesis } from "./deep-synthesis.ts";export { cmdBrainIdeas } from "./ideas.ts";diff --git a/src/cli/brain/verbs/panel.ts b/src/cli/brain/verbs/panel.tsnew file mode 100644index 00000000..247ede62--- /dev/null+++ b/src/cli/brain/verbs/panel.ts@@ -0,0 +1,139 @@+/**+ * `o2b brain panel <op>` (Agent Write Contract Suite, t_0cc6fdff):+ * convenience face of the decision-panel session kind. `open` takes+ * the topic as positional text; `submit`/`status` are sugar over the+ * shared session surface for panel-shaped sessions.+ */++import { readFileSync } from "node:fs";++import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";+import {+ WriteSessionRequestError,+ sessionEnvelope,+} from "../../../core/brain/write-session/engine.ts";+import { openPanelSession, submitToPanelSession } from "../../../core/brain/write-session/panel.ts";+import { readWriteSession } from "../../../core/brain/write-session/store.ts";+import type { WriteSessionEnvelope } from "../../../core/brain/write-session/types.ts";+import { fail, ok, okJson, parse, resolveBrainVault } from "../helpers.ts";++const USAGE =+ "usage: o2b brain panel <open <topic...>|submit <session-id>|status <session-id>> " ++ "[--personas a,b,c] [--target T] [--file F] [--require-review] [--agent A] [--vault V] [--json]";++function renderEnvelope(env: WriteSessionEnvelope, asJson: boolean): void {+ if (asJson) {+ // Spread: the readonly envelope interface has no index signature,+ // so it is not assignable to okJson's Record parameter directly.+ okJson({ ...env });+ return;+ }+ ok(`panel session: ${env.session_id}`);+ ok(`status: ${env.status}`);+ ok(`step: ${env.step}`);+ ok(`target: ${env.target_path}`);+ for (const e of env.errors) ok(`error: [${e.code}] ${e.path}: ${e.message}`);+ if (env.status === "needs-llm-step") {+ ok(`prompt: ${env.prompt}`);+ }+}++function exitCode(env: WriteSessionEnvelope): number {+ return env.status === "needs-correction" || env.status === "failed" ? 1 : 0;+}++/** JSON-mode callers get JSON on EVERY failure path, not just envelopes. */+function emitCliError(message: string, asJson: boolean): number {+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+}++export async function cmdBrainPanel(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ personas: { type: "string" },+ target: { type: "string" },+ file: { type: "string" },+ agent: { type: "string" },+ "require-review": { type: "boolean" },+ });+ const op = positional[0];+ const asJson = flags["json"] === true;+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ try {+ switch (op) {+ case "open": {+ const topic = positional.slice(1).join(" ").trim();+ if (!topic) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const personasFlag = flags["personas"] as string | undefined;+ const env = openPanelSession(vault, {+ agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),+ topic,+ requireReview: flags["require-review"] === true,+ ...(personasFlag+ ? {+ personas: personasFlag+ .split(",")+ .map((p) => p.trim())+ .filter((p) => p !== ""),+ }+ : {}),+ ...(flags["target"] ? { targetPath: String(flags["target"]) } : {}),+ });+ renderEnvelope(env, asJson);+ return exitCode(env);+ }+ case "submit": {+ const id = positional[1];+ if (!id) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const fileFlag = flags["file"] as string | undefined;+ const text =+ fileFlag !== undefined && fileFlag !== "-"+ ? readFileSync(fileFlag, "utf8")+ : readFileSync(0, "utf8");+ const env = submitToPanelSession(vault, { sessionId: id, text });+ renderEnvelope(env, asJson);+ return exitCode(env);+ }+ case "status": {+ const id = positional[1];+ if (!id) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const probe = readWriteSession(vault, id, new Date().toISOString());+ if (probe.error !== null) return emitCliError(probe.error, asJson);+ if (probe.session === null) {+ return emitCliError(`unknown write-session: ${id}`, asJson);+ }+ renderEnvelope(sessionEnvelope(probe.session), asJson);+ return 0;+ }+ default: {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ }+ } catch (err) {+ if (err instanceof WriteSessionRequestError) {+ if (asJson) {+ okJson({ ok: false, message: err.message, errors: err.errors });+ return 1;+ }+ return fail(err.message);+ }+ return emitCliError(err instanceof Error ? err.message : String(err), asJson);+ }+}diff --git a/src/cli/brain/verbs/session.ts b/src/cli/brain/verbs/session.tsnew file mode 100644index 00000000..cb846777--- /dev/null+++ b/src/cli/brain/verbs/session.ts@@ -0,0 +1,208 @@+/**+ * `o2b brain session <op>` (Agent Write Contract Suite, t_bc36a8a2):+ * the CLI face of the write-session kernel. Envelopes are printed as+ * JSON with `--json` (the machine contract shared with the MCP tool);+ * the human rendering stays one-line-per-fact.+ *+ * Exit codes: 0 on an accepted operation, 1 when the envelope reports+ * a non-advancing state (needs-correction / failed) or the request was+ * structurally rejected, 2 on usage errors.+ */++import { readFileSync } from "node:fs";++import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";+import {+ WriteSessionRequestError,+ abandonSession,+ approveSession,+ openArtifactSession,+ sessionEnvelope,+} from "../../../core/brain/write-session/engine.ts";+import { dispatchSubmit } from "../../../core/brain/write-session/panel.ts";+import {+ listWriteSessions,+ readWriteSession,+ sweepWriteSessions,+} from "../../../core/brain/write-session/store.ts";+import type {+ WriteSessionEnvelope,+ WriteSessionIntent,+} from "../../../core/brain/write-session/types.ts";+import { fail, ok, okJson, parse } from "../helpers.ts";+import { resolveBrainVault } from "../helpers.ts";++const USAGE =+ "usage: o2b brain session <open|submit|approve|abandon|status|list|sweep> " ++ "[<session-id>] [--target T] [--file F] [--schema-type S] [--intent create|overwrite|merge] " ++ "[--prompt P] [--require-review] [--retry-cap N] [--agent A] [--vault V] [--json]";++function renderEnvelope(env: WriteSessionEnvelope, asJson: boolean): void {+ if (asJson) {+ // Spread: the readonly envelope interface has no index signature,+ // so it is not assignable to okJson's Record parameter directly.+ okJson({ ...env });+ return;+ }+ ok(`session: ${env.session_id} (${env.kind})`);+ ok(`status: ${env.status}`);+ ok(`step: ${env.step}`);+ ok(`target: ${env.target_path}`);+ ok(`attempts left: ${env.attempts_left}`);+ for (const e of env.errors) ok(`error: [${e.code}] ${e.path}: ${e.message}`);+}++/** Mutating ops exit 1 when the envelope reports a non-advancing state. */+function emitEnvelope(env: WriteSessionEnvelope, asJson: boolean): number {+ renderEnvelope(env, asJson);+ return env.status === "needs-correction" || env.status === "failed" ? 1 : 0;+}++function emitRequestError(err: WriteSessionRequestError, asJson: boolean): number {+ if (asJson) {+ okJson({ ok: false, message: err.message, errors: err.errors });+ return 1;+ }+ return fail(+ err.errors.length > 0+ ? `${err.message} (${err.errors.map((e) => e.code).join(", ")})`+ : err.message,+ );+}++/** JSON-mode callers get JSON on EVERY failure path, not just envelopes. */+function emitCliError(message: string, asJson: boolean): number {+ if (asJson) {+ okJson({ ok: false, message });+ return 1;+ }+ return fail(message);+}++function readBody(fileFlag: string | undefined): string {+ if (fileFlag !== undefined && fileFlag !== "-") {+ return readFileSync(fileFlag, "utf8");+ }+ // `--file -` or no flag: read stdin synchronously (agents pipe bodies).+ return readFileSync(0, "utf8");+}++export async function cmdBrainSession(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ json: { type: "boolean" },+ target: { type: "string" },+ file: { type: "string" },+ prompt: { type: "string" },+ agent: { type: "string" },+ intent: { type: "string" },+ "schema-type": { type: "string" },+ "require-review": { type: "boolean" },+ "retry-cap": { type: "string" },+ });+ const op = positional[0];+ const asJson = flags["json"] === true;+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);++ try {+ switch (op) {+ case "open": {+ const target = flags["target"] as string | undefined;+ if (!target) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const intentRaw = (flags["intent"] as string | undefined) ?? "create";+ if (intentRaw !== "create" && intentRaw !== "overwrite" && intentRaw !== "merge") {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const retryCapRaw = flags["retry-cap"] as string | undefined;+ const env = openArtifactSession(vault, {+ agent: (flags["agent"] as string | undefined) ?? resolveAgentName(config),+ targetPath: target,+ intent: intentRaw as WriteSessionIntent,+ requireReview: flags["require-review"] === true,+ ...(flags["prompt"] ? { prompt: String(flags["prompt"]) } : {}),+ ...(flags["schema-type"] ? { schemaType: String(flags["schema-type"]) } : {}),+ ...(retryCapRaw !== undefined ? { retryCap: Number(retryCapRaw) } : {}),+ });+ return emitEnvelope(env, asJson);+ }+ case "submit": {+ const id = positional[1];+ if (!id) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const env = dispatchSubmit(vault, {+ sessionId: id,+ text: readBody(flags["file"] as string | undefined),+ });+ return emitEnvelope(env, asJson);+ }+ case "approve":+ case "abandon": {+ const id = positional[1];+ if (!id) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const env =+ op === "approve"+ ? approveSession(vault, { sessionId: id })+ : abandonSession(vault, { sessionId: id });+ return emitEnvelope(env, asJson);+ }+ case "status": {+ const id = positional[1];+ if (!id) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ const probe = readWriteSession(vault, id, new Date().toISOString());+ if (probe.error !== null) return emitCliError(probe.error, asJson);+ if (probe.session === null) {+ return emitCliError(`unknown write-session: ${id}`, asJson);+ }+ // A status QUERY always exits 0 - the envelope carries the state.+ renderEnvelope(sessionEnvelope(probe.session), asJson);+ return 0;+ }+ case "list": {+ const sessions = listWriteSessions(vault, new Date().toISOString());+ if (asJson) {+ okJson({ sessions: sessions.map((s) => sessionEnvelope(s)) });+ return 0;+ }+ if (sessions.length === 0) {+ ok("no write-sessions");+ return 0;+ }+ for (const s of sessions) {+ ok(`${s.id} ${s.kind} ${s.status} ${s.targetPath}`);+ }+ return 0;+ }+ case "sweep": {+ const res = sweepWriteSessions(vault, new Date().toISOString());+ if (asJson) {+ okJson({ removed: res.removed, kept: res.kept });+ return 0;+ }+ ok(`sweep: ${res.removed} removed, ${res.kept} kept`);+ return 0;+ }+ default: {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ }+ } catch (err) {+ if (err instanceof WriteSessionRequestError) {+ return emitRequestError(err, asJson);+ }+ return emitCliError(err instanceof Error ? err.message : String(err), asJson);+ }+}diff --git a/src/cli/command-manifest.ts b/src/cli/command-manifest.tsindex 2e328eba..6194f7d6 100644--- a/src/cli/command-manifest.ts+++ b/src/cli/command-manifest.ts@@ -161,6 +161,11 @@ export const CLI_COMMAND_MANIFEST: CliRootManifest = Object.freeze({command("bench", "Memory quality benchmark over a disposable fixture vault"),command("git", "Git history as project memory: ingest, status, find, mine"),command("architect", "Deterministic architecture notes for a code project"),+ command(+ "session",+ "Agent write sessions: open, submit, approve, abandon, status, list, sweep",+ ),+ command("panel", "Multi-persona decision panel riding the write-session kernel"),command("trigger", "Grounded proactive trigger queue (scan/list/ack/dismiss/act/history)"),command("deep-synthesis", "Topic dossier: agreements, contradictions, stale claims, gaps"),command("ideas", "Ranked next-direction candidates from open loops"),diff --git a/src/core/brain/agent-backend/claude.ts b/src/core/brain/agent-backend/claude.tsnew file mode 100644index 00000000..09e9aad8--- /dev/null+++ b/src/core/brain/agent-backend/claude.ts@@ -0,0 +1,31 @@+/**+ * Claude Code memory backend (Agent Write Contract Suite, t_53f9f67f).+ *+ * Pure delegation to the existing `claude-memory-*` modules - no logic+ * moves, no behavior changes. The adapter exists so the import flow+ * resolves its format functions through the registry seam; with the+ * default backend the output stays byte-identical to calling the+ * modules directly (regression-tested).+ */++import { defaultMemoryDir } from "../claude-memory-paths.ts";+import { parseClaudeMemoryFile } from "../claude-memory-parser.ts";+import { renderPreferenceFromMemory, slugifyMemoryName } from "../claude-memory-render.ts";+import type { MemoryRenderInput, MemorySourceBackend, MemorySourceParse } from "./types.ts";++export const claudeMemoryBackend: MemorySourceBackend = Object.freeze({+ id: "claude",+ label: "Claude Code",+ discoverMemoryDir(vault: string): string {+ return defaultMemoryDir(vault);+ },+ parseMemoryFile(text: string): MemorySourceParse {+ return parseClaudeMemoryFile(text);+ },+ renderPreference(input: MemoryRenderInput): string {+ return renderPreferenceFromMemory(input);+ },+ slugifyName(name: string): string {+ return slugifyMemoryName(name);+ },+});diff --git a/src/core/brain/agent-backend/registry.ts b/src/core/brain/agent-backend/registry.tsnew file mode 100644index 00000000..ccfc9d35--- /dev/null+++ b/src/core/brain/agent-backend/registry.ts@@ -0,0 +1,45 @@+/**+ * Memory backend registry (Agent Write Contract Suite, t_53f9f67f).+ *+ * Frozen map of registered format adapters with config-driven+ * selection: the `memory_backend` device-config key picks the backend,+ * `claude` is the default, and an unknown id fails loudly with the+ * registered list - never a silent fallback to the wrong format.+ */++import { discoverConfig } from "../../config.ts";+import { claudeMemoryBackend } from "./claude.ts";+import type { MemorySourceBackend } from "./types.ts";++export const DEFAULT_MEMORY_BACKEND_ID = "claude";++const REGISTRY: ReadonlyMap<string, MemorySourceBackend> = new Map([+ [claudeMemoryBackend.id, claudeMemoryBackend],+]);++/** Registered backends in registration order. */+export function listMemoryBackends(): ReadonlyArray<MemorySourceBackend> {+ return Object.freeze([...REGISTRY.values()]);+}++/** Backend by id; throws with the registered list on an unknown id. */+export function getMemoryBackend(id: string): MemorySourceBackend {+ const backend = REGISTRY.get(id);+ if (backend === undefined) {+ throw new Error(+ `unknown memory backend '${id}' - registered: ${[...REGISTRY.keys()].join(", ")}`,+ );+ }+ return backend;+}++/**+ * Resolve the active backend from the device config. A missing config+ * file or absent key means the default - existing setups see zero+ * behavior change.+ */+export function resolveMemoryBackend(configPath?: string | null): MemorySourceBackend {+ const discovery = discoverConfig(configPath ?? undefined);+ const id = discovery.data["memory_backend"]?.trim() || DEFAULT_MEMORY_BACKEND_ID;+ return getMemoryBackend(id);+}diff --git a/src/core/brain/agent-backend/types.ts b/src/core/brain/agent-backend/types.tsnew file mode 100644index 00000000..f0e6ca01--- /dev/null+++ b/src/core/brain/agent-backend/types.ts@@ -0,0 +1,58 @@+/**+ * Memory-source backend protocol (Agent Write Contract Suite,+ * t_53f9f67f).+ *+ * The seam that decouples "import an agent runtime's memory into Brain+ * preferences" from the Claude Code memory format. A backend is a+ * self-contained format adapter: it knows where the runtime keeps its+ * memory files, how to parse one, and how to render a parsed entry as+ * a Brain preference. Adding a runtime means adding ONE module that+ * satisfies this interface and registering it - no changes to the+ * import core, CLI, or MCP surfaces (the memclaw v1.2.0 pattern).+ *+ * Deliberately narrow: backends are FORMAT adapters, not generation+ * engines - the deterministic-core rule means there is nothing+ * provider-specific to dispatch beyond parsing and rendering. The+ * write-session kernel does NOT consult backends (design decision:+ * no speculative coupling).+ */++/** Parsed memory entry - structurally the claude-memory parse result. */+export type MemorySourceParse =+ | {+ readonly kind: "feedback";+ readonly name: string;+ readonly description: string;+ readonly body: string;+ readonly bodySha256: string;+ }+ | {+ readonly kind: "skip";+ readonly skipReason: string;+ };++/** Render input - structurally the claude-memory render input. */+export interface MemoryRenderInput {+ readonly name: string;+ readonly description: string;+ readonly body: string;+ readonly memoryPath: string;+ readonly importedAt: string;+ readonly bodySha256: string;+}++/** One runtime's memory-format adapter. */+export interface MemorySourceBackend {+ /** Stable selector used by the `memory_backend` config key. */+ readonly id: string;+ /** Human-readable runtime name for messages. */+ readonly label: string;+ /** Default memory directory for a vault under this runtime. */+ discoverMemoryDir(vault: string): string;+ /** Parse one memory file's text. */+ parseMemoryFile(text: string): MemorySourceParse;+ /** Render a parsed entry as a Brain preference markdown body. */+ renderPreference(input: MemoryRenderInput): string;+ /** Deterministic name -> preference-slug transform. */+ slugifyName(name: string): string;+}diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsindex c09dcc6e..b01417ba 100644--- a/src/core/brain/import-claude-memory.ts+++ b/src/core/brain/import-claude-memory.ts@@ -7,11 +7,11 @@ import { BRAIN_LOG_EVENT_KIND } from "./types.ts";import { createSnapshot } from "./snapshot.ts";import { isoSecond } from "./time.ts";import { resolveAgentName } from "../config.ts";-import { parseClaudeMemoryFile } from "./claude-memory-parser.ts";import { loadManifest, saveManifest } from "./claude-memory-manifest.ts";import { planAction, type PlannedFile } from "./claude-memory-plan.ts";-import { renderPreferenceFromMemory, slugifyMemoryName } from "./claude-memory-render.ts";import { assertSafeMemoryPath } from "./claude-memory-paths.ts";+import { claudeMemoryBackend } from "./agent-backend/claude.ts";+import type { MemorySourceBackend } from "./agent-backend/types.ts";import { BRAIN_PREFERENCES_REL, preferencePath } from "./paths.ts";export interface ImportClaudeMemoryOpts {@@ -20,6 +20,12 @@ export interface ImportClaudeMemoryOpts {readonly mode: "dry-run" | "apply";readonly allowArbitraryMemoryPath?: boolean;readonly now?: Date;+ /**+ * Memory-format adapter (t_53f9f67f). Defaults to the Claude Code+ * backend - byte-identical to the pre-seam behavior. Resolve via+ * `resolveMemoryBackend()` to honor the `memory_backend` config key.+ */+ readonly backend?: MemorySourceBackend;}export interface ImportClaudeMemoryResult {@@ -72,6 +78,7 @@ function mergePreservingEvidence(existingBody: string, freshBody: string): strin}export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMemoryResult {+ const backend = opts.backend ?? claudeMemoryBackend;assertSafeMemoryPath(opts.memoryDir, opts.allowArbitraryMemoryPath ?? false);if (!existsSync(opts.memoryDir)) {throw new Error(`memory directory not found: ${opts.memoryDir}`);@@ -100,12 +107,12 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMeif (name === "MEMORY.md") continue;if (!name.endsWith(".md")) continue;const text = readFileSync(join(opts.memoryDir, name), "utf8");- const parsed = parseClaudeMemoryFile(text);+ const parsed = backend.parseMemoryFile(text);if (parsed.kind === "skip") {skipped.push({ basename: name, reason: parsed.skipReason });continue;}- const slug = slugifyMemoryName(parsed.name);+ const slug = backend.slugifyName(parsed.name);const prefId = `pref-${slug}`;const dupOf = seenPrefIds.get(prefId);if (dupOf) {@@ -128,7 +135,7 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe});plans.push(plan);if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {- const body = renderPreferenceFromMemory({+ const body = backend.renderPreference({name: parsed.name,description: parsed.description,body: parsed.body,diff --git a/src/core/brain/note.ts b/src/core/brain/note.tsindex 4d0379b7..7776e2fe 100644--- a/src/core/brain/note.ts+++ b/src/core/brain/note.ts@@ -14,6 +14,7 @@ import { vaultRelative } from "../path-safety.ts";import { sanitiseTextField } from "../redactor.ts";import { appendLogEvent } from "./log.ts";+import { mirrorNote, resolveSharedNamespace, type MirrorOutcome } from "./shared-namespace.ts";import { isoSecond } from "./time.ts";import { BRAIN_LOG_EVENT_KIND } from "./types.ts";@@ -39,6 +40,12 @@ export interface AppendBrainNoteResult {readonly absolute_log_path: string;/** Identity actually written into the log entry. */readonly agent: string;+ /**+ * Shared-namespace mirror outcome (t_936a1a61). Present only when+ * the `shared_namespace` config key is set - unconfigured setups+ * keep the previous result shape.+ */+ readonly mirror?: MirrorOutcome;}/**@@ -63,10 +70,22 @@ export function appendBrainNote(input: AppendBrainNoteInput): AppendBrainNoteResbody: { text: sanitised, agent },} as const;const res = appendLogEvent(input.vault, entry);+ // t_936a1a61: mirror AFTER the primary append succeeded; the mirror+ // is fail-soft and must never alter the primary result.+ const shared = resolveSharedNamespace(input.configPath ?? null);+ const mirror =+ shared === null+ ? undefined+ : mirrorNote(shared, input.vault, {+ text: sanitised,+ agent,+ ...(input.now ? { now: input.now } : {}),+ });return {logged_at: timestamp,log_path: vaultRelative(res.logPath, input.vault),absolute_log_path: resolve(res.logPath),agent,+ ...(mirror !== undefined ? { mirror } : {}),};}diff --git a/src/core/brain/shared-namespace.ts b/src/core/brain/shared-namespace.tsnew file mode 100644index 00000000..8ed9c293--- /dev/null+++ b/src/core/brain/shared-namespace.ts@@ -0,0 +1,102 @@+/**+ * Cross-agent shared memory namespace (Agent Write Contract Suite,+ * t_936a1a61).+ *+ * Opt-in: the `shared_namespace` device-config key names a second+ * vault root. When set, explicit remember-writes (feedback signals and+ * narrative notes) MIRROR there after the primary write succeeds, so+ * facts learned by one agent become visible to every agent sharing the+ * namespace. Attribution is carried twice: the existing `agent` field+ * plus `origin_vault` (basename of the primary vault).+ *+ * Mirror semantics are FAIL-SOFT by contract: any mirror failure is+ * swallowed and reported as `"failed"` - it must never break, delay,+ * or alter the primary write. Default (key absent) is `"off"` with+ * zero behavior change. One-way by design: the shared vault's own+ * dream pass treats mirrored records as ordinary first-class signals.+ */++import { realpathSync } from "node:fs";+import { basename, resolve } from "node:path";++import { discoverConfig } from "../config.ts";+import { appendLogEvent } from "./log.ts";+import { writeSignal, type WriteSignalInput } from "./signal.ts";+import { isoSecond } from "./time.ts";+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";++export type MirrorOutcome = "ok" | "failed" | "off";++/** Shared-namespace root from the device config, or null when off. */+export function resolveSharedNamespace(configPath?: string | null): string | null {+ const discovery = discoverConfig(configPath ?? undefined);+ const value = discovery.data["shared_namespace"]?.trim();+ return value ? value : null;+}++/**+ * Mirror a feedback signal into the shared vault. The record is the+ * same signal with `origin_vault` attribution; slug collisions resolve+ * through the normal allocator.+ */+export function mirrorSignal(+ sharedVault: string,+ originVault: string,+ input: WriteSignalInput,+): MirrorOutcome {+ if (isSelfMirror(sharedVault, originVault)) return "failed";+ try {+ writeSignal(sharedVault, { ...input, origin_vault: basename(originVault) });+ return "ok";+ } catch {+ return "failed";+ }+}++export interface MirrorNoteInput {+ readonly text: string;+ readonly agent: string;+ readonly now?: Date;+}++/** Mirror a narrative note event into the shared vault's log. */+export function mirrorNote(+ sharedVault: string,+ originVault: string,+ input: MirrorNoteInput,+): MirrorOutcome {+ if (isSelfMirror(sharedVault, originVault)) return "failed";+ try {+ appendLogEvent(sharedVault, {+ timestamp: isoSecond(input.now ?? new Date()),+ eventType: BRAIN_LOG_EVENT_KIND.note,+ body: {+ text: input.text,+ agent: input.agent,+ origin_vault: basename(originVault),+ },+ });+ return "ok";+ } catch {+ return "failed";+ }+}++/**+ * A shared namespace pointing back at the origin vault would+ * double-write every record into its own store. That is always an+ * operator misconfiguration - surface it as `failed` rather than+ * silently duplicating.+ */+function isSelfMirror(sharedVault: string, originVault: string): boolean {+ return canonicalPath(sharedVault) === canonicalPath(originVault);+}++/** Realpath when resolvable (catches symlink aliases), lexical otherwise. */+function canonicalPath(path: string): string {+ try {+ return realpathSync(path);+ } catch {+ return resolve(path);+ }+}diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex d6a0ec7a..3f7c4cb7 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -85,6 +85,12 @@ export interface WriteSignalInput {readonly dedup_hash?: string;/** Session coordinates `<path>#<turn-id>` (§16). */readonly session_ref?: string;+ /**+ * Cross-agent shared namespace (t_936a1a61): basename of the origin+ * vault, stamped on MIRRORED records only. Absent on primary writes+ * so existing signals stay byte-identical.+ */+ readonly origin_vault?: string;/*** Vault portability suite (v0.22.0). Opt-in: when true and `raw` is* present, the body is stored through the deterministic codec and a@@ -213,6 +219,9 @@ export function writeSignal(if (sanitised.session_ref && sanitised.session_ref.trim()) {metadata["session_ref"] = sanitised.session_ref.trim();}+ if (sanitised.origin_vault && sanitised.origin_vault.trim()) {+ metadata["origin_vault"] = sanitised.origin_vault.trim();+ }// Opt-in codec (v0.22.0): store the raw body compressed and stamp a// `_raw_codec` marker so the reader expands it. Default path is verbatim.diff --git a/src/core/brain/types.ts b/src/core/brain/types.tsindex 7bfea45b..1caf6855 100644--- a/src/core/brain/types.ts+++ b/src/core/brain/types.ts@@ -217,6 +217,15 @@ export const BRAIN_LOG_EVENT_KIND = {* Emitted only on a changed run, so a no-op stays byte-identical.*/reconcile: "reconcile",+ /**+ * `write-session` (Agent Write Contract Suite, t_bc36a8a2) - one+ * audit row per TERMINAL write-session transition (done, failed,+ * abandoned, approved commit). Payload carries `session_id`, `kind`,+ * `status`, `target`, `attempts`, and whether operator review was+ * required. Non-terminal correction loops stay inside the session+ * file - the log records outcomes, not chatter.+ */+ writeSession: "write-session",} as const;export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];diff --git a/src/core/brain/write-session/engine.ts b/src/core/brain/write-session/engine.tsnew file mode 100644index 00000000..a76fbc0e--- /dev/null+++ b/src/core/brain/write-session/engine.ts@@ -0,0 +1,418 @@+/**+ * Write-session engine (Agent Write Contract Suite, t_bc36a8a2).+ *+ * The lifecycle the calling agent drives:+ *+ * open -> `needs-llm-step` envelope (prompt + schema hints ++ * collision metadata when the target is occupied)+ * submit-> `done` (validated, committed atomically)+ * | `needs-correction` (machine-readable errors + compact+ * correction prompt; session state preserved)+ * | `needs-review` (validated, parked for operator approve)+ * | `failed` (retry cap exhausted - terminal)+ * approve / abandon -> operator-side terminal transitions.+ *+ * Hard rules, enforced here and only here:+ * - OSB never generates content; every artifact byte comes from the+ * caller. Fail-closed: nothing lands unless validation is clean.+ * - `create` intent NEVER overwrites; `overwrite` replaces;+ * `merge` appends a session-stamped delimited section - existing+ * bytes are preserved verbatim in both non-destructive modes.+ * - Every terminal transition appends exactly one `write-session`+ * audit event through the existing log chokepoint.+ */++import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { appendLogEvent } from "../log.ts";+import { loadSchemaPack } from "../schema-pack.ts";+import { BRAIN_LOG_EVENT_KIND } from "../types.ts";+import { createWriteSession, readWriteSession, saveWriteSession } from "./store.ts";+import {+ buildCorrectionPrompt,+ inspectExistingTarget,+ validateArtifact,+ validateTargetPath,+} from "./validate.ts";+import {+ isTerminalWriteSessionStatus,+ type ExistingTargetInfo,+ type WriteSessionEnvelope,+ type WriteSessionError,+ type WriteSessionIntent,+ type WriteSessionRecord,+} from "./types.ts";++export const DEFAULT_RETRY_CAP = 3;+export const DEFAULT_TTL_MS = 24 * 3600 * 1000;++/** Structured request failure - carries the machine-readable errors. */+export class WriteSessionRequestError extends Error {+ readonly errors: ReadonlyArray<WriteSessionError>;++ constructor(message: string, errors: ReadonlyArray<WriteSessionError> = []) {+ super(message);+ this.name = "WriteSessionRequestError";+ this.errors = errors;+ }+}++export interface OpenArtifactSessionInput {+ readonly agent: string;+ readonly targetPath: string;+ /** Operator/agent-supplied generation instruction; a default is built. */+ readonly prompt?: string;+ readonly schemaType?: string | null;+ readonly intent?: WriteSessionIntent;+ readonly requireReview?: boolean;+ readonly retryCap?: number;+ readonly ttlMs?: number;+ /** ISO timestamp; fixtures pass a constant for determinism. */+ readonly now?: string;+}++/** Open an artifact session; throws {@link WriteSessionRequestError} on a bad target. */+export function openArtifactSession(+ vault: string,+ input: OpenArtifactSessionInput,+): WriteSessionEnvelope {+ const targetErrors = validateTargetPath(input.targetPath);+ if (targetErrors.length > 0) {+ throw new WriteSessionRequestError(+ `target rejected: ${targetErrors[0]!.message}`,+ targetErrors,+ );+ }+ const now = resolveNow(input.now);+ const schemaType = input.schemaType?.trim() || null;+ const expiresAt = new Date(Date.parse(now) + normalizeTtlMs(input.ttlMs)).toISOString();+ const retryCap = normalizeRetryCap(input.retryCap);+ const record = createWriteSession(vault, now, (id) =>+ Object.freeze({+ id,+ kind: "artifact" as const,+ status: "needs-llm-step" as const,+ step: "artifact",+ agent: input.agent.trim() || "unknown",+ createdAt: now,+ updatedAt: now,+ expiresAt,+ attempts: 0,+ retryCap,+ targetPath: input.targetPath,+ intent: input.intent ?? ("create" as const),+ requireReview: input.requireReview === true,+ prompt: input.prompt?.trim() || buildArtifactPrompt(input.targetPath, schemaType),+ schemaType,+ topic: null,+ personas: [],+ responses: {},+ pendingArtifact: null,+ lastErrors: [],+ failReason: null,+ }),+ );+ return sessionEnvelope(record, inspectExistingTarget(vault, record.targetPath));+}++export interface SubmitToSessionInput {+ readonly sessionId: string;+ readonly artifact: string;+ readonly now?: string;+}++/**+ * Submit the current step's text. Artifact sessions validate + commit;+ * panel sessions are routed by the caller through the panel module+ * (which reuses {@link acceptArtifactSubmission} semantics per step).+ */+export function submitToSession(vault: string, input: SubmitToSessionInput): WriteSessionEnvelope {+ const now = resolveNow(input.now);+ const session = loadLiveSession(vault, input.sessionId, now);+ if (session.kind !== "artifact") {+ throw new WriteSessionRequestError(+ `session ${session.id} is a '${session.kind}' session - submit through its kind-specific surface`,+ );+ }++ // Collision guard runs at COMMIT time, not just open time: the target+ // may have appeared between open and submit (another device, another+ // agent). `create` intent treats an occupied target as an error.+ const errors: WriteSessionError[] = [+ ...validateArtifactForSession(vault, session, input.artifact),+ ];+ if (session.intent === "create" && inspectExistingTarget(vault, session.targetPath) !== null) {+ errors.push(+ Object.freeze({+ code: "target-exists",+ path: "target",+ message:+ `${session.targetPath} already exists; reopen the session with overwrite or merge intent ` ++ "(or abandon)",+ }),+ );+ }++ if (errors.length > 0) {+ return recordFailedAttempt(vault, session, errors, now);+ }+ if (session.requireReview) {+ const parked: WriteSessionRecord = Object.freeze({+ ...session,+ status: "needs-review" as const,+ updatedAt: now,+ pendingArtifact: input.artifact,+ lastErrors: [],+ prompt: "Awaiting operator review - no further generation needed.",+ });+ saveWriteSession(vault, parked);+ return sessionEnvelope(parked);+ }+ return commitArtifact(vault, session, input.artifact, now);+}++export interface SessionOpInput {+ readonly sessionId: string;+ readonly now?: string;+}++/** Operator-side approval of a `needs-review` session. */+export function approveSession(vault: string, input: SessionOpInput): WriteSessionEnvelope {+ const now = resolveNow(input.now);+ const session = loadLiveSession(vault, input.sessionId, now);+ if (session.status !== "needs-review" || session.pendingArtifact === null) {+ throw new WriteSessionRequestError(+ `session ${session.id} is not awaiting review (status: ${session.status})`,+ );+ }+ return commitArtifact(vault, session, session.pendingArtifact, now);+}++/** Terminal abandon; safe on any non-terminal session. */+export function abandonSession(vault: string, input: SessionOpInput): WriteSessionEnvelope {+ const now = resolveNow(input.now);+ const session = loadLiveSession(vault, input.sessionId, now);+ const abandoned: WriteSessionRecord = Object.freeze({+ ...session,+ status: "failed" as const,+ updatedAt: now,+ failReason: "abandoned",+ pendingArtifact: null,+ });+ saveWriteSession(vault, abandoned);+ auditTerminal(vault, abandoned, now);+ return sessionEnvelope(abandoned);+}++/** Envelope view of a session record (status/list surfaces). */+export function sessionEnvelope(+ session: WriteSessionRecord,+ existing: ExistingTargetInfo | null = null,+): WriteSessionEnvelope {+ return Object.freeze({+ status: session.status,+ session_id: session.id,+ kind: session.kind,+ step: session.step,+ prompt: session.prompt,+ schema_hints: buildSchemaHints(session),+ errors: session.lastErrors,+ attempts_left: Math.max(0, session.retryCap - session.attempts),+ expires_at: session.expiresAt,+ target_path: session.targetPath,+ existing,+ });+}++// ----- Shared internals (panel module reuses these) -------------------------++export function resolveNow(now: string | undefined): string {+ if (now === undefined) return new Date().toISOString();+ const ts = Date.parse(now);+ if (Number.isNaN(ts)) {+ throw new WriteSessionRequestError(`invalid 'now' timestamp: ${now}`);+ }+ return new Date(ts).toISOString();+}++/** TTL must be a positive integer; reject before any date arithmetic. */+function normalizeTtlMs(ttlMs: number | undefined): number {+ if (ttlMs === undefined) return DEFAULT_TTL_MS;+ if (!Number.isFinite(ttlMs) || !Number.isInteger(ttlMs) || ttlMs < 1) {+ throw new WriteSessionRequestError(`ttlMs must be a positive integer, got: ${ttlMs}`);+ }+ return ttlMs;+}++function normalizeRetryCap(cap: number | undefined): number {+ if (cap === undefined) return DEFAULT_RETRY_CAP;+ if (!Number.isInteger(cap) || cap < 1 || cap > 20) {+ throw new WriteSessionRequestError(`retry cap must be an integer in [1, 20], got: ${cap}`);+ }+ return cap;+}++/**+ * Load a session that can still accept operations. An expired-on-read+ * session is persisted as failed (the lazy-TTL transform becomes+ * durable the moment anyone touches the session) and then refused.+ */+export function loadLiveSession(vault: string, id: string, now: string): WriteSessionRecord {+ const probe = readWriteSession(vault, id, now);+ if (probe.error !== null) {+ throw new WriteSessionRequestError(probe.error);+ }+ if (probe.session === null) {+ throw new WriteSessionRequestError(`unknown write-session: ${id}`);+ }+ const session = probe.session;+ if (isTerminalWriteSessionStatus(session.status)) {+ if (probe.expiredOnRead) {+ // The TTL transform fired on THIS read (disk record was still+ // non-terminal): make the expiry durable + audited exactly once.+ // A record already terminal on disk skips both.+ saveWriteSession(vault, session);+ auditTerminal(vault, session, now);+ }+ throw new WriteSessionRequestError(+ `write-session ${id} is terminal (${session.status}${+ session.failReason ? `/${session.failReason}` : ""+ })`,+ );+ }+ return session;+}++export function validateArtifactForSession(+ vault: string,+ session: WriteSessionRecord,+ artifact: string,+): ReadonlyArray<WriteSessionError> {+ return validateArtifact(artifact, {+ schemaType: session.schemaType,+ vocabulary: loadSchemaPack(vault).vocabulary,+ });+}++/** Failed attempt bookkeeping shared by artifact and panel steps. */+export function recordFailedAttempt(+ vault: string,+ session: WriteSessionRecord,+ errors: ReadonlyArray<WriteSessionError>,+ now: string,+): WriteSessionEnvelope {+ const attempts = session.attempts + 1;+ if (attempts >= session.retryCap) {+ const failed: WriteSessionRecord = Object.freeze({+ ...session,+ status: "failed" as const,+ attempts,+ updatedAt: now,+ lastErrors: errors,+ failReason: "retry-cap",+ pendingArtifact: null,+ });+ saveWriteSession(vault, failed);+ auditTerminal(vault, failed, now);+ return sessionEnvelope(failed);+ }+ const corrected: WriteSessionRecord = Object.freeze({+ ...session,+ status: "needs-correction" as const,+ attempts,+ updatedAt: now,+ lastErrors: errors,+ prompt: buildCorrectionPrompt(errors),+ });+ saveWriteSession(vault, corrected);+ return sessionEnvelope(corrected);+}++/** Validated commit + terminal bookkeeping (artifact and panel share it). */+export function commitArtifact(+ vault: string,+ session: WriteSessionRecord,+ artifact: string,+ now: string,+): WriteSessionEnvelope {+ const absolute = join(vault, session.targetPath);+ // Last-line-of-defense collision guard: submit-time checks cannot+ // cover the window between a needs-review park and the operator's+ // approve - if the target appeared meanwhile, `create` must still+ // refuse to overwrite at the write chokepoint itself.+ if (session.intent === "create" && existsSync(absolute)) {+ return recordFailedAttempt(+ vault,+ session,+ [+ Object.freeze({+ code: "target-exists",+ path: "target",+ message:+ `${session.targetPath} already exists; reopen the session with overwrite or merge intent ` ++ "(or abandon)",+ }),+ ],+ now,+ );+ }+ const body = artifact.endsWith("\n") ? artifact : `${artifact}\n`;+ mkdirSync(dirname(absolute), { recursive: true });+ if (session.intent === "merge" && existsSync(absolute)) {+ const existing = readFileSync(absolute, "utf8").replace(/\s+$/u, "");+ const merged = `${existing}\n\n<!-- o2b:ws-merge ${session.id} -->\n\n${body}`;+ atomicWriteFileSync(absolute, merged);+ } else {+ atomicWriteFileSync(absolute, body);+ }+ const done: WriteSessionRecord = Object.freeze({+ ...session,+ status: "done" as const,+ updatedAt: now,+ pendingArtifact: null,+ lastErrors: [],+ prompt: "Committed - no further generation needed.",+ });+ saveWriteSession(vault, done);+ auditTerminal(vault, done, now);+ return sessionEnvelope(done);+}++function buildArtifactPrompt(targetPath: string, schemaType: string | null): string {+ const schemaLine = schemaType ? ` The frontmatter must declare \`type: ${schemaType}\`.` : "";+ return (+ `Produce the complete markdown artifact for ${targetPath}. ` ++ "Start with a YAML frontmatter block (at minimum a `kind` key), follow with a heading and the body." ++ schemaLine ++ " Submit the full file content - it is validated before anything is written."+ );+}++function buildSchemaHints(session: WriteSessionRecord): ReadonlyArray<string> {+ const hints = [+ "frontmatter: required YAML block with at least one key",+ "format: UTF-8 markdown, no raw control characters",+ ];+ if (session.schemaType) hints.push(`type: ${session.schemaType} (frontmatter 'type' key)`);+ return Object.freeze(hints);+}++/** One audit row per terminal transition through the log chokepoint. */+export function auditTerminal(vault: string, session: WriteSessionRecord, now: string): void {+ appendLogEvent(vault, {+ timestamp: now.replace(/\.\d{3}Z$/u, "Z"),+ eventType: BRAIN_LOG_EVENT_KIND.writeSession,+ agent: session.agent,+ body: {+ session_id: session.id,+ kind: session.kind,+ status: session.status,+ target: session.targetPath,+ attempts: String(session.attempts),+ review: session.requireReview ? "required" : "not-required",+ ...(session.failReason ? { reason: session.failReason } : {}),+ },+ });+}diff --git a/src/core/brain/write-session/panel.ts b/src/core/brain/write-session/panel.tsnew file mode 100644index 00000000..4f97fc5e--- /dev/null+++ b/src/core/brain/write-session/panel.ts@@ -0,0 +1,308 @@+/**+ * Decision panel as a write-session kind+ * (Agent Write Contract Suite, t_0cc6fdff on the t_bc36a8a2 kernel).+ *+ * The panel rides the session kernel instead of owning a second state+ * machine: persona steps and the synthesis step reuse the kernel's+ * correction loop, retry cap, TTL, review gate, commit, and audit. OSB+ * sequences the lenses and validates the texts; the calling agent+ * supplies every generated word - the no-LLM-in-core rule holds.+ *+ * Step walk: `persona:<slug>` for each persona in declared order, then+ * `synthesis`, then the rendered decision note commits to the session+ * target (default `Brain/decisions/panels/panel-<date>-<topic>.md`).+ */++import {+ WriteSessionRequestError,+ commitArtifact,+ loadLiveSession,+ recordFailedAttempt,+ resolveNow,+ sessionEnvelope,+ submitToSession,+ DEFAULT_RETRY_CAP,+ DEFAULT_TTL_MS,+} from "./engine.ts";+import { createWriteSession, saveWriteSession } from "./store.ts";+import { loadPersonas } from "./personas.ts";+import { inspectExistingTarget, validateTargetPath } from "./validate.ts";+import { formatFrontmatter, slugify } from "../../vault.ts";+import type {+ WriteSessionEnvelope,+ WriteSessionError,+ WriteSessionPersona,+ WriteSessionRecord,+} from "./types.ts";++/** Per-step text cap - a lens answer, not an essay collection. */+export const PANEL_STEP_MAX_CHARS = 8000;++const SYNTHESIS_STEP = "synthesis";++export interface OpenPanelSessionInput {+ readonly agent: string;+ readonly topic: string;+ /** Persona slugs to convene, in order; defaults to every loaded persona. */+ readonly personas?: ReadonlyArray<string>;+ /** Override the default panels namespace target. */+ readonly targetPath?: string;+ readonly requireReview?: boolean;+ readonly retryCap?: number;+ readonly ttlMs?: number;+ readonly now?: string;+}++/** Open a panel session; the first envelope carries persona step one. */+export function openPanelSession(+ vault: string,+ input: OpenPanelSessionInput,+): WriteSessionEnvelope {+ const topic = input.topic.trim();+ if (topic === "") {+ throw new WriteSessionRequestError("panel topic must not be empty");+ }+ const personas = selectPersonas(loadPersonas(vault), input.personas);+ const now = resolveNow(input.now);+ const targetPath =+ input.targetPath ?? `Brain/decisions/panels/panel-${now.slice(0, 10)}-${slugify(topic)}.md`;+ const targetErrors = validateTargetPath(targetPath);+ if (targetErrors.length > 0) {+ throw new WriteSessionRequestError(+ `target rejected: ${targetErrors[0]!.message}`,+ targetErrors,+ );+ }+ const first = personas[0]!;+ const expiresAt = new Date(Date.parse(now) + (input.ttlMs ?? DEFAULT_TTL_MS)).toISOString();+ const record = createWriteSession(vault, now, (id) =>+ Object.freeze({+ id,+ kind: "panel" as const,+ status: "needs-llm-step" as const,+ step: `persona:${first.slug}`,+ agent: input.agent.trim() || "unknown",+ createdAt: now,+ updatedAt: now,+ expiresAt,+ attempts: 0,+ retryCap: input.retryCap ?? DEFAULT_RETRY_CAP,+ targetPath,+ intent: "create" as const,+ requireReview: input.requireReview === true,+ prompt: personaPrompt(first, topic),+ schemaType: null,+ topic,+ personas,+ responses: {},+ pendingArtifact: null,+ lastErrors: [],+ failReason: null,+ }),+ );+ return sessionEnvelope(record);+}++export interface SubmitPanelStepInput {+ readonly sessionId: string;+ readonly text: string;+ readonly now?: string;+}++/** Submit the current panel step (persona answer or synthesis). */+export function submitToPanelSession(+ vault: string,+ input: SubmitPanelStepInput,+): WriteSessionEnvelope {+ const now = resolveNow(input.now);+ const session = loadLiveSession(vault, input.sessionId, now);+ if (session.kind !== "panel") {+ throw new WriteSessionRequestError(+ `session ${session.id} is an '${session.kind}' session - use the artifact submit surface`,+ );+ }+ const errors = validateStepText(input.text);+ if (errors.length > 0) {+ return recordFailedAttempt(vault, session, errors, now);+ }+ const text = input.text.trim();++ if (session.step === SYNTHESIS_STEP) {+ // Commit-time collision guard: panel sessions always carry `create`+ // intent, and create NEVER overwrites - same contract as the+ // artifact flow. An occupied target (operator-specified, or a+ // same-day rerun of the same topic) is a structured error, not a+ // silent overwrite.+ if (inspectExistingTarget(vault, session.targetPath) !== null) {+ return recordFailedAttempt(+ vault,+ session,+ [+ Object.freeze({+ code: "target-exists",+ path: "target",+ message: `${session.targetPath} already exists; abandon and reopen with --target`,+ }),+ ],+ now,+ );+ }+ const note = renderPanelNote(session, text, now);+ if (session.requireReview) {+ const parked: WriteSessionRecord = Object.freeze({+ ...session,+ status: "needs-review" as const,+ updatedAt: now,+ responses: Object.freeze({ ...session.responses, [SYNTHESIS_STEP]: text }),+ pendingArtifact: note,+ lastErrors: [],+ prompt: "Awaiting operator review - no further generation needed.",+ });+ saveWriteSession(vault, parked);+ return sessionEnvelope(parked);+ }+ return commitArtifact(+ vault,+ Object.freeze({+ ...session,+ responses: Object.freeze({ ...session.responses, [SYNTHESIS_STEP]: text }),+ }),+ note,+ now,+ );+ }++ // Persona step accepted: record the answer, advance, reset attempts.+ const responses = Object.freeze({ ...session.responses, [session.step]: text });+ const next = nextStep(session, session.step);+ const advanced: WriteSessionRecord = Object.freeze({+ ...session,+ status: "needs-llm-step" as const,+ step: next,+ attempts: 0,+ updatedAt: now,+ responses,+ lastErrors: [],+ prompt:+ next === SYNTHESIS_STEP+ ? synthesisPrompt({ ...session, responses })+ : personaPrompt(+ session.personas.find((p) => `persona:${p.slug}` === next)!,+ session.topic ?? "",+ ),+ });+ saveWriteSession(vault, advanced);+ return sessionEnvelope(advanced);+}++export interface DispatchSubmitInput {+ readonly sessionId: string;+ readonly text: string;+ readonly now?: string;+}++/**+ * Kind-agnostic submit for surfaces that take a bare session id (CLI+ * `brain session submit`, the MCP tool): routes to the artifact or+ * panel flow based on the stored session kind.+ */+export function dispatchSubmit(vault: string, input: DispatchSubmitInput): WriteSessionEnvelope {+ const now = resolveNow(input.now);+ const session = loadLiveSession(vault, input.sessionId, now);+ if (session.kind === "panel") {+ return submitToPanelSession(vault, { sessionId: input.sessionId, text: input.text, now });+ }+ return submitToSession(vault, { sessionId: input.sessionId, artifact: input.text, now });+}++// ----- internals -------------------------------------------------------------++function selectPersonas(+ loaded: ReadonlyArray<WriteSessionPersona>,+ requested: ReadonlyArray<string> | undefined,+): ReadonlyArray<WriteSessionPersona> {+ if (requested === undefined || requested.length === 0) return loaded;+ const bySlug = new Map(loaded.map((p) => [p.slug, p]));+ const selected: WriteSessionPersona[] = [];+ // Duplicates would break step progression: `nextStep` walks the+ // persona list by indexOf, so a repeated slug loops on itself and+ // the session never reaches synthesis.+ const seen = new Set<string>();+ for (const rawSlug of requested) {+ const slug = rawSlug.trim();+ if (slug === "") {+ throw new WriteSessionRequestError("persona slug must not be empty");+ }+ if (seen.has(slug)) {+ throw new WriteSessionRequestError(`duplicate persona '${slug}' requested`);+ }+ seen.add(slug);+ const persona = bySlug.get(slug);+ if (persona === undefined) {+ throw new WriteSessionRequestError(+ `unknown persona '${slug}' - available: ${loaded.map((p) => p.slug).join(", ")}`,+ );+ }+ selected.push(persona);+ }+ return Object.freeze(selected);+}++function validateStepText(text: string): ReadonlyArray<WriteSessionError> {+ if (typeof text !== "string" || text.trim() === "") {+ return Object.freeze([+ Object.freeze({ code: "step-empty", path: "body", message: "step text must not be empty" }),+ ]);+ }+ if (text.length > PANEL_STEP_MAX_CHARS) {+ return Object.freeze([+ Object.freeze({+ code: "step-too-long",+ path: "body",+ message: `step text exceeds ${PANEL_STEP_MAX_CHARS} characters`,+ }),+ ]);+ }+ return Object.freeze([]);+}++function nextStep(session: WriteSessionRecord, current: string): string {+ const steps = session.personas.map((p) => `persona:${p.slug}`);+ const index = steps.indexOf(current);+ return index >= 0 && index < steps.length - 1 ? steps[index + 1]! : SYNTHESIS_STEP;+}++function personaPrompt(persona: WriteSessionPersona, topic: string): string {+ return `Decision topic: ${topic}\n\nAnswer as the '${persona.slug}' panelist (${persona.lens}).\n${persona.prompt}`;+}++function synthesisPrompt(session: WriteSessionRecord): string {+ const answers = session.personas+ .map((p) => `### ${p.lens} (${p.slug})\n${session.responses[`persona:${p.slug}`] ?? ""}`)+ .join("\n\n");+ return (+ `Decision topic: ${session.topic}\n\n` ++ `Every panelist has answered:\n\n${answers}\n\n` ++ "Synthesize the deliberation into a recommendation: state the decision, the strongest supporting argument per lens, the unresolved tensions, and the conditions that would reverse it."+ );+}++/** Deterministic decision note - same session state, same bytes. */+function renderPanelNote(session: WriteSessionRecord, synthesis: string, now: string): string {+ const metadata = {+ kind: "decision-panel",+ topic: session.topic ?? "",+ created_at: now.replace(/\.\d{3}Z$/u, "Z"),+ session: session.id,+ agent: session.agent,+ personas: session.personas.map((p) => p.slug),+ tags: ["brain", "brain/decision-panel"],+ };+ const lines: string[] = [`# Panel: ${session.topic ?? ""}`, ""];+ for (const persona of session.personas) {+ lines.push(`## ${persona.lens} (${persona.slug})`, "");+ lines.push(session.responses[`persona:${persona.slug}`] ?? "", "");+ }+ lines.push("## Synthesis", "", synthesis);+ return formatFrontmatter(metadata, lines.join("\n"));+}diff --git a/src/core/brain/write-session/personas.ts b/src/core/brain/write-session/personas.tsnew file mode 100644index 00000000..fd536107--- /dev/null+++ b/src/core/brain/write-session/personas.ts@@ -0,0 +1,79 @@+/**+ * Panel personas (Agent Write Contract Suite, t_0cc6fdff).+ *+ * A persona is one analytical lens the calling agent must answer+ * through. Operators own custom personas as ordinary vault notes under+ * `Brain/personas/<slug>.md` (frontmatter `kind: persona`, `lens`; the+ * body is the generation instruction). When the directory is absent or+ * holds no persona notes, the built-in default set applies - the panel+ * works out of the box and stays operator-curatable.+ */++import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import { parseFrontmatter } from "../../vault.ts";+import type { WriteSessionPersona } from "./types.ts";++/** Default lens set, in deliberation order. */+export const DEFAULT_PERSONAS: ReadonlyArray<WriteSessionPersona> = Object.freeze([+ Object.freeze({+ slug: "technical",+ lens: "technical feasibility",+ prompt:+ "Assess the topic strictly through technical feasibility: implementation effort, architectural fit, operational burden, and reversibility. Name concrete constraints.",+ }),+ Object.freeze({+ slug: "strategic",+ lens: "strategic alignment",+ prompt:+ "Assess the topic through strategic alignment: does it serve the project's direction, what does it displace, and what does deferring cost. Argue from priorities, not implementation detail.",+ }),+ Object.freeze({+ slug: "risk",+ lens: "risk and failure modes",+ prompt:+ "Assess the topic through risk: enumerate failure modes, blast radius, irreversibility, and mitigations. Be explicitly adversarial - assume things go wrong.",+ }),+ Object.freeze({+ slug: "user-experience",+ lens: "user experience",+ prompt:+ "Assess the topic through the user's experience: who is affected, what changes in their workflow, what friction appears or disappears. Argue from the user's seat.",+ }),+]);++/** Vault directory operators curate personas in. */+export function personasDir(vault: string): string {+ return join(vault, "Brain", "personas");+}++/**+ * Load operator personas, falling back to {@link DEFAULT_PERSONAS}.+ * Notes are read in filename order (deterministic step sequence);+ * non-persona notes and malformed files are skipped silently - the+ * panel must keep working when a stray note lands in the directory.+ */+export function loadPersonas(vault: string): ReadonlyArray<WriteSessionPersona> {+ const dir = personasDir(vault);+ if (!existsSync(dir)) return DEFAULT_PERSONAS;+ const personas: WriteSessionPersona[] = [];+ for (const name of readdirSync(dir).toSorted()) {+ if (!name.endsWith(".md")) continue;+ let meta: Readonly<Record<string, unknown>>;+ let body: string;+ try {+ [meta, body] = parseFrontmatter(join(dir, name));+ } catch {+ continue;+ }+ if (meta["kind"] !== "persona") continue;+ const slug = name.slice(0, -".md".length);+ const lens =+ typeof meta["lens"] === "string" && meta["lens"].trim() ? meta["lens"].trim() : slug;+ const prompt = body.trim();+ if (prompt === "") continue;+ personas.push(Object.freeze({ slug, lens, prompt }));+ }+ return personas.length > 0 ? Object.freeze(personas) : DEFAULT_PERSONAS;+}diff --git a/src/core/brain/write-session/store.ts b/src/core/brain/write-session/store.tsnew file mode 100644index 00000000..45034536--- /dev/null+++ b/src/core/brain/write-session/store.ts@@ -0,0 +1,359 @@+/**+ * Write-session store (Agent Write Contract Suite, t_bc36a8a2).+ *+ * One JSON file per session under `Brain/.sessions/write/<id>.json`,+ * consistent with the `Brain/.payloads/` convention: dot-prefixed,+ * vault-synced, machine-owned. snake_case on disk, camelCase in TS,+ * atomic writes through `fs-atomic`.+ *+ * TTL is LAZY: expiry is evaluated on read (an expired non-terminal+ * session reads as terminal `failed`/`expired`), and+ * {@link sweepWriteSessions} deletes terminal and expired files. No+ * daemon, no background timer - the same pattern as every other OSB+ * maintenance surface.+ *+ * Tolerant reads: a corrupted session file surfaces as a probe error+ * (never a throw), mirroring `readGitState` / the log parser.+ */++import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";++import { atomicCreateFileSyncExclusive, atomicWriteFileSync } from "../../fs-atomic.ts";+import {+ isTerminalWriteSessionStatus,+ type WriteSessionError,+ type WriteSessionIntent,+ type WriteSessionKind,+ type WriteSessionPersona,+ type WriteSessionProbe,+ type WriteSessionRecord,+ type WriteSessionStatus,+} from "./types.ts";++/** Session ids are lowercase slugs - the grammar doubles as path safety. */+const SESSION_ID_RE = /^ws-[a-z0-9][a-z0-9-]*$/;++const STATUS_SET: ReadonlySet<string> = new Set([+ "needs-llm-step",+ "needs-correction",+ "needs-review",+ "done",+ "failed",+]);++const KIND_SET: ReadonlySet<string> = new Set(["artifact", "panel"]);+const INTENT_SET: ReadonlySet<string> = new Set(["create", "overwrite", "merge"]);++export function isWriteSessionId(value: unknown): value is string {+ return typeof value === "string" && SESSION_ID_RE.test(value);+}++/** Session directory inside the vault. */+export function writeSessionDir(vault: string): string {+ return join(vault, "Brain", ".sessions", "write");+}++/** Path of one session file; the id grammar is enforced first. */+export function writeSessionPath(vault: string, id: string): string {+ if (!isWriteSessionId(id)) {+ throw new Error(`invalid write-session id: ${JSON.stringify(id)}`);+ }+ return join(writeSessionDir(vault), `${id}.json`);+}++/**+ * Allocate a collision-free session id from the supplied timestamp.+ * `ws-<yyyymmdd>-<hhmmss>` with `-2`, `-3`, ... suffixes when a session+ * landed in the same second - deterministic for fixture callers.+ */+export function allocateWriteSessionId(vault: string, nowIso: string): string {+ const ts = Date.parse(nowIso);+ if (Number.isNaN(ts)) {+ throw new Error(`invalid session timestamp: ${nowIso}`);+ }+ const iso = new Date(ts).toISOString();+ const stem = `ws-${iso.slice(0, 10).replaceAll("-", "")}-${iso.slice(11, 19).replaceAll(":", "")}`;+ if (!existsSync(join(writeSessionDir(vault), `${stem}.json`))) return stem;+ for (let n = 2; n < 10_000; n++) {+ const candidate = `${stem}-${n}`;+ if (!existsSync(join(writeSessionDir(vault), `${candidate}.json`))) return candidate;+ }+ throw new Error(`could not allocate a write-session id for ${stem}`);+}++function serializeRecord(record: WriteSessionRecord): string {+ return (+ JSON.stringify(+ {+ id: record.id,+ kind: record.kind,+ status: record.status,+ step: record.step,+ agent: record.agent,+ created_at: record.createdAt,+ updated_at: record.updatedAt,+ expires_at: record.expiresAt,+ attempts: record.attempts,+ retry_cap: record.retryCap,+ target_path: record.targetPath,+ intent: record.intent,+ require_review: record.requireReview,+ prompt: record.prompt,+ schema_type: record.schemaType,+ topic: record.topic,+ personas: record.personas.map((p) => ({ slug: p.slug, lens: p.lens, prompt: p.prompt })),+ responses: record.responses,+ pending_artifact: record.pendingArtifact,+ last_errors: record.lastErrors.map((e) => ({+ code: e.code,+ path: e.path,+ message: e.message,+ })),+ fail_reason: record.failReason,+ },+ null,+ 2,+ ) + "\n"+ );+}++function str(rec: Record<string, unknown>, key: string): string {+ return typeof rec[key] === "string" ? (rec[key] as string) : "";+}++function parsePersonas(raw: unknown): ReadonlyArray<WriteSessionPersona> {+ if (!Array.isArray(raw)) return Object.freeze([]);+ const personas: WriteSessionPersona[] = [];+ for (const item of raw) {+ if (typeof item !== "object" || item === null) continue;+ const p = item as Record<string, unknown>;+ if (typeof p["slug"] !== "string" || p["slug"] === "") continue;+ personas.push(+ Object.freeze({ slug: p["slug"], lens: str(p, "lens"), prompt: str(p, "prompt") }),+ );+ }+ return Object.freeze(personas);+}++function parseErrors(raw: unknown): ReadonlyArray<WriteSessionError> {+ if (!Array.isArray(raw)) return Object.freeze([]);+ const errors: WriteSessionError[] = [];+ for (const item of raw) {+ if (typeof item !== "object" || item === null) continue;+ const e = item as Record<string, unknown>;+ if (typeof e["code"] !== "string") continue;+ errors.push(+ Object.freeze({ code: e["code"], path: str(e, "path"), message: str(e, "message") }),+ );+ }+ return Object.freeze(errors);+}++function parseResponses(raw: unknown): Readonly<Record<string, string>> {+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return Object.freeze({});+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {+ if (typeof value === "string") out[key] = value;+ }+ return Object.freeze(out);+}++function isIsoDateString(value: unknown): value is string {+ return typeof value === "string" && !Number.isNaN(Date.parse(value));+}++function isCounter(value: unknown): value is number {+ return typeof value === "number" && Number.isInteger(value) && value >= 0;+}++/**+ * Fail-closed: a valid-JSON record missing required structure reads as+ * malformed (error probe), never as a live session with defaulted+ * fields - a corrupted store entry must not become writable state.+ */+function parseRecord(raw: unknown): WriteSessionRecord | null {+ if (typeof raw !== "object" || raw === null) return null;+ const rec = raw as Record<string, unknown>;+ if (!isWriteSessionId(rec["id"])) return null;+ if (!KIND_SET.has(String(rec["kind"]))) return null;+ if (!STATUS_SET.has(String(rec["status"]))) return null;+ if (typeof rec["step"] !== "string" || rec["step"] === "") return null;+ if (typeof rec["agent"] !== "string" || rec["agent"] === "") return null;+ if (!isIsoDateString(rec["created_at"])) return null;+ if (!isIsoDateString(rec["updated_at"])) return null;+ if (!isIsoDateString(rec["expires_at"])) return null;+ if (typeof rec["target_path"] !== "string" || rec["target_path"] === "") return null;+ if (!isCounter(rec["attempts"])) return null;+ if (!isCounter(rec["retry_cap"])) return null;+ const intent = INTENT_SET.has(String(rec["intent"]))+ ? (rec["intent"] as WriteSessionIntent)+ : "create";+ return Object.freeze({+ id: rec["id"] as string,+ kind: rec["kind"] as WriteSessionKind,+ status: rec["status"] as WriteSessionStatus,+ step: str(rec, "step"),+ agent: str(rec, "agent"),+ createdAt: str(rec, "created_at"),+ updatedAt: str(rec, "updated_at"),+ expiresAt: str(rec, "expires_at"),+ attempts: typeof rec["attempts"] === "number" ? rec["attempts"] : 0,+ retryCap: typeof rec["retry_cap"] === "number" ? rec["retry_cap"] : 0,+ targetPath: str(rec, "target_path"),+ intent,+ requireReview: rec["require_review"] === true,+ prompt: str(rec, "prompt"),+ schemaType: typeof rec["schema_type"] === "string" ? rec["schema_type"] : null,+ topic: typeof rec["topic"] === "string" ? rec["topic"] : null,+ personas: parsePersonas(rec["personas"]),+ responses: parseResponses(rec["responses"]),+ pendingArtifact: typeof rec["pending_artifact"] === "string" ? rec["pending_artifact"] : null,+ lastErrors: parseErrors(rec["last_errors"]),+ failReason: typeof rec["fail_reason"] === "string" ? rec["fail_reason"] : null,+ });+}++/**+ * Lazy-TTL view: a non-terminal session whose `expiresAt` is in the+ * past reads as terminal `failed`/`expired`. The transform is pure -+ * the file is not rewritten on read; `sweepWriteSessions` owns cleanup.+ */+function applyTtl(record: WriteSessionRecord, nowIso: string): WriteSessionRecord {+ if (isTerminalWriteSessionStatus(record.status)) return record;+ const expires = Date.parse(record.expiresAt);+ const now = Date.parse(nowIso);+ if (Number.isNaN(expires) || Number.isNaN(now) || now < expires) return record;+ return Object.freeze({ ...record, status: "failed" as const, failReason: "expired" });+}++/** Persist a session record atomically (updates an EXISTING session). */+export function saveWriteSession(vault: string, record: WriteSessionRecord): void {+ mkdirSync(writeSessionDir(vault), { recursive: true });+ atomicWriteFileSync(writeSessionPath(vault, record.id), serializeRecord(record));+}++/**+ * Allocate an id and persist a NEW session in one step. The first save+ * goes through an exclusive create (hardlink-based, fails on EEXIST),+ * so two concurrent openers in the same second can never claim the+ * same id - the loser simply retries with the next suffix. This closes+ * the check-then-use window a bare `allocate + save` pair would have.+ */+export function createWriteSession(+ vault: string,+ nowIso: string,+ build: (id: string) => WriteSessionRecord,+): WriteSessionRecord {+ mkdirSync(writeSessionDir(vault), { recursive: true });+ for (let attempt = 0; attempt < 10_000; attempt++) {+ const id = allocateWriteSessionId(vault, nowIso);+ const record = build(id);+ try {+ atomicCreateFileSyncExclusive(writeSessionPath(vault, id), serializeRecord(record));+ return record;+ } catch (exc) {+ if ((exc as NodeJS.ErrnoException).code === "EEXIST") continue;+ throw exc;+ }+ }+ throw new Error("could not create a write-session: id space exhausted for this second");+}++/**+ * Read one session. Missing file: `{session: null, error: null}`.+ * Malformed JSON or an invalid record: `{session: null, error}` so the+ * engine can report the corruption instead of crashing.+ */+export function readWriteSession(vault: string, id: string, nowIso: string): WriteSessionProbe {+ if (!isWriteSessionId(id)) {+ return Object.freeze({+ session: null,+ error: `invalid write-session id: ${id}`,+ expiredOnRead: false,+ });+ }+ const path = writeSessionPath(vault, id);+ if (!existsSync(path)) {+ return Object.freeze({ session: null, error: null, expiredOnRead: false });+ }+ let raw: unknown;+ try {+ raw = JSON.parse(readFileSync(path, "utf8"));+ } catch (exc) {+ return Object.freeze({+ session: null,+ error: `write-session file is not valid JSON: ${(exc as Error).message}`,+ expiredOnRead: false,+ });+ }+ const record = parseRecord(raw);+ if (record === null) {+ return Object.freeze({+ session: null,+ error: `write-session record is malformed (${id})`,+ expiredOnRead: false,+ });+ }+ const view = applyTtl(record, nowIso);+ return Object.freeze({ session: view, error: null, expiredOnRead: view !== record });+}++/** All readable sessions, sorted by created_at then id. Corrupt files are skipped. */+export function listWriteSessions(+ vault: string,+ nowIso: string,+): ReadonlyArray<WriteSessionRecord> {+ const dir = writeSessionDir(vault);+ if (!existsSync(dir)) return [];+ const sessions: WriteSessionRecord[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".json")) continue;+ const probe = readWriteSession(vault, name.slice(0, -".json".length), nowIso);+ if (probe.session !== null) sessions.push(probe.session);+ }+ sessions.sort((a, b) =>+ a.createdAt === b.createdAt ? a.id.localeCompare(b.id) : a.createdAt.localeCompare(b.createdAt),+ );+ return Object.freeze(sessions);+}++/** Remove one session file (idempotent). */+export function deleteWriteSession(vault: string, id: string): void {+ rmSync(writeSessionPath(vault, id), { force: true });+}++export interface SweepWriteSessionsResult {+ readonly removed: number;+ readonly kept: number;+}++/**+ * Delete terminal (done/failed) and expired session files. Corrupt+ * files are also removed - they can never transition anywhere.+ */+export function sweepWriteSessions(vault: string, nowIso: string): SweepWriteSessionsResult {+ const dir = writeSessionDir(vault);+ if (!existsSync(dir)) return Object.freeze({ removed: 0, kept: 0 });+ let removed = 0;+ let kept = 0;+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".json")) continue;+ const id = name.slice(0, -".json".length);+ if (!isWriteSessionId(id)) {+ // A *.json name outside the id grammar can never become a live+ // session - it is corrupt by definition; sweep owns its removal.+ rmSync(join(dir, name), { force: true });+ removed += 1;+ continue;+ }+ const probe = readWriteSession(vault, id, nowIso);+ if (probe.session === null || isTerminalWriteSessionStatus(probe.session.status)) {+ rmSync(join(dir, name), { force: true });+ removed += 1;+ } else {+ kept += 1;+ }+ }+ return Object.freeze({ removed, kept });+}diff --git a/src/core/brain/write-session/types.ts b/src/core/brain/write-session/types.tsnew file mode 100644index 00000000..76709b05--- /dev/null+++ b/src/core/brain/write-session/types.ts@@ -0,0 +1,144 @@+/**+ * Write-session contract types (Agent Write Contract Suite, t_bc36a8a2).+ *+ * One generic, file-backed session lifecycle serves every agent-facing+ * structured write: a caller opens a session, receives a JSON envelope+ * telling it exactly what to generate, submits the artifact back, and+ * OSB validates locally before anything lands in the vault. The kernel+ * is provider-agnostic by construction - OSB never calls an LLM; the+ * calling agent owns generation, OSB owns sequencing, validation, and+ * the final atomic commit.+ *+ * The decision panel (t_0cc6fdff) is a session KIND on this kernel,+ * not a parallel lifecycle: panel-only state lives on the session+ * record; the envelope grammar below is shared and stable.+ */++/** Session kinds. `artifact` writes one note; `panel` deliberates. */+export type WriteSessionKind = "artifact" | "panel";++/**+ * Envelope statuses (design doc grammar, stable across CLI and MCP):+ *+ * - `needs-llm-step` - OSB needs the caller to generate the current+ * step's text (artifact body or persona answer).+ * - `needs-correction` - the last submit failed validation; errors and+ * a compact correction prompt are attached and+ * the session state is preserved.+ * - `needs-review` - the artifact validated but the session was+ * opened with `require_review`; an operator+ * `approve` commits it.+ * - `done` - terminal; the artifact is committed.+ * - `failed` - terminal; retry cap, TTL expiry, or abandon.+ */+export type WriteSessionStatus =+ | "needs-llm-step"+ | "needs-correction"+ | "needs-review"+ | "done"+ | "failed";++/** Commit intent against an existing target path. */+export type WriteSessionIntent = "create" | "overwrite" | "merge";++/** Machine-readable validation error. */+export interface WriteSessionError {+ readonly code: string;+ /** What the error is about: a frontmatter key, `body`, `target`, ... */+ readonly path: string;+ readonly message: string;+}++/** One panel persona (loaded from Brain/personas/ or built-in). */+export interface WriteSessionPersona {+ readonly slug: string;+ readonly lens: string;+ readonly prompt: string;+}++/**+ * Persisted session record (`Brain/.sessions/write/<id>.json`,+ * snake_case on disk). Panel-only fields (`topic`, `personas`,+ * `responses`) stay empty for artifact sessions - the record shape is+ * uniform so the store stays kind-agnostic.+ */+export interface WriteSessionRecord {+ readonly id: string;+ readonly kind: WriteSessionKind;+ readonly status: WriteSessionStatus;+ /** Current step: `artifact`, `persona:<slug>`, or `synthesis`. */+ readonly step: string;+ readonly agent: string;+ readonly createdAt: string;+ readonly updatedAt: string;+ readonly expiresAt: string;+ /** Failed submits against the CURRENT step. */+ readonly attempts: number;+ readonly retryCap: number;+ /** Vault-relative commit target. */+ readonly targetPath: string;+ readonly intent: WriteSessionIntent;+ readonly requireReview: boolean;+ /** Generation prompt for the current step. */+ readonly prompt: string;+ /** Declared schema-pack type the artifact must satisfy, if any. */+ readonly schemaType: string | null;+ readonly topic: string | null;+ readonly personas: ReadonlyArray<WriteSessionPersona>;+ /** Accepted per-step submissions, keyed by step name. */+ readonly responses: Readonly<Record<string, string>>;+ /** Validated artifact awaiting operator approval (`needs-review`). */+ readonly pendingArtifact: string | null;+ readonly lastErrors: ReadonlyArray<WriteSessionError>;+ /** Terminal-failure reason: `retry-cap`, `expired`, `abandoned`. */+ readonly failReason: string | null;+}++/** Read probe mirroring the store conventions (git state, continuity). */+export interface WriteSessionProbe {+ readonly session: WriteSessionRecord | null;+ readonly error: string | null;+ /**+ * True when the lazy-TTL transform fired on THIS read: the disk+ * record is still non-terminal but the returned view is+ * `failed`/`expired`. The engine uses this to persist + audit the+ * expiry exactly once - a record already terminal on disk reads+ * with `expiredOnRead: false`.+ */+ readonly expiredOnRead: boolean;+}++/**+ * The JSON envelope every operation returns. Stable grammar shared by+ * the CLI verb and the MCP tool; `existing` is populated only when the+ * target path already holds content the caller must decide about.+ */+export interface WriteSessionEnvelope {+ readonly status: WriteSessionStatus;+ readonly session_id: string;+ readonly kind: WriteSessionKind;+ readonly step: string;+ readonly prompt: string;+ readonly schema_hints: ReadonlyArray<string>;+ readonly errors: ReadonlyArray<WriteSessionError>;+ readonly attempts_left: number;+ readonly expires_at: string;+ readonly target_path: string;+ readonly existing: ExistingTargetInfo | null;+}++/** Collision metadata for an already-occupied target path. */+export interface ExistingTargetInfo {+ readonly bytes: number;+ readonly content_hash: string;+ readonly first_heading: string | null;+}++export const WRITE_SESSION_TERMINAL_STATUSES: ReadonlySet<WriteSessionStatus> = new Set([+ "done",+ "failed",+]);++export function isTerminalWriteSessionStatus(status: WriteSessionStatus): boolean {+ return WRITE_SESSION_TERMINAL_STATUSES.has(status);+}diff --git a/src/core/brain/write-session/validate.ts b/src/core/brain/write-session/validate.tsnew file mode 100644index 00000000..fac58b69--- /dev/null+++ b/src/core/brain/write-session/validate.ts@@ -0,0 +1,199 @@+/**+ * Write-session artifact validation and target policy+ * (Agent Write Contract Suite, t_bc36a8a2).+ *+ * Fail-closed by construction: every check returns machine-readable+ * `{code, path, message}` errors, and the engine commits ONLY a clean+ * artifact. The correction prompt is derived from the error list so+ * the calling agent receives exactly what to fix - the session keeps+ * the target and schema, the agent resubmits the full artifact.+ *+ * Target policy mirrors the design doc's reserved-deny list: writes+ * land inside `Brain/` but never in machine-owned or dream-owned+ * namespaces (`preferences/`, `log/`, `.sessions/`, `.payloads/`,+ * `_brain.yaml`).+ */++import { createHash } from "node:crypto";+import { existsSync, readFileSync, statSync } from "node:fs";+import { join, normalize, sep } from "node:path";++import { parseFrontmatterText } from "../../vault.ts";+import { isKnownSchemaToken, type BrainSchemaVocabulary } from "../schema-vocab.ts";+import type { ExistingTargetInfo, WriteSessionError } from "./types.ts";++/** Hard cap on artifact size - a note, not a payload dump. */+export const ARTIFACT_MAX_BYTES = 262_144;++/** Reserved vault-relative prefixes (and exact files) sessions may never touch. */+const RESERVED_PREFIXES: ReadonlyArray<string> = Object.freeze([+ "Brain/preferences/",+ "Brain/log/",+ "Brain/.sessions/",+ "Brain/.payloads/",+]);++const RESERVED_FILES: ReadonlySet<string> = new Set(["Brain/_brain.yaml"]);++function err(code: string, path: string, message: string): WriteSessionError {+ return Object.freeze({ code, path, message });+}++/**+ * C0 controls except \t (0x09), \n (0x0A), \r (0x0D). A char-code walk+ * instead of a regex keeps the no-control-regex lint baseline intact.+ */+function hasForbiddenControlChar(text: string): boolean {+ for (let i = 0; i < text.length; i++) {+ const code = text.charCodeAt(i);+ if (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0d) return true;+ }+ return false;+}++/**+ * Validate a vault-relative commit target. Returns `[]` when the path+ * is acceptable; every violation is a coded error.+ */+export function validateTargetPath(targetPath: string): ReadonlyArray<WriteSessionError> {+ const errors: WriteSessionError[] = [];+ if (typeof targetPath !== "string" || !targetPath.startsWith("Brain/")) {+ return Object.freeze([+ err("target-outside-brain", "target", "target must be a vault-relative path under Brain/"),+ ]);+ }+ if (targetPath.includes("..") || targetPath.includes("\\") || targetPath.includes("\x00")) {+ return Object.freeze([+ err("target-traversal", "target", "target must not contain '..', backslashes, or NUL"),+ ]);+ }+ // normalize() collapses any remaining oddities; a path that changes+ // under normalization is suspicious enough to reject outright.+ if (normalize(targetPath).split(sep).join("/") !== targetPath) {+ return Object.freeze([+ err("target-traversal", "target", "target must be a normalized relative path"),+ ]);+ }+ if (RESERVED_FILES.has(targetPath)) {+ errors.push(err("target-reserved", "target", `${targetPath} is machine-owned`));+ }+ for (const prefix of RESERVED_PREFIXES) {+ if (targetPath.startsWith(prefix)) {+ errors.push(err("target-reserved", "target", `${prefix} is a reserved namespace`));+ }+ }+ if (errors.length === 0 && !targetPath.endsWith(".md")) {+ errors.push(err("target-extension", "target", "target must be a .md note"));+ }+ return Object.freeze(errors);+}++export interface ValidateArtifactOptions {+ /** Schema-pack page type the artifact must declare, if any. */+ readonly schemaType?: string | null;+ /** Resolved vocabulary; required when `schemaType` is set. */+ readonly vocabulary?: BrainSchemaVocabulary;+}++/**+ * Validate a submitted artifact body. Order matters: cheap structural+ * checks first so the error list reads top-down like a fix list.+ */+export function validateArtifact(+ artifact: string,+ options: ValidateArtifactOptions,+): ReadonlyArray<WriteSessionError> {+ const errors: WriteSessionError[] = [];+ if (typeof artifact !== "string" || artifact.trim() === "") {+ return Object.freeze([err("artifact-empty", "body", "artifact is empty")]);+ }+ if (Buffer.byteLength(artifact, "utf8") > ARTIFACT_MAX_BYTES) {+ errors.push(err("artifact-too-large", "body", `artifact exceeds ${ARTIFACT_MAX_BYTES} bytes`));+ }+ if (hasForbiddenControlChar(artifact)) {+ errors.push(err("artifact-control-chars", "body", "artifact carries raw control characters"));+ }++ if (!artifact.startsWith("---\n")) {+ errors.push(err("frontmatter-missing", "frontmatter", "artifact has no frontmatter block"));+ return Object.freeze(errors);+ }+ let meta: Readonly<Record<string, unknown>>;+ try {+ [meta] = parseFrontmatterText(artifact);+ } catch (exc) {+ errors.push(err("frontmatter-malformed", "frontmatter", (exc as Error).message));+ return Object.freeze(errors);+ }+ if (Object.keys(meta).length === 0) {+ errors.push(err("frontmatter-missing", "frontmatter", "frontmatter block has no keys"));+ return Object.freeze(errors);+ }++ const schemaType = options.schemaType?.trim();+ if (schemaType) {+ const vocab = options.vocabulary;+ if (vocab === undefined || !isKnownSchemaToken(vocab, "page_types", schemaType)) {+ errors.push(+ err(+ "schema-type-unknown",+ "type",+ `schema type '${schemaType}' is not declared in page_types`,+ ),+ );+ } else {+ const declared = typeof meta["type"] === "string" ? meta["type"].trim().toLowerCase() : "";+ if (declared !== schemaType.toLowerCase()) {+ errors.push(+ err("schema-type-mismatch", "type", `frontmatter must declare type: ${schemaType}`),+ );+ }+ }+ }+ if (+ meta["tags"] !== undefined &&+ (!Array.isArray(meta["tags"]) || !meta["tags"].every((t) => typeof t === "string"))+ ) {+ errors.push(err("tags-malformed", "tags", "tags must be an array of strings"));+ }+ return Object.freeze(errors);+}++/**+ * Compact correction prompt for the `needs-correction` envelope. One+ * line per error; the closing instruction asks for the FULL artifact+ * so a partial patch never half-lands.+ */+export function buildCorrectionPrompt(errors: ReadonlyArray<WriteSessionError>): string {+ const lines = errors.map((e) => `- [${e.code}] ${e.path}: ${e.message}`);+ return [+ "The previous submission failed validation. Fix every issue below and resubmit the full corrected artifact:",+ ...lines,+ ].join("\n");+}++/**+ * Collision metadata for an occupied target. Returns null when the+ * path is free; the engine attaches the result to envelopes so the+ * caller can decide on overwrite/merge intent with evidence in hand.+ */+export function inspectExistingTarget(+ vault: string,+ targetPath: string,+): ExistingTargetInfo | null {+ const absolute = join(vault, targetPath);+ if (!existsSync(absolute)) return null;+ let content: string;+ try {+ if (!statSync(absolute).isFile()) return null;+ content = readFileSync(absolute, "utf8");+ } catch {+ return null;+ }+ const heading = /^#{1,6}\s+(.+)$/m.exec(content);+ return Object.freeze({+ bytes: Buffer.byteLength(content, "utf8"),+ content_hash: createHash("sha256").update(content, "utf8").digest("hex"),+ first_heading: heading?.[1]?.trim() ?? null,+ });+}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 2bc6f741..4838b3a6 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -184,6 +184,17 @@ import {import { appendLogEvent } from "../core/brain/log.ts";import type { BrainLogEntry } from "../core/brain/log.ts";import { appendBrainNote } from "../core/brain/note.ts";+import { mirrorSignal, resolveSharedNamespace } from "../core/brain/shared-namespace.ts";+import {+ WriteSessionRequestError,+ abandonSession,+ approveSession,+ openArtifactSession,+ sessionEnvelope,+} from "../core/brain/write-session/engine.ts";+import { dispatchSubmit, openPanelSession } from "../core/brain/write-session/panel.ts";+import { listWriteSessions, readWriteSession } from "../core/brain/write-session/store.ts";+import type { WriteSessionEnvelope } from "../core/brain/write-session/types.ts";import { buildMcpLandscape } from "../core/graph/mcp-config.ts";import {appendPinnedContext,@@ -260,7 +271,7 @@ async function toolBrainFeedback(// audit trail in `Brain/log/` and `inbox/processed/` stays consistent// across CLI and MCP entry points. `--force-confirmed` ADDITIONALLY// creates a confirmed pref below.- const sigResult = writeSignal(ctx.vault, {+ const signalInput = {topic,signal: signalRaw as BrainSignalSign,agent,@@ -271,7 +282,13 @@ async function toolBrainFeedback(...(scope ? { scope } : {}),...(source && source.length > 0 ? { source: [...source] } : {}),...(raw ? { raw } : {}),- });+ };+ const sigResult = writeSignal(ctx.vault, signalInput);+ // t_936a1a61: fail-soft mirror into the shared namespace AFTER the+ // primary write; `mirror` is reported only when the key is configured.+ const sharedNamespace = resolveSharedNamespace(ctx.configPath);+ const mirror =+ sharedNamespace === null ? undefined : mirrorSignal(sharedNamespace, ctx.vault, signalInput);try {appendLogEvent(ctx.vault, {@@ -326,6 +343,7 @@ async function toolBrainFeedback(return {kind: prefResult ? "preference" : "signal",+ ...(mirror !== undefined ? { mirror } : {}),signal_path: vaultRelativeSafe(ctx.vault, sigResult.path),signal_absolute_path: resolve(sigResult.path),signal_id: sigResult.id,@@ -616,6 +634,133 @@ async function toolBrainNote(};}+// ----- brain_write_session (Agent Write Contract Suite, v0.41.0) ------------++/**+ * One agent-facing surface for the write-session kernel: `op`+ * discriminates the lifecycle operation, `kind` (open only) picks+ * artifact vs panel. Envelopes are the same JSON the CLI prints -+ * status, step, prompt, errors, attempts_left, expires_at, target.+ * Structured request failures surface as INVALID_PARAMS with the+ * machine-readable error list in the message.+ */+async function toolBrainWriteSession(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const op = coerceStr(args, "op", true)!;+ const sessionId = coerceStr(args, "session_id", false);+ const requireSessionId = (): string => {+ if (!sessionId) {+ throw new MCPError(INVALID_PARAMS, `brain_write_session: op '${op}' requires session_id`);+ }+ return sessionId;+ };+ try {+ switch (op) {+ case "open": {+ const kind = coerceStr(args, "kind", false) ?? "artifact";+ const agent =+ normalizeAgentArgument(coerceStr(args, "agent", false) ?? null) ??+ resolveAgentName(ctx.configPath ?? undefined);+ const requireReview = args["require_review"] === true;+ if (kind === "panel") {+ const topic = coerceStr(args, "topic", true)!;+ const personasRaw = args["personas"];+ const personas = Array.isArray(personasRaw)+ ? personasRaw.filter((x): x is string => typeof x === "string")+ : undefined;+ const target = coerceStr(args, "target", false);+ return asRecord(+ openPanelSession(ctx.vault, {+ agent,+ topic,+ requireReview,+ ...(personas && personas.length > 0 ? { personas } : {}),+ ...(target ? { targetPath: target } : {}),+ }),+ );+ }+ if (kind !== "artifact") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_write_session: kind must be 'artifact' or 'panel', got '${kind}'`,+ );+ }+ const target = coerceStr(args, "target", true)!;+ const intent = coerceStr(args, "intent", false) ?? "create";+ if (intent !== "create" && intent !== "overwrite" && intent !== "merge") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_write_session: intent must be create|overwrite|merge, got '${intent}'`,+ );+ }+ const schemaType = coerceStr(args, "schema_type", false);+ const prompt = coerceStr(args, "prompt", false);+ const retryCap = args["retry_cap"];+ return asRecord(+ openArtifactSession(ctx.vault, {+ agent,+ targetPath: target,+ intent,+ requireReview,+ ...(schemaType ? { schemaType } : {}),+ ...(prompt ? { prompt } : {}),+ ...(typeof retryCap === "number" ? { retryCap } : {}),+ }),+ );+ }+ case "submit": {+ const id = requireSessionId();+ const text = coerceStr(args, "text", true)!;+ return asRecord(dispatchSubmit(ctx.vault, { sessionId: id, text }));+ }+ case "approve":+ return asRecord(approveSession(ctx.vault, { sessionId: requireSessionId() }));+ case "abandon":+ return asRecord(abandonSession(ctx.vault, { sessionId: requireSessionId() }));+ case "status": {+ const id = requireSessionId();+ const probe = readWriteSession(ctx.vault, id, new Date().toISOString());+ if (probe.error !== null) throw new MCPError(INVALID_PARAMS, probe.error);+ if (probe.session === null) {+ throw new MCPError(INVALID_PARAMS, `unknown write-session: ${id}`);+ }+ return asRecord(sessionEnvelope(probe.session));+ }+ case "list": {+ const limit = coerceInt(args, "limit", 100, 1, 500);+ const sessions = listWriteSessions(ctx.vault, new Date().toISOString());+ return {+ total: sessions.length,+ sessions: sessions.slice(0, limit).map((rec) => asRecord(sessionEnvelope(rec))),+ };+ }+ default:+ throw new MCPError(+ INVALID_PARAMS,+ `brain_write_session: op must be open|submit|approve|abandon|status|list, got '${op}'`,+ );+ }+ } catch (err) {+ if (err instanceof WriteSessionRequestError) {+ // Preserve the {code, path, message} boundary contract: the+ // structured list rides MCPError's data slot, the message stays+ // human-readable prose.+ throw new MCPError(+ INVALID_PARAMS,+ err.message,+ err.errors.length > 0 ? { errors: err.errors } : undefined,+ );+ }+ throw err;+ }+}++function asRecord(envelope: WriteSessionEnvelope): Record<string, unknown> {+ return { ...envelope };+}+// ----- brain_context (v0.10.10) --------------------------------------------type PinnedContextOperation = "read" | "write" | "append" | "clear";@@ -3167,6 +3312,71 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([outputSchema: PINNED_CONTEXT_OUTPUT_SCHEMA,handler: toolBrainPinnedContext,},+ {+ name: "brain_write_session",+ description:+ "Provider-agnostic Brain write sessions (artifact and decision-panel kinds): open returns a generation prompt, submit validates the text, only clean artifacts commit. Correction loop, retry cap, collision guard, optional operator review. The calling agent generates; the Brain never does.",+ inputSchema: {+ type: "object",+ properties: {+ op: {+ type: "string",+ enum: ["open", "submit", "approve", "abandon", "status", "list"],+ description: "Lifecycle operation.",+ },+ kind: {+ type: "string",+ enum: ["artifact", "panel"],+ description: "Session kind for op=open. Defaults to artifact.",+ },+ session_id: {+ type: "string",+ description: "Session id (`ws-...`) for submit/approve/abandon/status.",+ },+ target: {+ type: "string",+ description:+ "Vault-relative commit target under Brain/ (artifact open; optional panel override). Reserved namespaces are refused.",+ },+ text: {+ type: "string",+ description:+ "Generated text for op=submit: the full artifact, a persona answer, or the synthesis.",+ },+ topic: { type: "string", description: "Decision topic (panel open)." },+ personas: {+ type: "array",+ items: { type: "string" },+ description:+ "Persona slugs to convene in order (panel open). Defaults to every loaded persona.",+ },+ schema_type: {+ type: "string",+ description: "Schema-pack page type the artifact must declare (artifact open).",+ },+ intent: {+ type: "string",+ enum: ["create", "overwrite", "merge"],+ description:+ "Commit intent against an existing target (artifact open). Default create - never overwrites.",+ },+ prompt: { type: "string", description: "Custom generation instruction (artifact open)." },+ require_review: {+ type: "boolean",+ description: "Park the validated artifact at needs-review until an operator approves.",+ },+ retry_cap: { type: "number", description: "Failed submits allowed per step (default 3)." },+ limit: {+ type: "number",+ description: "Max sessions returned by op=list (default 100, cap 500).",+ },+ agent: { type: "string", description: "Agent identity override (open)." },+ },+ required: ["op"],+ additionalProperties: false,+ },+ handler: toolBrainWriteSession,+ },{name: "brain_intention",description:diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 59b01535..c09b859d 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -86,6 +86,7 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.frbrain_pinned_context: "pinned.md is operator-curated and small by practice",brain_recall_feedback: "write; returns one event receipt plus bounded weights",brain_switch_vault: "write; returns a small profile ack",+ brain_write_session: "lifecycle ops return one fixed-shape envelope; prompts are kernel-bounded",schema_apply_mutations: "write; returns a bounded mutation receipt",payment_memory_init: "write; returns a bootstrap receipt",payment_receipt_append: "write; returns a single receipt path",diff --git a/tests/cli/brain-intent-review.test.ts b/tests/cli/brain-intent-review.test.tsindex a6a1ea08..897835b5 100644--- a/tests/cli/brain-intent-review.test.ts+++ b/tests/cli/brain-intent-review.test.ts@@ -37,7 +37,11 @@ afterEach(() => {describe("o2b brain intent-review", () => {test("prints JSON intent review report", async () => {- const result = await runCli(["brain", "intent-review", "--json"], {+ // Fixed --now keeps the fixture inside the clustering window: the+ // signals carry hardcoded May 2026 dates, and a wall-clock run+ // ages them out (the 2026-05-21 signal left the 14-day window on+ // 2026-06-04, flipping the decision to needs_more_evidence).+ const result = await runCli(["brain", "intent-review", "--json", "--now", "2026-05-24"], {env: { OPEN_SECOND_BRAIN_CONFIG: configPath },});expect(result.returncode).toBe(0);diff --git a/tests/cli/brain-panel.test.ts b/tests/cli/brain-panel.test.tsnew file mode 100644index 00000000..8bee9b19--- /dev/null+++ b/tests/cli/brain-panel.test.ts@@ -0,0 +1,92 @@+/**+ * `o2b brain panel` CLI surface (Agent Write Contract Suite,+ * t_0cc6fdff).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-panel-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++async function submitText(sessionId: string, text: string) {+ const file = join(tmp, "step.md");+ writeFileSync(file, text);+ const res = await runCli([+ "brain",+ "panel",+ "submit",+ sessionId,+ "--file",+ file,+ "--vault",+ vault,+ "--json",+ ]);+ expect(res.returncode).toBe(0);+ return JSON.parse(res.stdout) as { status: string; step: string; target_path: string };+}++test("panel open walks personas to a committed decision note", async () => {+ const opened = await runCli([+ "brain",+ "panel",+ "open",+ "Should we ship feature X",+ "--personas",+ "technical,risk",+ "--vault",+ vault,+ "--json",+ ]);+ expect(opened.returncode).toBe(0);+ const env = JSON.parse(opened.stdout) as { session_id: string; step: string; prompt: string };+ expect(env.step).toBe("persona:technical");+ expect(env.prompt).toContain("Should we ship feature X");++ let next = await submitText(env.session_id, "Feasible.");+ expect(next.step).toBe("persona:risk");+ next = await submitText(env.session_id, "Acceptable risk.");+ expect(next.step).toBe("synthesis");+ next = await submitText(env.session_id, "Ship it.");+ expect(next.status).toBe("done");++ const note = readFileSync(join(vault, next.target_path), "utf8");+ expect(note).toContain("kind: decision-panel");+ expect(note).toContain("## Synthesis");+});++test("panel status reports the live envelope", async () => {+ const opened = await runCli(["brain", "panel", "open", "Topic", "--vault", vault, "--json"]);+ const env = JSON.parse(opened.stdout) as { session_id: string };+ const status = await runCli([+ "brain",+ "panel",+ "status",+ env.session_id,+ "--vault",+ vault,+ "--json",+ ]);+ expect(status.returncode).toBe(0);+ expect(JSON.parse(status.stdout).kind).toBe("panel");+});++test("panel open without a topic exits 2", async () => {+ const res = await runCli(["brain", "panel", "open", "--vault", vault]);+ expect(res.returncode).toBe(2);+});diff --git a/tests/cli/brain-session.test.ts b/tests/cli/brain-session.test.tsnew file mode 100644index 00000000..3dc72a7d--- /dev/null+++ b/tests/cli/brain-session.test.ts@@ -0,0 +1,168 @@+/**+ * `o2b brain session` CLI surface (Agent Write Contract Suite,+ * t_bc36a8a2).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;++const GOOD = "---\nkind: note\n---\n\n# Session note\n\nBody.\n";++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-session-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++async function openSession(extra: string[] = []): Promise<{ session_id: string }> {+ const res = await runCli([+ "brain",+ "session",+ "open",+ "--target",+ "Brain/notes/cli.md",+ "--vault",+ vault,+ "--json",+ ...extra,+ ]);+ expect(res.returncode).toBe(0);+ return JSON.parse(res.stdout) as { session_id: string };+}++test("open -> submit --file drives a session to done", async () => {+ const opened = await openSession();+ const artifact = join(tmp, "artifact.md");+ writeFileSync(artifact, GOOD);+ const submitted = await runCli([+ "brain",+ "session",+ "submit",+ (opened as { session_id: string }).session_id,+ "--file",+ artifact,+ "--vault",+ vault,+ "--json",+ ]);+ expect(submitted.returncode).toBe(0);+ const env = JSON.parse(submitted.stdout) as { status: string };+ expect(env.status).toBe("done");+ expect(readFileSync(join(vault, "Brain", "notes", "cli.md"), "utf8")).toContain("# Session note");+});++test("invalid submit exits 1 with the correction envelope on stdout", async () => {+ const opened = await openSession();+ const artifact = join(tmp, "bad.md");+ writeFileSync(artifact, "no frontmatter");+ const submitted = await runCli([+ "brain",+ "session",+ "submit",+ opened.session_id,+ "--file",+ artifact,+ "--vault",+ vault,+ "--json",+ ]);+ expect(submitted.returncode).toBe(1);+ const env = JSON.parse(submitted.stdout) as {+ status: string;+ errors: Array<{ code: string }>;+ };+ expect(env.status).toBe("needs-correction");+ expect(env.errors.map((e) => e.code)).toContain("frontmatter-missing");+});++test("status, list, abandon, and sweep round-trip", async () => {+ const opened = await openSession();+ const status = await runCli([+ "brain",+ "session",+ "status",+ opened.session_id,+ "--vault",+ vault,+ "--json",+ ]);+ expect(JSON.parse(status.stdout).status).toBe("needs-llm-step");++ const list = await runCli(["brain", "session", "list", "--vault", vault, "--json"]);+ expect(JSON.parse(list.stdout).sessions).toHaveLength(1);++ const abandoned = await runCli([+ "brain",+ "session",+ "abandon",+ opened.session_id,+ "--vault",+ vault,+ "--json",+ ]);+ expect(JSON.parse(abandoned.stdout).status).toBe("failed");++ const swept = await runCli(["brain", "session", "sweep", "--vault", vault, "--json"]);+ expect(JSON.parse(swept.stdout).removed).toBe(1);+});++test("approve commits a reviewed session", async () => {+ const opened = await openSession(["--require-review"]);+ const artifact = join(tmp, "artifact.md");+ writeFileSync(artifact, GOOD);+ const submitted = await runCli([+ "brain",+ "session",+ "submit",+ opened.session_id,+ "--file",+ artifact,+ "--vault",+ vault,+ "--json",+ ]);+ expect(JSON.parse(submitted.stdout).status).toBe("needs-review");+ const approved = await runCli([+ "brain",+ "session",+ "approve",+ opened.session_id,+ "--vault",+ vault,+ "--json",+ ]);+ expect(approved.returncode).toBe(0);+ expect(JSON.parse(approved.stdout).status).toBe("done");+});++test("a reserved target is refused with exit 1 and structured errors", async () => {+ const res = await runCli([+ "brain",+ "session",+ "open",+ "--target",+ "Brain/preferences/pref-x.md",+ "--vault",+ vault,+ "--json",+ ]);+ expect(res.returncode).toBe(1);+ const body = JSON.parse(res.stdout) as { errors: Array<{ code: string }> };+ expect(body.errors.map((e) => e.code)).toContain("target-reserved");+});++test("usage errors exit 2", async () => {+ const res = await runCli(["brain", "session", "open", "--vault", vault]);+ expect(res.returncode).toBe(2);+});diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.tsindex 53df43cc..77c8dac7 100644--- a/tests/core/brain.types.test.ts+++ b/tests/core/brain.types.test.ts@@ -85,6 +85,8 @@ describe("BRAIN_* const enums", () => {"reconcile",// Runtime lifecycle hooks (v0.26.0)"session-lifecycle",+ // Agent Write Contract Suite (v0.41.0) terminal write-session audit+ "write-session",]);const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));expect(actual).toEqual(expected);diff --git a/tests/core/brain/agent-backend.test.ts b/tests/core/brain/agent-backend.test.tsnew file mode 100644index 00000000..4517d681--- /dev/null+++ b/tests/core/brain/agent-backend.test.ts@@ -0,0 +1,123 @@+/**+ * Memory-source backend boundary (Agent Write Contract Suite,+ * t_53f9f67f): protocol + registry + Claude adapter with config-driven+ * selection. The default backend must be byte-identical to calling the+ * claude-memory modules directly.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ DEFAULT_MEMORY_BACKEND_ID,+ getMemoryBackend,+ listMemoryBackends,+ resolveMemoryBackend,+} from "../../../src/core/brain/agent-backend/registry.ts";+import { claudeMemoryBackend } from "../../../src/core/brain/agent-backend/claude.ts";+import { parseClaudeMemoryFile } from "../../../src/core/brain/claude-memory-parser.ts";+import {+ renderPreferenceFromMemory,+ slugifyMemoryName,+} from "../../../src/core/brain/claude-memory-render.ts";+import { defaultMemoryDir } from "../../../src/core/brain/claude-memory-paths.ts";+import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-agent-backend-"));+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const MEMORY_FILE = [+ "---",+ "name: no_shouting_in_docs",+ "description: Avoid exclamation marks in documentation",+ "metadata:",+ " type: feedback",+ "---",+ "",+ "Do not use exclamation marks in technical documentation.",+ "",+ "**Why:** Tone consistency.",+ "**How to apply:** Use neutral punctuation.",+].join("\n");++test("registry lists the claude backend and resolves it by id", () => {+ const ids = listMemoryBackends().map((b) => b.id);+ expect(ids).toEqual(["claude"]);+ expect(getMemoryBackend("claude").id).toBe("claude");+ expect(DEFAULT_MEMORY_BACKEND_ID).toBe("claude");+});++test("an unknown backend id fails with the registered list in the message", () => {+ expect(() => getMemoryBackend("cursor")).toThrow(/unknown memory backend 'cursor'.*claude/);+});++test("resolveMemoryBackend defaults to claude and honors the memory_backend config key", () => {+ const configPath = join(tmp, "config.yaml");+ // A guaranteed-missing path keeps the default-resolution assertion+ // hermetic - the host machine's real config must not leak in.+ expect(resolveMemoryBackend(join(tmp, "missing-config.yaml")).id).toBe("claude");+ expect(resolveMemoryBackend(configPath).id).toBe("claude");++ writeFileSync(configPath, 'vault: "/tmp/x"\nmemory_backend: claude\n');+ expect(resolveMemoryBackend(configPath).id).toBe("claude");++ writeFileSync(configPath, 'vault: "/tmp/x"\nmemory_backend: bogus\n');+ expect(() => resolveMemoryBackend(configPath)).toThrow(/unknown memory backend 'bogus'/);+});++test("the claude adapter is byte-identical to the claude-memory modules", () => {+ const parsed = claudeMemoryBackend.parseMemoryFile(MEMORY_FILE);+ expect(parsed).toEqual(parseClaudeMemoryFile(MEMORY_FILE));+ if (parsed.kind !== "feedback") throw new Error("fixture must parse as feedback");++ expect(claudeMemoryBackend.slugifyName(parsed.name)).toBe(slugifyMemoryName(parsed.name));++ const renderInput = {+ name: parsed.name,+ description: parsed.description,+ body: parsed.body,+ memoryPath: "/home/u/.claude/projects/-x/memory/no_shouting.md",+ importedAt: "2026-06-04T10:00:00Z",+ bodySha256: parsed.bodySha256,+ };+ expect(claudeMemoryBackend.renderPreference(renderInput)).toBe(+ renderPreferenceFromMemory(renderInput),+ );++ expect(claudeMemoryBackend.discoverMemoryDir("/srv/projects/demo")).toBe(+ defaultMemoryDir("/srv/projects/demo"),+ );+});++test("importClaudeMemory through an explicit backend matches the default path", () => {+ const vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ const memoryDir = join(tmp, "memory");+ mkdirSync(memoryDir, { recursive: true });+ writeFileSync(join(memoryDir, "no_shouting_in_docs.md"), MEMORY_FILE);++ const baseline = importClaudeMemory({+ vault,+ memoryDir,+ mode: "dry-run",+ allowArbitraryMemoryPath: true,+ });+ const viaBackend = importClaudeMemory({+ vault,+ memoryDir,+ mode: "dry-run",+ allowArbitraryMemoryPath: true,+ backend: claudeMemoryBackend,+ });+ expect(viaBackend.plans).toEqual(baseline.plans);+ expect(viaBackend.skipped).toEqual(baseline.skipped);+});diff --git a/tests/core/brain/shared-namespace.test.ts b/tests/core/brain/shared-namespace.test.tsnew file mode 100644index 00000000..fe2b16f2--- /dev/null+++ b/tests/core/brain/shared-namespace.test.ts@@ -0,0 +1,158 @@+/**+ * Cross-agent shared memory namespace (Agent Write Contract Suite,+ * t_936a1a61): opt-in mirror of explicit remember-writes into a shared+ * vault, per-agent + origin attribution, fail-soft mirroring.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ mirrorNote,+ mirrorSignal,+ resolveSharedNamespace,+} from "../../../src/core/brain/shared-namespace.ts";+import { appendBrainNote } from "../../../src/core/brain/note.ts";+import { parseSignal } from "../../../src/core/brain/signal.ts";+import { parseLogDay } from "../../../src/core/brain/log.ts";+import { buildToolTable, findTool, type ServerContext } from "../../../src/mcp/tools.ts";++let tmp: string;+let vault: string;+let shared: string;+let configPath: string;++const SIGNAL_INPUT = {+ topic: "mirror-topic",+ signal: "positive" as const,+ agent: "coding-agent",+ principle: "Mirrored facts stay attributed.",+ created_at: "2026-06-04T10:00:00Z",+ date: "2026-06-04",+ slug: "mirror-topic",+};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-shared-ns-"));+ vault = join(tmp, "vault");+ shared = join(tmp, "shared");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ mkdirSync(join(shared, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\nshared_namespace: "${shared}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("resolveSharedNamespace reads the config key; absent means off", () => {+ expect(resolveSharedNamespace(configPath)).toBe(shared);+ writeFileSync(configPath, `vault: "${vault}"\n`);+ expect(resolveSharedNamespace(configPath)).toBeNull();+ expect(resolveSharedNamespace(join(tmp, "missing.yaml"))).toBeNull();+});++test("mirrorSignal lands the signal in the shared vault with origin attribution", () => {+ expect(mirrorSignal(shared, vault, SIGNAL_INPUT)).toBe("ok");+ const inbox = join(shared, "Brain", "inbox");+ const files = readdirSync(inbox).filter((f) => f.endsWith(".md"));+ expect(files).toHaveLength(1);+ const signal = parseSignal(join(inbox, files[0]!));+ expect(signal.agent).toBe("coding-agent");+ const text = readFileSync(join(inbox, files[0]!), "utf8");+ expect(text).toContain("origin_vault: vault");+});++test("a broken shared namespace degrades to failed without throwing", () => {+ rmSync(shared, { recursive: true, force: true });+ writeFileSync(shared, "not a directory");+ expect(mirrorSignal(shared, vault, SIGNAL_INPUT)).toBe("failed");+ expect(mirrorNote(shared, vault, { text: "hello", agent: "coding-agent" })).toBe("failed");+});++test("a shared namespace pointing at the origin vault is refused as failed", () => {+ expect(mirrorSignal(vault, vault, SIGNAL_INPUT)).toBe("failed");+ expect(mirrorNote(vault, vault, { text: "self", agent: "a" })).toBe("failed");+ expect(readdirSync(join(vault, "Brain")).some((f) => f === "inbox")).toBe(false);+});++test("mirrorNote lands a note event with origin attribution", () => {+ expect(+ mirrorNote(shared, vault, {+ text: "released v1",+ agent: "coding-agent",+ now: new Date("2026-06-04T10:00:00Z"),+ }),+ ).toBe("ok");+ const { entries } = parseLogDay(shared, "2026-06-04");+ expect(entries).toHaveLength(1);+ expect(entries[0]!.eventType).toBe("note");+ expect(entries[0]!.body["origin_vault"]).toBe("vault");+ expect(entries[0]!.body["agent"]).toBe("coding-agent");+});++test("appendBrainNote mirrors when configured and reports the outcome", () => {+ const res = appendBrainNote({+ vault,+ text: "fact discovered",+ agent: "coding-agent",+ configPath,+ now: new Date("2026-06-04T10:00:00Z"),+ });+ expect(res.mirror).toBe("ok");+ expect(parseLogDay(shared, "2026-06-04").entries).toHaveLength(1);+ // Primary log always lands regardless of mirror state.+ expect(parseLogDay(vault, "2026-06-04").entries).toHaveLength(1);+});++test("appendBrainNote without the key stays silent about mirroring", () => {+ writeFileSync(configPath, `vault: "${vault}"\n`);+ const res = appendBrainNote({ vault, text: "no mirror", agent: "a", configPath });+ expect(res.mirror).toBeUndefined();+});++test("MCP brain_feedback mirrors the signal and reports mirror: ok", async () => {+ const ctx: ServerContext = { vault, configPath, repoRoot: null };+ const tool = findTool(buildToolTable("writer"), "brain_feedback");+ const res = (await tool.handler(ctx, {+ topic: "mirror-topic",+ signal: "positive",+ principle: "Mirrored facts stay attributed.",+ agent: "coding-agent",+ })) as Record<string, unknown>;+ expect(res["mirror"]).toBe("ok");+ const files = readdirSync(join(shared, "Brain", "inbox")).filter((f) => f.endsWith(".md"));+ expect(files).toHaveLength(1);+});++test("MCP brain_feedback mirror failure never breaks the primary write", async () => {+ rmSync(shared, { recursive: true, force: true });+ writeFileSync(shared, "not a directory");+ const ctx: ServerContext = { vault, configPath, repoRoot: null };+ const tool = findTool(buildToolTable("writer"), "brain_feedback");+ const res = (await tool.handler(ctx, {+ topic: "mirror-topic",+ signal: "positive",+ principle: "Primary write survives.",+ agent: "coding-agent",+ })) as Record<string, unknown>;+ expect(res["mirror"]).toBe("failed");+ const files = readdirSync(join(vault, "Brain", "inbox")).filter((f) => f.endsWith(".md"));+ expect(files).toHaveLength(1);+});++test("unconfigured setups keep the previous result shape (no mirror key)", async () => {+ writeFileSync(configPath, `vault: "${vault}"\n`);+ const ctx: ServerContext = { vault, configPath, repoRoot: null };+ const tool = findTool(buildToolTable("writer"), "brain_feedback");+ const res = (await tool.handler(ctx, {+ topic: "plain",+ signal: "positive",+ principle: "No mirror configured.",+ agent: "coding-agent",+ })) as Record<string, unknown>;+ expect("mirror" in res).toBe(false);+});diff --git a/tests/core/brain/write-session/engine.test.ts b/tests/core/brain/write-session/engine.test.tsnew file mode 100644index 00000000..d720ce9f--- /dev/null+++ b/tests/core/brain/write-session/engine.test.ts@@ -0,0 +1,232 @@+/**+ * Write-session engine: lifecycle, correction loop, collision guard,+ * review gate, audit (Agent Write Contract Suite, t_bc36a8a2).+ */++import { afterEach, beforeEach, 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 {+ WriteSessionRequestError,+ abandonSession,+ approveSession,+ openArtifactSession,+ sessionEnvelope,+ submitToSession,+} from "../../../../src/core/brain/write-session/engine.ts";+import { readWriteSession } from "../../../../src/core/brain/write-session/store.ts";+import { parseLogDay } from "../../../../src/core/brain/log.ts";++let tmp: string;+let vault: string;++const NOW = "2026-06-04T10:00:00.000Z";+const DATE = "2026-06-04";++const GOOD = ["---", "kind: note", "---", "", "# Decision record", "", "We adopt it."].join("\n");++function open(over: Record<string, unknown> = {}) {+ return openArtifactSession(vault, {+ agent: "fixture-agent",+ targetPath: "Brain/notes/adr.md",+ now: NOW,+ ...over,+ });+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-ws-engine-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("open returns a needs-llm-step envelope with prompt, hints, and ttl", () => {+ const env = open({ schemaType: "note" });+ expect(env.status).toBe("needs-llm-step");+ expect(env.kind).toBe("artifact");+ expect(env.step).toBe("artifact");+ expect(env.session_id).toMatch(/^ws-/);+ expect(env.prompt).toContain("Brain/notes/adr.md");+ expect(env.schema_hints.some((h) => h.includes("type: note"))).toBe(true);+ expect(env.attempts_left).toBe(3);+ expect(Date.parse(env.expires_at) - Date.parse(NOW)).toBe(24 * 3600 * 1000);+ expect(env.existing).toBeNull();+});++test("open rejects an invalid target with structured errors", () => {+ try {+ open({ targetPath: "Brain/preferences/pref-x.md" });+ throw new Error("expected WriteSessionRequestError");+ } catch (exc) {+ expect(exc).toBeInstanceOf(WriteSessionRequestError);+ const errors = (exc as WriteSessionRequestError).errors;+ expect(errors.map((e) => e.code)).toContain("target-reserved");+ }+});++test("open against an occupied target attaches existing metadata", () => {+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ writeFileSync(join(vault, "Brain", "notes", "adr.md"), "---\nkind: note\n---\n\n# Old\n");+ const env = open();+ expect(env.existing).not.toBeNull();+ expect(env.existing!.first_heading).toBe("Old");+});++test("invalid submit returns needs-correction, preserves state, decrements attempts", () => {+ const opened = open();+ const env = submitToSession(vault, {+ sessionId: opened.session_id,+ artifact: "# no frontmatter",+ now: NOW,+ });+ expect(env.status).toBe("needs-correction");+ expect(env.errors.map((e) => e.code)).toContain("frontmatter-missing");+ expect(env.prompt).toContain("resubmit the full corrected artifact");+ expect(env.attempts_left).toBe(2);+ expect(env.target_path).toBe("Brain/notes/adr.md");+});++test("retry cap exhaustion is terminal failed with an audit event", () => {+ const opened = open({ retryCap: 2 });+ submitToSession(vault, { sessionId: opened.session_id, artifact: "bad", now: NOW });+ const env = submitToSession(vault, { sessionId: opened.session_id, artifact: "bad", now: NOW });+ expect(env.status).toBe("failed");+ expect(env.attempts_left).toBe(0);+ const probe = readWriteSession(vault, opened.session_id, NOW);+ expect(probe.session!.failReason).toBe("retry-cap");+ const { entries } = parseLogDay(vault, DATE);+ const audit = entries.filter((e) => e.eventType === "write-session");+ expect(audit).toHaveLength(1);+ expect(audit[0]!.body["status"]).toBe("failed");+});++test("valid submit commits atomically and is terminal done", () => {+ const opened = open();+ const env = submitToSession(vault, { sessionId: opened.session_id, artifact: GOOD, now: NOW });+ expect(env.status).toBe("done");+ const committed = readFileSync(join(vault, "Brain", "notes", "adr.md"), "utf8");+ expect(committed).toContain("# Decision record");+ expect(committed.endsWith("\n")).toBe(true);+ const { entries } = parseLogDay(vault, DATE);+ const audit = entries.filter((e) => e.eventType === "write-session");+ expect(audit).toHaveLength(1);+ expect(audit[0]!.body["status"]).toBe("done");+ expect(audit[0]!.body["target"]).toBe("Brain/notes/adr.md");+ // terminal: a second submit is rejected+ expect(() =>+ submitToSession(vault, { sessionId: opened.session_id, artifact: GOOD, now: NOW }),+ ).toThrow(/terminal/);+});++test("create intent never overwrites an existing target", () => {+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ writeFileSync(join(vault, "Brain", "notes", "adr.md"), "PRECIOUS\n");+ const opened = open();+ const env = submitToSession(vault, { sessionId: opened.session_id, artifact: GOOD, now: NOW });+ expect(env.status).toBe("needs-correction");+ expect(env.errors.map((e) => e.code)).toContain("target-exists");+ expect(readFileSync(join(vault, "Brain", "notes", "adr.md"), "utf8")).toBe("PRECIOUS\n");+});++test("overwrite intent replaces; merge intent appends a delimited section", () => {+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ writeFileSync(join(vault, "Brain", "notes", "adr.md"), "---\nkind: note\n---\n\n# Old\n");++ const over = open({ intent: "overwrite" });+ expect(+ submitToSession(vault, { sessionId: over.session_id, artifact: GOOD, now: NOW }).status,+ ).toBe("done");+ expect(readFileSync(join(vault, "Brain", "notes", "adr.md"), "utf8")).not.toContain("# Old");++ writeFileSync(join(vault, "Brain", "notes", "adr.md"), "---\nkind: note\n---\n\n# Old\n");+ const merge = open({ intent: "merge" });+ expect(+ submitToSession(vault, { sessionId: merge.session_id, artifact: GOOD, now: NOW }).status,+ ).toBe("done");+ const merged = readFileSync(join(vault, "Brain", "notes", "adr.md"), "utf8");+ expect(merged).toContain("# Old");+ expect(merged).toContain("# Decision record");+ expect(merged.indexOf("# Old")).toBeLessThan(merged.indexOf("# Decision record"));+ expect(merged).toContain(merge.session_id);+});++test("require_review stops at needs-review; approve commits", () => {+ const opened = open({ requireReview: true });+ const env = submitToSession(vault, { sessionId: opened.session_id, artifact: GOOD, now: NOW });+ expect(env.status).toBe("needs-review");+ expect(existsSync(join(vault, "Brain", "notes", "adr.md"))).toBe(false);++ const approved = approveSession(vault, { sessionId: opened.session_id, now: NOW });+ expect(approved.status).toBe("done");+ expect(readFileSync(join(vault, "Brain", "notes", "adr.md"), "utf8")).toContain(+ "# Decision record",+ );+ const { entries } = parseLogDay(vault, DATE);+ const audit = entries.filter((e) => e.eventType === "write-session");+ expect(audit).toHaveLength(1);+ expect(audit[0]!.body["review"]).toBe("required");+});++test("approve outside needs-review is a structured error", () => {+ const opened = open();+ expect(() => approveSession(vault, { sessionId: opened.session_id, now: NOW })).toThrow(+ WriteSessionRequestError,+ );+});++test("abandon is terminal failed/abandoned with audit", () => {+ const opened = open();+ const env = abandonSession(vault, { sessionId: opened.session_id, now: NOW });+ expect(env.status).toBe("failed");+ const probe = readWriteSession(vault, opened.session_id, NOW);+ expect(probe.session!.failReason).toBe("abandoned");+ const { entries } = parseLogDay(vault, DATE);+ expect(entries.filter((e) => e.eventType === "write-session")).toHaveLength(1);+});++test("an expired session is audited exactly once across repeated ops", () => {+ const opened = open({ ttlMs: 1000 });+ const LATER = "2026-06-04T11:00:00Z";+ for (let i = 0; i < 3; i++) {+ expect(() =>+ submitToSession(vault, { sessionId: opened.session_id, artifact: GOOD, now: LATER }),+ ).toThrow(/terminal/);+ }+ const { entries } = parseLogDay(vault, DATE);+ const audit = entries.filter((e) => e.eventType === "write-session");+ expect(audit).toHaveLength(1);+ expect(audit[0]!.body["reason"]).toBe("expired");+});++test("an expired session refuses submits with a terminal error", () => {+ const opened = open({ ttlMs: 1000 });+ expect(() =>+ submitToSession(vault, {+ sessionId: opened.session_id,+ artifact: GOOD,+ now: "2026-06-04T11:00:00Z",+ }),+ ).toThrow(/expired|terminal/);+});++test("sessionEnvelope reflects current state for status queries", () => {+ const opened = open();+ submitToSession(vault, { sessionId: opened.session_id, artifact: "bad", now: NOW });+ const probe = readWriteSession(vault, opened.session_id, NOW);+ const env = sessionEnvelope(probe.session!);+ expect(env.status).toBe("needs-correction");+ expect(env.attempts_left).toBe(2);+ expect(env.session_id).toBe(opened.session_id);+});++test("unknown session id is a structured error", () => {+ expect(() =>+ submitToSession(vault, { sessionId: "ws-20990101-000000", artifact: GOOD, now: NOW }),+ ).toThrow(WriteSessionRequestError);+});diff --git a/tests/core/brain/write-session/panel.test.ts b/tests/core/brain/write-session/panel.test.tsnew file mode 100644index 00000000..7a2d88d4--- /dev/null+++ b/tests/core/brain/write-session/panel.test.ts@@ -0,0 +1,221 @@+/**+ * Decision panel as a write-session kind+ * (Agent Write Contract Suite, t_0cc6fdff on the t_bc36a8a2 kernel).+ */++import { afterEach, beforeEach, 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 {+ DEFAULT_PERSONAS,+ loadPersonas,+} from "../../../../src/core/brain/write-session/personas.ts";+import {+ dispatchSubmit,+ openPanelSession,+ submitToPanelSession,+} from "../../../../src/core/brain/write-session/panel.ts";+import {+ WriteSessionRequestError,+ approveSession,+ openArtifactSession,+} from "../../../../src/core/brain/write-session/engine.ts";+import { readWriteSession } from "../../../../src/core/brain/write-session/store.ts";+import { parseLogDay } from "../../../../src/core/brain/log.ts";+import { parseFrontmatter } from "../../../../src/core/vault.ts";++let tmp: string;+let vault: string;++const NOW = "2026-06-04T10:00:00.000Z";++function openPanel(over: Record<string, unknown> = {}) {+ return openPanelSession(vault, {+ agent: "fixture-agent",+ topic: "Adopt the new sync engine",+ now: NOW,+ ...over,+ });+}++function drivePersonas(sessionId: string): ReturnType<typeof submitToPanelSession> {+ let env = submitToPanelSession(vault, {+ sessionId,+ text: "Technically feasible with bounded effort.",+ now: NOW,+ });+ env = submitToPanelSession(vault, { sessionId, text: "Strategically sound.", now: NOW });+ env = submitToPanelSession(vault, { sessionId, text: "Risk is acceptable.", now: NOW });+ env = submitToPanelSession(vault, { sessionId, text: "Users benefit immediately.", now: NOW });+ return env;+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-ws-panel-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++// ----- personas --------------------------------------------------------------++test("built-in default personas cover the four lenses in declared order", () => {+ expect(DEFAULT_PERSONAS.map((p) => p.slug)).toEqual([+ "technical",+ "strategic",+ "risk",+ "user-experience",+ ]);+ for (const persona of DEFAULT_PERSONAS) {+ expect(persona.lens.length).toBeGreaterThan(0);+ expect(persona.prompt.length).toBeGreaterThan(0);+ }+});++test("loadPersonas falls back to defaults and reads Brain/personas/ when present", () => {+ expect(loadPersonas(vault).map((p) => p.slug)).toEqual(DEFAULT_PERSONAS.map((p) => p.slug));++ const dir = join(vault, "Brain", "personas");+ mkdirSync(dir, { recursive: true });+ writeFileSync(+ join(dir, "contrarian.md"),+ "---\nkind: persona\nlens: devil's advocate\n---\n\nArgue against the proposal.\n",+ );+ writeFileSync(join(dir, "ignored.md"), "---\nkind: note\n---\n\nNot a persona.\n");+ const personas = loadPersonas(vault);+ expect(personas.map((p) => p.slug)).toEqual(["contrarian"]);+ expect(personas[0]!.lens).toBe("devil's advocate");+ expect(personas[0]!.prompt).toContain("Argue against");+});++// ----- panel lifecycle --------------------------------------------------------++test("open walks persona steps in order, then synthesis, then commits the note", () => {+ const opened = openPanel();+ expect(opened.status).toBe("needs-llm-step");+ expect(opened.kind).toBe("panel");+ expect(opened.step).toBe("persona:technical");+ expect(opened.prompt).toContain("Adopt the new sync engine");+ expect(opened.target_path).toBe(+ "Brain/decisions/panels/panel-2026-06-04-adopt-the-new-sync-engine.md",+ );++ const afterPersonas = drivePersonas(opened.session_id);+ expect(afterPersonas.step).toBe("synthesis");+ expect(afterPersonas.status).toBe("needs-llm-step");+ expect(afterPersonas.prompt).toContain("Technically feasible");+ expect(afterPersonas.prompt).toContain("Users benefit immediately.");++ const done = submitToPanelSession(vault, {+ sessionId: opened.session_id,+ text: "Adopt it; risks are manageable.",+ now: NOW,+ });+ expect(done.status).toBe("done");++ const note = readFileSync(join(vault, done.target_path), "utf8");+ const [meta, body] = parseFrontmatter(join(vault, done.target_path));+ expect(meta["kind"]).toBe("decision-panel");+ expect(meta["topic"]).toBe("Adopt the new sync engine");+ expect(meta["personas"]).toEqual(["technical", "strategic", "risk", "user-experience"]);+ expect(body).toContain("## Synthesis");+ expect(body).toContain("Adopt it; risks are manageable.");+ expect(note).toContain("Risk is acceptable.");++ const { entries } = parseLogDay(vault, "2026-06-04");+ const audit = entries.filter((e) => e.eventType === "write-session");+ expect(audit).toHaveLength(1);+ expect(audit[0]!.body["kind"]).toBe("panel");+});++test("an empty persona answer is a correction, not an advance", () => {+ const opened = openPanel();+ const env = submitToPanelSession(vault, { sessionId: opened.session_id, text: " ", now: NOW });+ expect(env.status).toBe("needs-correction");+ expect(env.step).toBe("persona:technical");+ expect(env.errors.map((e) => e.code)).toContain("step-empty");+ const retry = submitToPanelSession(vault, {+ sessionId: opened.session_id,+ text: "Feasible.",+ now: NOW,+ });+ expect(retry.step).toBe("persona:strategic");+ expect(retry.attempts_left).toBe(3);+});++test("a persona subset can be requested at open", () => {+ const opened = openPanel({ personas: ["risk", "technical"] });+ expect(opened.step).toBe("persona:risk");+ const next = submitToPanelSession(vault, {+ sessionId: opened.session_id,+ text: "Low risk.",+ now: NOW,+ });+ expect(next.step).toBe("persona:technical");+});++test("unknown persona selection is a structured error", () => {+ expect(() => openPanel({ personas: ["nonexistent"] })).toThrow(WriteSessionRequestError);+});++test("require_review parks the rendered note for operator approval", () => {+ const opened = openPanel({ requireReview: true });+ drivePersonas(opened.session_id);+ const parked = submitToPanelSession(vault, {+ sessionId: opened.session_id,+ text: "Adopt.",+ now: NOW,+ });+ expect(parked.status).toBe("needs-review");+ expect(existsSync(join(vault, parked.target_path))).toBe(false);+ const approved = approveSession(vault, { sessionId: opened.session_id, now: NOW });+ expect(approved.status).toBe("done");+ expect(readFileSync(join(vault, parked.target_path), "utf8")).toContain("## Synthesis");+});++test("panel synthesis never overwrites an existing target", () => {+ const target = "Brain/decisions/panels/manual.md";+ mkdirSync(join(vault, "Brain", "decisions", "panels"), { recursive: true });+ writeFileSync(join(vault, target), "PRECIOUS\n");+ const opened = openPanel({ targetPath: target, personas: ["technical"] });+ submitToPanelSession(vault, { sessionId: opened.session_id, text: "Feasible.", now: NOW });+ const env = submitToPanelSession(vault, {+ sessionId: opened.session_id,+ text: "Adopt.",+ now: NOW,+ });+ expect(env.status).toBe("needs-correction");+ expect(env.errors.map((e) => e.code)).toContain("target-exists");+ expect(readFileSync(join(vault, target), "utf8")).toBe("PRECIOUS\n");+});++test("dispatchSubmit routes by session kind", () => {+ const panel = openPanel();+ expect(dispatchSubmit(vault, { sessionId: panel.session_id, text: "Fine.", now: NOW }).step).toBe(+ "persona:strategic",+ );+ const artifact = openArtifactSession(vault, {+ agent: "fixture-agent",+ targetPath: "Brain/notes/x.md",+ now: NOW,+ });+ const env = dispatchSubmit(vault, {+ sessionId: artifact.session_id,+ text: "---\nkind: note\n---\n\n# X\n",+ now: NOW,+ });+ expect(env.status).toBe("done");+});++test("panel responses survive process restarts via the session file", () => {+ const opened = openPanel();+ submitToPanelSession(vault, { sessionId: opened.session_id, text: "Feasible.", now: NOW });+ const probe = readWriteSession(vault, opened.session_id, NOW);+ expect(probe.session!.responses["persona:technical"]).toBe("Feasible.");+ expect(probe.session!.step).toBe("persona:strategic");+});diff --git a/tests/core/brain/write-session/store.test.ts b/tests/core/brain/write-session/store.test.tsnew file mode 100644index 00000000..b11295cd--- /dev/null+++ b/tests/core/brain/write-session/store.test.ts@@ -0,0 +1,207 @@+/**+ * Write-session store (Agent Write Contract Suite, t_bc36a8a2).+ *+ * One JSON file per session under `Brain/.sessions/write/`, snake_case+ * on disk, lazy TTL on read, sweep for terminal/expired files.+ */++import { afterEach, beforeEach, 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 {+ allocateWriteSessionId,+ createWriteSession,+ deleteWriteSession,+ isWriteSessionId,+ listWriteSessions,+ readWriteSession,+ saveWriteSession,+ sweepWriteSessions,+ writeSessionDir,+ writeSessionPath,+} from "../../../../src/core/brain/write-session/store.ts";+import type { WriteSessionRecord } from "../../../../src/core/brain/write-session/types.ts";++let tmp: string;+let vault: string;++const NOW = "2026-06-04T10:00:00Z";+const LATER = "2026-06-05T11:00:00Z";++function record(id: string, over: Partial<WriteSessionRecord> = {}): WriteSessionRecord {+ return {+ id,+ kind: "artifact",+ status: "needs-llm-step",+ step: "artifact",+ agent: "fixture-agent",+ createdAt: NOW,+ updatedAt: NOW,+ expiresAt: "2026-06-05T10:00:00Z",+ attempts: 0,+ retryCap: 3,+ targetPath: "Brain/notes/fixture.md",+ intent: "create",+ requireReview: false,+ prompt: "Write the fixture note.",+ schemaType: null,+ topic: null,+ personas: [],+ responses: {},+ pendingArtifact: null,+ lastErrors: [],+ failReason: null,+ ...over,+ };+}++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-ws-store-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("writeSessionDir nests under Brain/.sessions/write", () => {+ expect(writeSessionDir(vault)).toBe(join(vault, "Brain", ".sessions", "write"));+});++test("session id grammar accepts allocated ids and rejects traversal shapes", () => {+ const id = allocateWriteSessionId(vault, NOW);+ expect(isWriteSessionId(id)).toBe(true);+ expect(id.startsWith("ws-")).toBe(true);+ expect(isWriteSessionId("../../etc/passwd")).toBe(false);+ expect(isWriteSessionId("ws-UPPER")).toBe(false);+ expect(isWriteSessionId("")).toBe(false);+ expect(() => writeSessionPath(vault, "../escape")).toThrow(/session id/);+});++test("createWriteSession claims ids exclusively - same-second creates never collide", () => {+ const a = createWriteSession(vault, NOW, (id) => record(id));+ const b = createWriteSession(vault, NOW, (id) => record(id));+ expect(a.id).not.toBe(b.id);+ expect(readWriteSession(vault, a.id, NOW).session).not.toBeNull();+ expect(readWriteSession(vault, b.id, NOW).session).not.toBeNull();+});++test("a structurally incomplete record reads as an error probe (fail closed)", () => {+ const id = allocateWriteSessionId(vault, NOW);+ mkdirSync(writeSessionDir(vault), { recursive: true });+ writeFileSync(+ writeSessionPath(vault, id),+ JSON.stringify({ id, kind: "artifact", status: "needs-llm-step" }),+ );+ const probe = readWriteSession(vault, id, NOW);+ expect(probe.session).toBeNull();+ expect(probe.error).toMatch(/malformed/);+});++test("sweep removes *.json files whose names violate the id grammar", () => {+ mkdirSync(writeSessionDir(vault), { recursive: true });+ writeFileSync(join(writeSessionDir(vault), "GARBAGE.json"), "{}");+ const swept = sweepWriteSessions(vault, NOW);+ expect(swept.removed).toBe(1);+ expect(existsSync(join(writeSessionDir(vault), "GARBAGE.json"))).toBe(false);+});++test("allocateWriteSessionId never collides with an existing session file", () => {+ const first = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(first));+ const second = allocateWriteSessionId(vault, NOW);+ expect(second).not.toBe(first);+ expect(isWriteSessionId(second)).toBe(true);+});++test("save + read round-trips a record with snake_case on disk", () => {+ const id = allocateWriteSessionId(vault, NOW);+ saveWriteSession(+ vault,+ record(id, {+ kind: "panel",+ step: "persona:technical",+ topic: "adopt bun",+ personas: [{ slug: "technical", lens: "technical feasibility", prompt: "Assess it." }],+ responses: { "persona:technical": "fine" },+ lastErrors: [{ code: "frontmatter-missing", path: "frontmatter", message: "absent" }],+ }),+ );+ const raw = JSON.parse(readFileSync(writeSessionPath(vault, id), "utf8"));+ expect(raw["created_at"]).toBe(NOW);+ expect(raw["retry_cap"]).toBe(3);+ expect(raw["target_path"]).toBe("Brain/notes/fixture.md");+ expect(raw["require_review"]).toBe(false);+ expect(raw["last_errors"][0]["code"]).toBe("frontmatter-missing");++ const probe = readWriteSession(vault, id, NOW);+ expect(probe.error).toBeNull();+ expect(probe.session!.kind).toBe("panel");+ expect(probe.session!.step).toBe("persona:technical");+ expect(probe.session!.personas[0]!.lens).toBe("technical feasibility");+ expect(probe.session!.responses["persona:technical"]).toBe("fine");+});++test("missing session reads as a null probe without error", () => {+ const probe = readWriteSession(vault, "ws-2026-06-04-missing", NOW);+ expect(probe.session).toBeNull();+ expect(probe.error).toBeNull();+});++test("corrupted session file reads as an error probe, never throws", () => {+ const id = allocateWriteSessionId(vault, NOW);+ mkdirSync(writeSessionDir(vault), { recursive: true });+ writeFileSync(writeSessionPath(vault, id), "{broken");+ const probe = readWriteSession(vault, id, NOW);+ expect(probe.session).toBeNull();+ expect(probe.error).toMatch(/not valid JSON/);+});++test("lazy TTL: an expired non-terminal session reads as failed/expired", () => {+ const id = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(id, { status: "needs-correction" }));+ const fresh = readWriteSession(vault, id, NOW);+ expect(fresh.session!.status).toBe("needs-correction");+ const expired = readWriteSession(vault, id, LATER);+ expect(expired.session!.status).toBe("failed");+ expect(expired.session!.failReason).toBe("expired");+});++test("lazy TTL leaves terminal sessions untouched", () => {+ const id = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(id, { status: "done" }));+ const probe = readWriteSession(vault, id, LATER);+ expect(probe.session!.status).toBe("done");+ expect(probe.session!.failReason).toBeNull();+});++test("listWriteSessions returns sessions sorted by created_at then id", () => {+ expect(listWriteSessions(vault, NOW)).toEqual([]);+ const a = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(a, { createdAt: "2026-06-04T09:00:00Z" }));+ const b = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(b, { createdAt: "2026-06-04T08:00:00Z" }));+ const sessions = listWriteSessions(vault, NOW);+ expect(sessions.map((s) => s.id)).toEqual([b, a]);+});++test("delete removes the file; sweep removes terminal and expired sessions", () => {+ const done = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(done, { status: "done" }));+ const expired = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(expired, { status: "needs-llm-step" }));+ const live = allocateWriteSessionId(vault, NOW);+ saveWriteSession(vault, record(live, { expiresAt: "2026-06-06T10:00:00Z" }));++ deleteWriteSession(vault, done);+ expect(existsSync(writeSessionPath(vault, done))).toBe(false);++ const swept = sweepWriteSessions(vault, LATER);+ expect(swept.removed).toBe(1);+ expect(swept.kept).toBe(1);+ expect(existsSync(writeSessionPath(vault, expired))).toBe(false);+ expect(existsSync(writeSessionPath(vault, live))).toBe(true);+});diff --git a/tests/core/brain/write-session/validate.test.ts b/tests/core/brain/write-session/validate.test.tsnew file mode 100644index 00000000..c4521ec2--- /dev/null+++ b/tests/core/brain/write-session/validate.test.ts@@ -0,0 +1,124 @@+/**+ * Write-session artifact validation and target policy+ * (Agent Write Contract Suite, t_bc36a8a2).+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ buildCorrectionPrompt,+ inspectExistingTarget,+ validateArtifact,+ validateTargetPath,+} from "../../../../src/core/brain/write-session/validate.ts";+import { resolveSchemaVocabulary } from "../../../../src/core/brain/schema-vocab.ts";++let tmp: string;+let vault: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-ws-validate-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const GOOD = ["---", "kind: note", "type: note", "---", "", "# Fixture", "", "Body."].join("\n");++// ----- target policy --------------------------------------------------------++test("target must be a vault-relative markdown path under Brain/", () => {+ expect(validateTargetPath("Brain/notes/x.md")).toEqual([]);+ expect(validateTargetPath("Brain/decisions/panels/p.md")).toEqual([]);++ expect(validateTargetPath("notes/x.md")[0]!.code).toBe("target-outside-brain");+ expect(validateTargetPath("/etc/passwd")[0]!.code).toBe("target-outside-brain");+ expect(validateTargetPath("Brain/../escape.md")[0]!.code).toBe("target-traversal");+ expect(validateTargetPath("Brain/notes/..\\win.md")[0]!.code).toBe("target-traversal");+ expect(validateTargetPath("Brain/notes/x.txt")[0]!.code).toBe("target-extension");+ expect(validateTargetPath("")[0]!.code).toBe("target-outside-brain");+});++test("reserved namespaces are denied with coded errors", () => {+ for (const target of [+ "Brain/preferences/pref-x.md",+ "Brain/log/2026-06-04.md",+ "Brain/.sessions/write/ws-1.md",+ "Brain/.payloads/abc.md",+ "Brain/_brain.yaml",+ ]) {+ const errors = validateTargetPath(target);+ expect(errors.length).toBeGreaterThan(0);+ expect(errors.map((e) => e.code)).toContain(+ target === "Brain/_brain.yaml" ? "target-reserved" : "target-reserved",+ );+ }+});++// ----- artifact validation --------------------------------------------------++test("a well-formed artifact with declared schema type validates cleanly", () => {+ const vocab = resolveSchemaVocabulary({ page_types: ["decision"] });+ const artifact = GOOD.replace("type: note", "type: decision");+ expect(validateArtifact(artifact, { schemaType: "decision", vocabulary: vocab })).toEqual([]);+});++test("empty and oversized artifacts are rejected", () => {+ expect(validateArtifact("", {})[0]!.code).toBe("artifact-empty");+ expect(validateArtifact(" \n ", {})[0]!.code).toBe("artifact-empty");+ const big = `${GOOD}\n${"x".repeat(300_000)}`;+ expect(validateArtifact(big, {}).map((e) => e.code)).toContain("artifact-too-large");+});++test("missing or malformed frontmatter is a coded error", () => {+ expect(validateArtifact("# No frontmatter\n\nBody.", {})[0]!.code).toBe("frontmatter-missing");+ const codes = validateArtifact("---\nkind note\n---\n\nBody.", {}).map((e) => e.code);+ expect(codes.some((c) => c === "frontmatter-missing" || c === "frontmatter-malformed")).toBe(+ true,+ );+});++test("declared schema type must be known and must match the artifact", () => {+ const vocab = resolveSchemaVocabulary({ page_types: ["decision"] });+ const unknown = validateArtifact(GOOD, { schemaType: "bogus", vocabulary: vocab });+ expect(unknown.map((e) => e.code)).toContain("schema-type-unknown");++ const mismatch = validateArtifact(GOOD, { schemaType: "decision", vocabulary: vocab });+ expect(mismatch.map((e) => e.code)).toContain("schema-type-mismatch");+});++test("control characters in the body are rejected", () => {+ const sneaky = `${GOOD}\nbad: \u0000byte`;+ expect(validateArtifact(sneaky, {}).map((e) => e.code)).toContain("artifact-control-chars");+});++// ----- correction prompt ----------------------------------------------------++test("correction prompt is compact and lists every error", () => {+ const prompt = buildCorrectionPrompt([+ { code: "frontmatter-missing", path: "frontmatter", message: "artifact has no frontmatter" },+ { code: "schema-type-mismatch", path: "type", message: "expected 'decision'" },+ ]);+ expect(prompt).toContain("frontmatter-missing");+ expect(prompt).toContain("expected 'decision'");+ expect(prompt).toContain("full corrected artifact");+ expect(prompt.length).toBeLessThan(1000);+});++// ----- existing-target inspection -------------------------------------------++test("inspectExistingTarget returns null for a free path and metadata for an occupied one", () => {+ expect(inspectExistingTarget(vault, "Brain/notes/free.md")).toBeNull();+ mkdirSync(join(vault, "Brain", "notes"), { recursive: true });+ writeFileSync(join(vault, "Brain", "notes", "busy.md"), "---\nkind: note\n---\n\n# Busy note\n");+ const info = inspectExistingTarget(vault, "Brain/notes/busy.md");+ expect(info!.bytes).toBeGreaterThan(0);+ expect(info!.content_hash).toMatch(/^[0-9a-f]{64}$/);+ expect(info!.first_heading).toBe("Busy note");+});diff --git a/tests/e2e/agent-write-contract.integration.test.ts b/tests/e2e/agent-write-contract.integration.test.tsnew file mode 100644index 00000000..3683ab48--- /dev/null+++ b/tests/e2e/agent-write-contract.integration.test.ts@@ -0,0 +1,166 @@+/**+ * Agent Write Contract Suite end-to-end (epic t_f01ed100): one flow+ * per feature against a real tmp vault, driven the way a calling+ * agent would drive it.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { openArtifactSession, submitToSession } from "../../src/core/brain/write-session/engine.ts";+import {+ openPanelSession,+ submitToPanelSession,+} from "../../src/core/brain/write-session/panel.ts";+import { resolveMemoryBackend } from "../../src/core/brain/agent-backend/registry.ts";+import { appendBrainNote } from "../../src/core/brain/note.ts";+import { mirrorSignal } from "../../src/core/brain/shared-namespace.ts";+import { parseLogDay } from "../../src/core/brain/log.ts";+import { parseSignal } from "../../src/core/brain/signal.ts";++let tmp: string;+let vault: string;+let shared: string;+let configPath: string;++const NOW = "2026-06-04T12:00:00.000Z";++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-awc-e2e-"));+ vault = join(tmp, "vault");+ shared = join(tmp, "shared");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ mkdirSync(join(shared, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\nshared_namespace: "${shared}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("artifact session: open -> invalid -> correction -> valid -> commit + audit", () => {+ const opened = openArtifactSession(vault, {+ agent: "e2e-agent",+ targetPath: "Brain/notes/handoff.md",+ schemaType: "note",+ now: NOW,+ });+ expect(opened.status).toBe("needs-llm-step");++ const corrected = submitToSession(vault, {+ sessionId: opened.session_id,+ artifact: "just text, no frontmatter",+ now: NOW,+ });+ expect(corrected.status).toBe("needs-correction");+ expect(corrected.prompt).toContain("resubmit the full corrected artifact");++ const done = submitToSession(vault, {+ sessionId: opened.session_id,+ artifact: "---\nkind: note\ntype: note\n---\n\n# Handoff\n\nState captured.\n",+ now: NOW,+ });+ expect(done.status).toBe("done");+ expect(readFileSync(join(vault, "Brain", "notes", "handoff.md"), "utf8")).toContain("# Handoff");++ const audit = parseLogDay(vault, "2026-06-04").entries.filter(+ (e) => e.eventType === "write-session",+ );+ expect(audit).toHaveLength(1);+ expect(audit[0]!.body["attempts"]).toBe("1");+});++test("panel session: four lenses, synthesis, committed decision note", () => {+ const opened = openPanelSession(vault, {+ agent: "e2e-agent",+ topic: "Adopt write sessions",+ now: NOW,+ });+ let env = opened;+ for (const answer of ["Feasible.", "Aligned.", "Low risk.", "Better UX."]) {+ env = submitToPanelSession(vault, { sessionId: opened.session_id, text: answer, now: NOW });+ }+ expect(env.step).toBe("synthesis");+ const done = submitToPanelSession(vault, {+ sessionId: opened.session_id,+ text: "Adopt now.",+ now: NOW,+ });+ expect(done.status).toBe("done");+ const note = readFileSync(join(vault, done.target_path), "utf8");+ expect(note).toContain("kind: decision-panel");+ expect(note).toContain("## risk and failure modes (risk)");+ expect(note).toContain("Adopt now.");+});++test("backend registry renders a preference through the claude adapter", () => {+ const backend = resolveMemoryBackend(configPath);+ expect(backend.id).toBe("claude");+ const parsed = backend.parseMemoryFile(+ [+ "---",+ "name: prefer_pipelines",+ "description: Prefer pipeline() over barriers",+ "metadata:",+ " type: feedback",+ "---",+ "",+ "Use pipeline() by default.",+ ].join("\n"),+ );+ if (parsed.kind !== "feedback") throw new Error("expected feedback parse");+ const rendered = backend.renderPreference({+ name: parsed.name,+ description: parsed.description,+ body: parsed.body,+ memoryPath: "/x/memory/prefer_pipelines.md",+ importedAt: "2026-06-04T12:00:00Z",+ bodySha256: parsed.bodySha256,+ });+ expect(rendered).toContain("pref-prefer-pipelines");+});++test("shared namespace: signal and note mirror with attribution; primary always lands", () => {+ expect(+ mirrorSignal(shared, vault, {+ topic: "e2e-topic",+ signal: "positive",+ agent: "e2e-agent",+ principle: "Mirrors carry origin.",+ created_at: "2026-06-04T12:00:00Z",+ date: "2026-06-04",+ slug: "e2e-topic",+ }),+ ).toBe("ok");+ const inbox = readdirSync(join(shared, "Brain", "inbox")).filter((f) => f.endsWith(".md"));+ expect(inbox).toHaveLength(1);+ expect(parseSignal(join(shared, "Brain", "inbox", inbox[0]!)).agent).toBe("e2e-agent");++ const res = appendBrainNote({+ vault,+ text: "e2e milestone",+ agent: "e2e-agent",+ configPath,+ now: new Date(NOW),+ });+ expect(res.mirror).toBe("ok");+ expect(parseLogDay(vault, "2026-06-04").entries.some((e) => e.eventType === "note")).toBe(true);+ expect(parseLogDay(shared, "2026-06-04").entries.some((e) => e.eventType === "note")).toBe(true);++ // Break the shared namespace: the primary write must be untouched.+ rmSync(shared, { recursive: true, force: true });+ writeFileSync(shared, "not a directory");+ const degraded = appendBrainNote({+ vault,+ text: "after breakage",+ agent: "e2e-agent",+ configPath,+ now: new Date("2026-06-04T12:01:00Z"),+ });+ expect(degraded.mirror).toBe("failed");+ const notes = parseLogDay(vault, "2026-06-04").entries.filter((e) => e.eventType === "note");+ expect(notes).toHaveLength(2);+});diff --git a/tests/mcp/brain-write-session.test.ts b/tests/mcp/brain-write-session.test.tsnew file mode 100644index 00000000..c5bc2cd0--- /dev/null+++ b/tests/mcp/brain-write-session.test.ts@@ -0,0 +1,128 @@+/**+ * `brain_write_session` MCP tool (Agent Write Contract Suite,+ * t_bc36a8a2 + t_0cc6fdff): one tool, op + kind discriminators, the+ * same envelopes as the CLI.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";++let tmp: string;+let vault: string;+let configPath: string;++const GOOD = "---\nkind: note\n---\n\n# MCP note\n\nBody.\n";++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-ws-"));+ vault = join(tmp, "vault");+ mkdirSync(join(vault, "Brain"), { recursive: true });+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: "${vault}"\n`);+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function ctx(): ServerContext {+ return { vault, configPath, repoRoot: null };+}++function tool() {+ return findTool(buildToolTable("full"), "brain_write_session");+}++test("artifact flow: open -> bad submit -> corrected submit -> done", async () => {+ const opened = (await tool().handler(ctx(), {+ op: "open",+ kind: "artifact",+ target: "Brain/notes/mcp.md",+ agent: "mcp-agent",+ })) as Record<string, unknown>;+ expect(opened["status"]).toBe("needs-llm-step");+ const id = opened["session_id"] as string;++ const bad = (await tool().handler(ctx(), {+ op: "submit",+ session_id: id,+ text: "no frontmatter",+ })) as Record<string, unknown>;+ expect(bad["status"]).toBe("needs-correction");+ expect((bad["errors"] as Array<{ code: string }>).map((e) => e.code)).toContain(+ "frontmatter-missing",+ );++ const done = (await tool().handler(ctx(), {+ op: "submit",+ session_id: id,+ text: GOOD,+ })) as Record<string, unknown>;+ expect(done["status"]).toBe("done");+ expect(readFileSync(join(vault, "Brain", "notes", "mcp.md"), "utf8")).toContain("# MCP note");+});++test("panel flow: open -> persona steps -> synthesis -> committed note", async () => {+ const opened = (await tool().handler(ctx(), {+ op: "open",+ kind: "panel",+ topic: "Adopt MCP sessions",+ personas: ["technical", "risk"],+ agent: "mcp-agent",+ })) as Record<string, unknown>;+ expect(opened["step"]).toBe("persona:technical");+ const id = opened["session_id"] as string;++ await tool().handler(ctx(), { op: "submit", session_id: id, text: "Feasible." });+ await tool().handler(ctx(), { op: "submit", session_id: id, text: "Low risk." });+ const done = (await tool().handler(ctx(), {+ op: "submit",+ session_id: id,+ text: "Adopt.",+ })) as Record<string, unknown>;+ expect(done["status"]).toBe("done");+ expect(readFileSync(join(vault, done["target_path"] as string), "utf8")).toContain(+ "## Synthesis",+ );+});++test("status, list, abandon ops round-trip", async () => {+ const opened = (await tool().handler(ctx(), {+ op: "open",+ kind: "artifact",+ target: "Brain/notes/s.md",+ })) as Record<string, unknown>;+ const id = opened["session_id"] as string;++ const status = (await tool().handler(ctx(), { op: "status", session_id: id })) as Record<+ string,+ unknown+ >;+ expect(status["status"]).toBe("needs-llm-step");++ const list = (await tool().handler(ctx(), { op: "list" })) as Record<string, unknown>;+ expect((list["sessions"] as unknown[]).length).toBe(1);++ const abandoned = (await tool().handler(ctx(), { op: "abandon", session_id: id })) as Record<+ string,+ unknown+ >;+ expect(abandoned["status"]).toBe("failed");+});++test("structured request errors surface as MCP invalid-params", async () => {+ await expect(+ tool().handler(ctx(), { op: "open", kind: "artifact", target: "Brain/preferences/x.md" }),+ ).rejects.toThrow(/target rejected/);+ await expect(tool().handler(ctx(), { op: "bogus" })).rejects.toThrow(/op/);+ await expect(tool().handler(ctx(), { op: "submit" })).rejects.toThrow(/session_id/);+});++test("the tool is advertised in full scope but not writer scope", () => {+ expect(() => findTool(buildToolTable("full"), "brain_write_session")).not.toThrow();+ expect(() => findTool(buildToolTable("writer"), "brain_write_session")).toThrow();+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 979ffd9d..6606a984 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -257,6 +257,8 @@ describe("tool listing", () => {"brain_trigger","brain_deep_synthesis","brain_idea_discovery",+ // Agent Write Contract Suite: provider-agnostic write sessions.+ "brain_write_session",].toSorted(),);// Explicit grep: legacy writable tools are no longer advertised.@@ -508,7 +510,8 @@ describe("stdio loop", () => {// brain_intention (Agent Surface Suite) = 62.// + brain_trigger / brain_deep_synthesis / brain_idea_discovery// (Workspace Insight Suite) = 65.- expect(list.result.tools.length).toBe(65);+ // + brain_write_session (Agent Write Contract Suite) = 66.+ expect(list.result.tools.length).toBe(66);});test("returns parse error for invalid JSON", async () => {