Skip to content

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

TypeScript

feat: Session Knowledge Synthesis Suite - structured session summaries, idea-lineage, episodic note history (v1.11.0) (#100)

Sol Aitkenc2c3ff4085b4
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index cf4c5c57..3dc5b8e2 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.10.0",
+ "version": "1.11.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 8a40c366..ef9da553 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.10.0",
+ "version": "1.11.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3aaec89b..a0cf28a8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,42 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.11.0] - 2026-06-14
+
+### Added
+
+- **Session Knowledge Synthesis Suite.** Three additive, deterministic,
+ language-agnostic units that turn temporal activity into structured,
+ queryable, provenance-traced knowledge. Every unit is a new surface; with no
+ new surface in use, reads are byte-identical to before, and the kernel never
+ calls an LLM (agent-extracted data is stored verbatim; everything else is a
+ pure read).
+ - **Structured session summary (`o2b brain session-summary`,
+ `brain_session_summary`).** A session-scoped digest over four canonical
+ categories - request, decisions, learnings, next_steps - stored as one
+ append-only continuity record (`session_summary_digest`), distinct from the
+ `session_summary_node` recall rollup and the per-line `pre_compact_extract`.
+ The agent supplies the already-extracted categories; the kernel validates,
+ dedupes by content hash, and appends, never parsing prose into categories.
+ An all-empty digest is rejected; absent a write, reads return null.
+ - **Idea-lineage provenance tracer (`o2b brain idea-lineage`,
+ `brain_idea_lineage`).** A read-only tracer reconstructing how a derived
+ artifact was reached as an observation -> synthesis -> conclusion graph. A
+ continuity id walks the `sourceRefs` graph (raw turns are observations,
+ summaries/extracts/digests synthesis, the queried record the conclusion),
+ resolving edges by record id or turn id, cycle-guarded and depth-bounded; a
+ preference id adapts the existing `buildBeliefEvolution` lifecycle into the
+ same shape. Unknown ids fail with a typed error rather than a silent empty
+ chain.
+ - **Episodic note-history decomposition (`o2b brain note-history`,
+ `brain_note_history`).** Splits a note's git commit chain into recallable
+ episodic phases on a deterministic commit-time gap (default 72h) - a
+ language-agnostic rule that never depends on commit-message wording. Each
+ phase carries the commit subjects, dates, and authors. A missing repo
+ reports `available: false` (no fabricated phase); a path with no commits
+ reports `available: true` with zero phases (empty is distinct from broken).
+ The sanitized read-only git reader gains an additive `path` pathspec filter.
+
## [1.10.0] - 2026-06-14
### Added
@@ -5468,6 +5504,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.11.0]: https://github.com/itechmeat/open-second-brain/compare/v1.10.0...v1.11.0
[1.10.0]: https://github.com/itechmeat/open-second-brain/compare/v1.9.0...v1.10.0
[1.9.0]: https://github.com/itechmeat/open-second-brain/compare/v1.8.0...v1.9.0
[1.8.0]: https://github.com/itechmeat/open-second-brain/compare/v1.7.0...v1.8.0
diff --git a/README.md b/README.md
index 97878afb..deca7e87 100644
--- a/README.md
+++ b/README.md
@@ -90,6 +90,7 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra
- **An index that survives interruption.** Stopping `o2b search watch` mid-sync finishes the in-flight pass at a file boundary before exiting (within `search_shutdown_grace_seconds`) instead of killing it mid-write; an incremental run is already resumable through the unchanged-file fastpath, and `search_resume_reindex` extends that to a full rebuild - an interrupted reindex resumes its staging build instead of starting over, guarded by a signature so a drifted build is discarded rather than trusted. Both default off, so behaviour is unchanged unless you ask for it.
- **A brain you can carry, hand off, and write to in process.** `o2b brain bank-export` serialises a whole vault - preferences, the page graph, a per-page interchange contract (path, kind, advisory confidence/provenance, citations, aliases, freshness), and the sources dashboard - into one deterministic, schema-versioned bundle for backup, migration, or downstream-tool ingest; `bank-import` reconstructs the page graph and reports the rest as carried-not-restored rather than faking a full restore. A `brain_create_note` MCP tool writes an actual vault note (path + frontmatter + content) atomically, refusing traversal, the Brain root, and clobbering. And `createBrain(vault)` is a thin in-process SDK over the same core functions - bank/graph export-import, preference export, source ingest plus list/get/delete, and note creation - so scripts and agents manage brain content without the CLI or MCP layer.
- **Recall you can tune, and a working set that prunes itself.** `o2b search --profile fast|balanced|thorough` (and the `brain_search` `profile` field) pick a recall preset over the same bounded knobs the self-tuner uses - an explicit profile wins over a learned grid point, and no profile leaves ranking bit-for-bit unchanged. `o2b brain file-context <path>` surfaces prior vault work that mentions a file before you read it; `o2b brain co-occurrence` proposes relationship edges between entities repeatedly co-referenced from the same notes, scored structurally over the wikilink graph with no natural-language word list in any language; and `o2b brain continuity rank` weights working-memory records by a usage-driven decay derived only from real recall telemetry, so stale decisions fade while actively-recalled ones stay prominent. All deterministic, all read-only or suggestion-only.
+- **Session knowledge you can query, trace, and walk.** `o2b brain session-summary` (and `brain_session_summary`) stores a session-scoped digest over four categories - request, decisions, learnings, next_steps - that the agent extracts and the kernel only stores, so you can ask what a session decided as one unit. `o2b brain idea-lineage <id>` traces how a derived artifact was reached as an observation to synthesis to conclusion graph over the edges already recorded (continuity `sourceRefs`, or a preference's belief-evolution), cycle-guarded and depth-bounded. `o2b brain note-history <path>` splits a note's git history into episodic phases on a deterministic commit-time gap - language-agnostic, no commit-message parsing. The kernel never calls a model; absent inputs report honestly rather than fabricating.
That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.
diff --git a/docs/brainstorm/session-knowledge-synthesis/cli-output/claude.md b/docs/brainstorm/session-knowledge-synthesis/cli-output/claude.md
new file mode 100644
index 00000000..3625e059
--- /dev/null
+++ b/docs/brainstorm/session-knowledge-synthesis/cli-output/claude.md
@@ -0,0 +1,59 @@
+## Part 1 - Scope recommendation
+
+### Candidate clusters
+
+- **Session Knowledge Synthesis** — `t_325a7e4a` (p0, structured session summary), `t_e4ddbe7c` (p3, daily morning brief), `t_635a3ea5` (p2, idea-lineage). Theme: `src/core/brain/temporal/` + `session-lifecycle.ts` — turn session activity into structured, queryable, surface-able temporal knowledge via agent-driven extraction. Usefulness: high (closes the "what happened / what was decided / what's next" loop, the core value of a second brain); risk: low, fully additive.
+- **Multi-agent session-import adapters** — `t_aaced180` (p1, Copilot history), `t_f5761ca8` (p1, Pi), `t_7cf20134` (p1, Copilot CLI), `t_7c89c306` (p1, progressive-batch parser). Theme: `src/core/brain/sessions/` adapter registry. Usefulness: moderate; risk: **blocking** — every adapter requires reverse-engineering an external/unstable transcript format (Pi explicitly "needs reverse-engineering"; Copilot format external), which the brief flags as a blocking risk.
+- **Graphify/codegraph passthroughs** — `t_b8283326`, `t_bf6933bc`, `t_5d8d6a00`, `t_85252236`, `t_a286135c`, `t_6c9f4434`, `t_a1e76788`. Theme: `src/core/partner/codegraph.ts`. Usefulness: low-moderate; risk: **blocking** — these are thin passthroughs whose logic lives in the external `graphify` binary and would silently no-op when it is absent (`t_bf6933bc` was already de-scoped for exactly this misleading-fallback reason).
+- **MCP server distribution / transport** — `t_da6321a9` (p3, console-script entry), `t_31dfae18` (p2, Streamable HTTP transport). Theme: `src/mcp/`. Usefulness: low for a memory store; risk: medium — validator notes the two are "different layers," and HTTP transport + API-key auth leans architectural (multi-client security model).
+
+### Recommended cluster
+
+- **Name**: Session Knowledge Synthesis
+- **Task IDs**: `t_325a7e4a`, `t_e4ddbe7c`, `t_635a3ea5`
+- **Why this cluster** (usefulness-first): For a second brain, the highest-leverage gap is that sessions are stored but not queryable as decisions/learnings/next-steps — `t_325a7e4a` (the only cleanly-buildable p0) fixes exactly that, producing machine-queryable structured memories instead of opaque transcripts. `t_e4ddbe7c` is the natural read-side consumer: a daily brief that surfaces those structured summaries plus pending items, completing a coherent session→summary→brief loop. `t_635a3ea5` adds the provenance leg, tracing how a decision or learning was reached, which makes the structured summaries auditable and trustworthy. All three live in `src/core/brain/temporal/` and `session-lifecycle.ts`, all rely on agent-driven extraction with the kernel storing already-structured data, and all are byte-identical-when-unused and language-agnostic. This is far more useful to the product than adding one more editor or codegraph passthrough.
+- **Why not the others**:
+ - Multi-agent session-import adapters: blocked — each depends on reverse-engineering an external/unstable transcript format.
+ - Graphify/codegraph passthroughs: blocked — thin passthroughs to an external binary that would silently no-op when absent (forbidden misleading fallback).
+ - MCP distribution/transport: loosely related ("different layers"), HTTP transport leans architectural, and it adds little to recall quality.
+- **Key risks and how to neutralize them**:
+ - *Provider dependency for AI extraction.* Neutralize by keeping all AI-derived fields optional and clearly provenance-marked; absence of a provider degrades to a deterministic structural skeleton, never a fake summary.
+ - *Touching shipped `weekly-brief.ts` behavior.* Neutralize by adding the daily variant additively (new cadence/scope), guaranteeing byte-identical output when the daily surface is unused.
+ - *Language-agnostic guarantee.* Neutralize by extracting categories (decisions/learnings/next-steps) via the agent/LLM and structural signals only — no hardcoded natural-language keyword lists.
+ - *Scope creep into provenance graph.* Neutralize by scoping idea-lineage to recording edges over existing belief-evolution/dream output, not a new graph engine.
+
+## Part 2 - Architectural variants for the recommended cluster
+
+### Variant 1: Agent-extracted structured records + read-side synthesis tools
+- **Approach**: Add a `session_summary` memory type with structured metadata (request/decisions/learnings/next-steps), written by an MCP tool the agent calls at session end (or via the existing stop hook prompting the agent). The daily brief and idea-lineage are read-side synthesis tools that aggregate these records; the kernel only stores already-extracted structured data and never calls an LLM.
+- **Trade-offs**:
+ - Pro: Matches the provider-agnostic kernel guarantee exactly; AI extraction stays fully agent-driven.
+ - Pro: Maximally additive — new memory type + new tools, byte-identical when unused; minimal contact with shipped `weekly-brief.ts`.
+ - Pro: Language-agnostic by construction (agent does extraction, no word lists).
+ - Con: Rich fields only populate when an agent/provider is active; raw-only sessions yield thin summaries.
+ - Con: Three loosely-shared tools rather than one unified pipeline (mild duplication).
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Deterministic skeleton + optional agent enrichment (sentinel-marked)
+- **Approach**: The stop hook deterministically writes a structural skeleton (turn count, files touched, tool calls) for every session with no provider needed; AI fields (decisions/learnings/next-steps) are filled later by an agent pass (e.g., during dream) and marked as derived using a generated/user sentinel pattern. Daily brief and lineage read from these progressively-enriched records.
+- **Trade-offs**:
+ - Pro: Strongest fail-soft story — useful output even with no provider, with AI fields honestly marked derived (no misleading fallback).
+ - Pro: Sentinel marking enables safe re-synthesis without clobbering enriched content.
+ - Con: Two-phase lifecycle (skeleton then enrichment) is more moving parts and ordering to reason about.
+ - Con: Couples the feature to the dream/synthesis pass timing.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 3: Unified TemporalSynthesisEnvelope (refactor weekly-brief into a general pipeline)
+- **Approach**: Generalize the existing `WeeklySynthesisEnvelope` into one `TemporalSynthesisEnvelope` parameterized by scope (session | daily | weekly) and synthesis type, so session summaries, the daily brief, and lineage are all variants of a single schema and pipeline.
+- **Trade-offs**:
+ - Pro: Most DRY; one synthesis path to maintain and extend later.
+ - Pro: Consistent schema across all temporal outputs.
+ - Con: Refactors shipped `weekly-brief.ts`, directly threatening the byte-identical-when-unused guarantee for an existing surface.
+ - Con: Largest blast radius; couples three new features to a refactor that must preserve v1.x weekly behavior exactly.
+- **Complexity**: large
+- **Risk**: medium
+
+### Recommended: Variant 1
+**Rationale**: Variant 1 aligns cleanest with the project's hard guarantees — the kernel never calls an LLM, extraction is agent-driven, and a new memory type plus read-side tools are byte-identical when unused with almost no contact with shipped `weekly-brief.ts`. It should borrow Variant 2's discipline of marking AI fields as optional/derived so absent-provider cases degrade honestly rather than fabricating summaries. Variant 3's unification is appealing long-term but its refactor of a shipped surface is unjustified risk for an additive low-priority release.
diff --git a/docs/brainstorm/session-knowledge-synthesis/cli-output/prompt.md b/docs/brainstorm/session-knowledge-synthesis/cli-output/prompt.md
new file mode 100644
index 00000000..962cc221
--- /dev/null
+++ b/docs/brainstorm/session-knowledge-synthesis/cli-output/prompt.md
@@ -0,0 +1,74 @@
+You are helping select and then brainstorm the scope of the NEXT release for the Open Second Brain project. Do not write code. Do not write a final design. Your job has two parts: (1) recommend the single most useful RELATED cluster of low-priority triage tasks to ship as one release, and (2) for that recommended cluster, produce architectural variants.
+
+# Selection objective
+
+From the triage column below, pick a COHERENT cluster of tasks that:
+
+- Share a subsystem or a single architectural theme (a "related cluster", not a grab-bag).
+- Are LOW / minor priority on this board. Priority scale here is: 4 = highest, 0 = unprocessed/lowest. Prefer p0-p1 clusters; p2 only if tightly related to the chosen theme.
+- Maximize USEFULNESS to the project. Usefulness is the most important criterion by far. The number of files touched and exact feature count are the WEAKEST signals - do not optimize for them.
+- Are buildable additively, without architectural unknowns that need a separate ADR, and without depending on reverse-engineering an external/unstable data format (treat "needs reverse-engineering of an external transcript/session format" as a blocking risk).
+
+Explicitly AVOID recommending:
+
+- Large architectural subsystems the board's validator flagged as "needs ADR / design discussion" (PDF export, voice/STT-TTS, whiteboard, 15-adapter architecture, universal agent runtime contract, LLM tracing, inbox-pill UI, subagent orchestration).
+- Thin passthroughs to an external binary that would silently no-op when that binary is absent (e.g. a `reindex --force` verb that just shells out to an absent `graphify`) - the project forbids misleading fallbacks.
+- Anything gated on an unmerged upstream PR.
+
+# Project context
+
+- Name: Open Second Brain. Language/runtime: TypeScript on Bun. Storage: SQLite (bun:sqlite, FTS5 + sqlite-vec). Surfaces: an MCP stdio server, an `o2b` CLI, and an Obsidian/Markdown vault.
+- The kernel is provider-agnostic: it NEVER calls an LLM itself. Any AI extraction must be agent-driven (via an MCP tool or a lifecycle hook); the kernel only stores already-extracted structured data.
+- Hard guarantees the project holds itself to: byte-identical reads when a new feature flag/surface is unused; language-agnostic behavior (NO hardcoded natural-language word lists in any language - use structural signals, frontmatter fields, document-frequency, or agent/LLM extraction); no misleading fallbacks; no hardcoding; no `as` TypeScript cast crutches.
+- Two relevant registry-driven subsystems already exist and are explicitly designed for easy extension:
+ 1. `src/core/install/adapters/` - writes the Open Second Brain MCP servers (and optional lifecycle hooks) into a third-party coding agent's own config. Present targets: aider, copilot-cli, cursor, gemini-cli, generic, grok, kiro, opencode, pi. A thin adapter is ~25 lines via the shared `_json-mcp.ts` base; bespoke hook+MCP adapters (grok) are larger. NOTE: the adapter-registration import list is currently duplicated verbatim across 4 CLI entry files (install.ts, init-interactive.ts, uninstall-target.ts, update.ts) - a latent DRY problem.
+ 2. `src/core/brain/sessions/` - session-import adapters that read an agent's transcript files and ingest them. Present: claude, codex, grok, hermes, opencode. Registry self-documents the 3-step add procedure. Adding a runtime here requires KNOWING that runtime's on-disk transcript format.
+
+Recent shipped releases (most recent first):
+- v1.10.0 Recall & Working-Memory Quality - selectable recall profiles, usage decay, co-occurrence auto-relate, file-context recall
+- v1.9.0 Brain Portability & Interop - bank export/import, page contract, brain_create_note, in-process SDK
+- v1.8.0 Indexer Durability & Resilience - cooperative abort, graceful watch shutdown, resumable reindex
+- v1.7.0 Knowledge Provenance - ingest, research, NER, derived facts, owner-scope, standing-query
+- v1.6.0 Vault Integrity & Trust; v1.5.0 Search & Recall Quality; v1.4.0 native Grok integration; v1.3.0 opencode integration + Continuity/Hygiene/Freshness
+
+Constraints for the chosen cluster:
+- Do not change existing public APIs in a breaking way.
+- No new external runtime dependencies unless unavoidable.
+- Every new surface must be byte-identical-when-unused and language-agnostic.
+
+# Triage column (every task with body and comments)
+
+<<<TRIAGE
+[The full triage column - 42 tasks with bodies and comments - was fed in verbatim at runtime via `kanban.ts triage`. Omitted from the committed audit trail to avoid persisting a board snapshot in the repo; the live board is the source of truth.]
+TRIAGE
+
+# Required output format
+
+## Part 1 - Scope recommendation
+
+### Candidate clusters
+List 2-4 candidate clusters you considered. For each: the cluster name, the task IDs in it, the shared theme, and a one-line usefulness/risk note.
+
+### Recommended cluster
+- **Name**:
+- **Task IDs**:
+- **Why this cluster** (3-5 sentences, usefulness-first):
+- **Why not the others** (1-2 sentences each):
+- **Key risks and how to neutralize them**:
+
+## Part 2 - Architectural variants for the recommended cluster
+
+Produce exactly 3 distinct architectural variants for IMPLEMENTING the recommended cluster. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/session-knowledge-synthesis/design.md b/docs/brainstorm/session-knowledge-synthesis/design.md
new file mode 100644
index 00000000..940d5bcd
--- /dev/null
+++ b/docs/brainstorm/session-knowledge-synthesis/design.md
@@ -0,0 +1,146 @@
+# Session Knowledge Synthesis - structured session summaries, idea lineage, and episodic note history
+
+**Status:** draft
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain stores rich temporal activity - session turns, preference
+lifecycle transitions, dream synthesis output, git-backed note history - but
+three slices of that activity are not yet queryable as structured, provenance-
+traced knowledge:
+
+1. A whole session is recallable only as hierarchical text rollups
+ (`session_summary_node`) or scattered labelled lines (`pre_compact_extract`);
+ there is no single session-scoped digest answering "what was the request,
+ what did we decide, what did we learn, what is next" as one unit.
+2. There is no read-side tracer that reconstructs how a derived insight was
+ reached (observation -> synthesis -> conclusion) from the source edges the
+ continuity store already records.
+3. A note's evolution over time is not decomposed into recallable episodic
+ phases; the git history exists (read-only reader shipped) but nothing turns
+ a note's commit chain into searchable phase records.
+
+## Scope
+
+- **Feature A - structured session summary (`t_325a7e4a`).** A session-scoped
+ digest with the four canonical categories request / decisions / learnings /
+ next_steps. The agent extracts the categories (kernel never calls an LLM);
+ the kernel validates and stores one continuity record per session, and a
+ read surface returns it as a unit.
+- **Feature B - idea lineage (`t_635a3ea5`).** A pure read-side tracer that,
+ given a derived artifact (a preference, a session summary, a derived fact),
+ walks the existing `sourceRefs` edges plus belief-evolution transitions and
+ dream output to reconstruct the observation -> synthesis -> conclusion chain.
+- **Feature C - episodic note history (`t_6a201155`).** Given a note path,
+ read its commit chain via the existing sanitized git reader, decompose it
+ into episodic phases by a deterministic structural rule (time gaps), and
+ emit recallable phase records; per-phase prose summary is agent-supplied or
+ a deterministic skeleton when no agent enriches it.
+
+## Out of scope
+
+- Daily / morning brief (`t_e4ddbe7c`): already shipped (`brain_brief`
+ view=morning / view=daily); closed as already-present, no code here.
+- Any new coding-agent install adapter or session-import adapter (operator
+ excluded "adding new agents" this cycle).
+- Embedding-backed semantic search over phase records beyond what the existing
+ index already provides; phases are recallable through the existing surfaces,
+ not a new vector store.
+- Mutating notes, sessions, or preferences. Every feature is additive and
+ read-or-append only.
+
+## Chosen approach
+
+Variant 1 from the consultant (`cli-output/claude.md`): agent-extracted
+structured records plus read-side synthesis tools, with the discipline borrowed
+from Variant 2 that every AI-derived field is optional and marked derived, so
+absence of a provider degrades to a deterministic structural skeleton and never
+a fabricated summary.
+
+Concretely:
+
+- **Storage** reuses the append-only continuity store
+ (`Brain/log/continuity/YYYY-MM.jsonl`) and its `sourceRefs` edge field. A new
+ record kind is added to the closed `ContinuityRecordKind` union for the
+ session digest; note-history phases reuse the same store. No schema migration
+ - the store is append-only and every record self-stamps its schema version.
+- **Extraction** is agent-driven through MCP tools that accept already-extracted
+ structured fields (the proven `brain_pre_compact_extract` pattern). The kernel
+ validates shape, dedupes by content hash, and appends. The kernel performs no
+ natural-language parsing beyond the existing structural label grammar.
+- **Read surfaces** are pure projections (the `buildDailyBrief` pattern):
+ deterministic, no disk mutation, byte-identical to absence when unused.
+
+## Design decisions
+
+- **Distinct record kind for the session digest.** The existing
+ `session_summary_node` kind is a hierarchical recall rollup; overloading it
+ would conflate two shapes. Add a new kind (e.g. `session_summary_digest`) so
+ recall, lineage, and the rollup stay structurally separable. Additive to the
+ union; `read-model.ts` normalization extends to lift `session_id`.
+- **Categories are data, not kernel grammar.** request / decisions / learnings
+ / next_steps are stored as agent-supplied arrays. The kernel does not infer
+ them from prose with a natural-language word list - that would break the
+ language-agnostic guarantee. An agent (any provider, any language) supplies
+ them; absent an agent, the digest is simply not written (no fake digest).
+- **Idea lineage adds no new storage.** It is a read-side walk over edges that
+ already exist (`sourceRefs`, belief-evolution transitions, dream summaries).
+ This keeps it byte-identical-when-unused and avoids a second provenance graph.
+- **Note-history phase splitting is deterministic and structural.** Phases are
+ cut on commit time gaps (a configurable threshold), not on NL topic detection.
+ This is language-agnostic and reproducible. Per-phase prose summary is an
+ optional agent enrichment, marked derived; the skeleton (commit range, dates,
+ author set, touched paths) is always available from the git reader alone.
+- **Fail-soft, honest absence.** Missing git repo -> reader returns null ->
+ "no history available" (not an empty fabricated phase). Missing agent
+ extraction -> skeleton only, with an explicit `enriched: false`. No
+ misleading fallback anywhere.
+
+## File changes
+
+New (core):
+- `src/core/brain/session-summary.ts` - digest record shape, append (agent-
+ supplied categories), and read (`getSessionSummary(vault, sessionId)`).
+- `src/core/brain/idea-lineage.ts` - read-side lineage tracer over sourceRefs +
+ belief-evolution + dream output.
+- `src/core/brain/note-history.ts` - git-reader-backed phase decomposition.
+
+Modified (core):
+- `src/core/brain/continuity/types.ts` - add `session_summary_digest` (and, if
+ needed, a note-history phase kind) to `ContinuityRecordKind`.
+- `src/core/brain/continuity/read-model.ts` - normalize the new kind(s).
+- `src/core/brain/session-lifecycle.ts` - optional hook point to fold a stored
+ digest into the SessionEnd result (read-back only, no new write path).
+
+New (MCP):
+- session-summary write + read tools, idea-lineage tool, note-history tool,
+ registered through the existing per-domain tool arrays in `brain-tools.ts`.
+ Update `FROZEN_BRAIN_TOOL_NAMES` and the tool-count assertions accordingly.
+
+New (CLI):
+- `src/cli/brain/verbs/session-summary.ts`, `idea-lineage.ts`,
+ `note-history.ts`, each exported from `verbs/index.ts` and wired into the
+ brain dispatcher; usage errors via the `usageError()` helper (exit 2).
+
+Docs:
+- `README.md`, `CHANGELOG.md`, `docs/mcp.md`, `docs/cli-reference.md`.
+
+Version: bump `package.json` and run `bun run scripts/sync-version.ts` inside
+this PR (per `CLAUDE.md`).
+
+## Risks and open questions
+
+- **Overlap with `pre_compact_extract`.** Mitigation: the session digest is a
+ session-scoped envelope with a fixed 4-category schema and its own read
+ surface; it complements, not duplicates, the per-line extractor. Decide in
+ Task A whether the digest tool reuses the extractor's storage helpers.
+- **`git/reader.ts` has no current callers.** It is shipped and tested but
+ unwired; note-history is its first consumer. Confirm its API
+ (`readCommits`, path filter) covers per-note history before building Task C.
+- **Tool-count test churn.** Adding top-level MCP tools changes
+ `FROZEN_BRAIN_TOOL_NAMES` and the `tools/list` count assertion in
+ `removed-tools.test.ts` (currently 78). Update both deliberately.
+- **Lineage cycles.** The tracer must guard against cyclic sourceRefs (seen-set)
+ and bound traversal depth, mirroring the existing lineage-ledger root walk.
diff --git a/docs/brainstorm/session-knowledge-synthesis/plan.md b/docs/brainstorm/session-knowledge-synthesis/plan.md
new file mode 100644
index 00000000..f8eae7e1
--- /dev/null
+++ b/docs/brainstorm/session-knowledge-synthesis/plan.md
@@ -0,0 +1,82 @@
+# Session Knowledge Synthesis - implementation plan
+
+Three atomic features on one branch (`feat/session-knowledge-synthesis`), each
+built TDD-first, each its own conventional commit. Order is chosen so the
+shared continuity-store touch (Task A) lands before the read-side consumers.
+
+## Task A: Structured session summary (`t_325a7e4a`)
+
+- **Files**:
+ - `src/core/brain/session-summary.ts` (new) - `SessionSummaryDigest` type
+ (request: string; decisions/learnings/next_steps: string[]),
+ `appendSessionSummary(vault, input)` (agent-supplied categories ->
+ validated, content-hash deduped, appended as `session_summary_digest`),
+ `getSessionSummary(vault, sessionId)` (latest digest for a session).
+ - `src/core/brain/continuity/types.ts` (mod) - add `session_summary_digest`
+ to `ContinuityRecordKind`.
+ - `src/core/brain/continuity/read-model.ts` (mod) - normalize the new kind
+ (lift `session_id`).
+ - `src/mcp/brain/...` (new tool) - `brain_session_summary` with two modes or
+ two tools: write (agent supplies categories) and read (fetch a session's
+ digest). Register in the per-domain tool array; update
+ `FROZEN_BRAIN_TOOL_NAMES` + tool-count assertions.
+ - `src/cli/brain/verbs/session-summary.ts` (new) + `verbs/index.ts` (mod).
+- **Acceptance**:
+ - Append rejects a payload missing all four categories (no empty digest).
+ - Re-appending identical categories for a session dedupes (content hash).
+ - `getSessionSummary` returns the latest digest; absent -> null, not a fake.
+ - Byte-identical continuity reads when the tool is never called.
+- **Depends on**: none.
+
+## Task B: Idea lineage (`t_635a3ea5`)
+
+- **Files**:
+ - `src/core/brain/idea-lineage.ts` (new) - `traceIdeaLineage(vault, {id})`
+ walks `sourceRefs` backward from a derived artifact, merges belief-evolution
+ transitions and dream-summary provenance, returns an ordered
+ observation -> synthesis -> conclusion chain with a seen-set cycle guard and
+ a bounded depth.
+ - `src/mcp/brain/...` (new tool) - `brain_idea_lineage`; register + update
+ frozen names / counts.
+ - `src/cli/brain/verbs/idea-lineage.ts` (new) + `verbs/index.ts` (mod).
+- **Acceptance**:
+ - A digest (Task A) whose `sourceRefs` point at session turns traces back to
+ those turns.
+ - A preference traces through its belief-evolution creation/promotion.
+ - Cyclic sourceRefs terminate (seen-set); depth is bounded and reported.
+ - Unknown id -> typed error, not a silent empty chain.
+- **Depends on**: Task A (provides a concrete derived artifact to trace).
+
+## Task C: Episodic note history (`t_6a201155`)
+
+- **Files**:
+ - `src/core/brain/note-history.ts` (new) - `decomposeNoteHistory(vault,
+ notePath, opts)`: read the note's commit chain via `git/reader.ts`
+ (`readCommits` with a path filter), split into phases on a configurable
+ commit-time-gap threshold (deterministic, structural), emit
+ `NoteHistoryPhase[]` (commit range, first/last date, author set, touched
+ paths, optional agent-supplied `summary` with `enriched` flag).
+ - `src/mcp/brain/...` (new tool) - `brain_note_history`; register + update
+ frozen names / counts.
+ - `src/cli/brain/verbs/note-history.ts` (new) + `verbs/index.ts` (mod).
+- **Acceptance**:
+ - Missing repo / non-repo dir -> "no history available" (reader null), not an
+ empty phase list pretending success.
+ - Empty repo (zero commits) is distinguished from breakage (reader []).
+ - A commit chain with a gap above threshold splits into >1 phase; below, 1.
+ - Phase summary defaults to a deterministic skeleton with `enriched: false`;
+ an agent-supplied summary sets `enriched: true`.
+ - Phase splitting is independent of commit-message language (no NL rule).
+- **Depends on**: none (parallel to A/B, but committed last to keep the diff
+ reviewable).
+
+## Cross-cutting (Phase 4-5, once A/B/C are in)
+
+- Full suite green (`bun test`), typecheck (`bun run typecheck`), lint
+ (`bun run lint`), version-sync check (`bun run scripts/sync-version.ts
+ --check`).
+- `tests/mcp/removed-tools.test.ts` tool-count (78 -> 78 + new top-level tools)
+ and `FROZEN_BRAIN_TOOL_NAMES` updated.
+- Docs: README, CHANGELOG (`## [X.Y.Z]` + compare link), docs/mcp.md,
+ docs/cli-reference.md.
+- Version bump in `package.json` + `bun run scripts/sync-version.ts`.
diff --git a/docs/brainstorm/session-knowledge-synthesis/variants.md b/docs/brainstorm/session-knowledge-synthesis/variants.md
new file mode 100644
index 00000000..81123fa5
--- /dev/null
+++ b/docs/brainstorm/session-knowledge-synthesis/variants.md
@@ -0,0 +1,87 @@
+# Session Knowledge Synthesis - variant audit trail
+
+## How scope was chosen
+
+This cycle the operator asked for a large scope of related, low-priority
+triage tasks, explicitly excluding "adding new agents" (neither install
+adapters like cline nor session-import adapters like copilot-cli / pi), and
+asked to move already-implemented-but-open tasks to done.
+
+Phase 0 ran the CLI consultant (`claude -p`) over the entire triage column
+(`cli-output/prompt.md`, `cli-output/claude.md`). The consultant recommended
+the **Session Knowledge Synthesis** cluster (`t_325a7e4a`, `t_e4ddbe7c`,
+`t_635a3ea5`) with **Variant 1** (agent-extracted structured records + read-side
+synthesis tools, kernel stays provider-agnostic). Full output is preserved
+verbatim in `cli-output/claude.md`.
+
+## Orchestrator gap analysis (override of the consultant cluster)
+
+The consultant worked from the triage text and a context summary; it did not
+know the codebase had moved ahead of two of the three tasks. Direct inspection
+of `main` found:
+
+- **`t_e4ddbe7c` (daily / morning brief) is already shipped.** `brain_brief`
+ exposes `view=morning` (`src/core/brain/morning-brief.ts:buildMorningBrief`)
+ and `view=daily` (`src/core/brain/temporal/daily-brief.ts:buildDailyBrief`),
+ plus weekly / monthly, from the temporal-synthesis suite. The only novel
+ upstream element - injecting the brief into a task tracker's description
+ field - is host-specific and not an Open Second Brain kernel concern.
+ -> Closed as already-present (moved to done), no code.
+- **`t_325a7e4a` (structured session summary) is only partially covered.**
+ `pre_compact_extract` already does agent-supplied structured extraction
+ (decision / commitment / outcome / rule / open_question), and
+ `session_summary_node` is a hierarchical recall rollup. Neither is a
+ session-scoped digest over the four canonical categories (request / decisions
+ / learnings / next_steps). -> Real but narrow gap; build it as a thin
+ session-scoped envelope reusing the existing extraction + storage primitives.
+- **`t_635a3ea5` (idea lineage) is a real gap.** The edges exist (`sourceRefs`,
+ belief-evolution, dream output) but no read-side tracer reconstructs the
+ observation -> synthesis -> conclusion chain. -> Build as a read-only tracer.
+
+To keep a meaningful scope after removing the already-done task, the operator
+agreed to add a third in-repo, non-agent task:
+
+- **`t_6a201155` (episodic note-history decomposition).** Substrate confirmed:
+ `src/core/brain/git/reader.ts` (Project History Suite) is a sanitized
+ read-only git reader, shipped and tested but with no current callers. A note's
+ version chain = the git commits touching its path; phases are a deterministic
+ structural split. -> Build as its first consumer.
+
+Final build scope: **A** structured session summary, **B** idea lineage, **C**
+episodic note history. `t_e4ddbe7c` closed as already-present.
+
+## Architectural variants considered (from the consultant, applied to the final scope)
+
+### Variant 1: Agent-extracted structured records + read-side synthesis tools
+- **Approach**: new structured record(s) written by an MCP tool the agent calls;
+ read-side tools aggregate. Kernel stores already-extracted data, never calls
+ an LLM.
+- **Trade-offs**: matches the provider-agnostic guarantee exactly; maximally
+ additive and byte-identical when unused; language-agnostic by construction.
+ Con: rich fields only populate when an agent is active.
+- **Complexity**: medium. **Risk**: low.
+
+### Variant 2: Deterministic skeleton + optional agent enrichment (sentinel-marked)
+- **Approach**: kernel writes a deterministic structural skeleton with no
+ provider; AI fields fill later and are marked derived.
+- **Trade-offs**: strongest fail-soft story. Con: two-phase lifecycle, more
+ ordering to reason about; couples to the dream pass timing.
+- **Complexity**: medium. **Risk**: low.
+
+### Variant 3: Unified TemporalSynthesisEnvelope (refactor weekly-brief)
+- **Approach**: generalize `WeeklySynthesisEnvelope` into one envelope
+ parameterized by scope.
+- **Trade-offs**: most DRY long-term. Con: refactors a shipped surface,
+ threatening byte-identical-when-unused; largest blast radius.
+- **Complexity**: large. **Risk**: medium.
+
+## Final decision
+
+**Variant 1**, borrowing Variant 2's discipline: every AI-derived field is
+optional and marked derived (`enriched` flag / absent digest), so no-provider
+cases degrade to a deterministic skeleton or honest absence, never a fabricated
+summary. Variant 3's unification is rejected - refactoring the shipped
+weekly-brief surface is unjustified risk for an additive release. This applies
+uniformly to all three features: the kernel validates and stores agent-supplied
+structure (A), reads existing edges (B), and reads git history with a
+deterministic split plus optional enrichment (C).
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 85acec9f..0ec8969d 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -73,6 +73,9 @@ o2b brain pre-compact-extract Extract decision/commitment/outcome/rule/open-ques
o2b brain session-grep Search imported session recall raw turns and summary nodes (since v0.29.0)
o2b brain session-describe Count raw turns and deterministic summary depths for one session recall DAG (since v0.29.0)
o2b brain session-expand Expand a session recall node to immediate sources and paginated raw turn content (since v0.29.0)
+o2b brain session-summary write|get|list a session-scoped structured digest (request/decisions/learnings/next_steps) (since v1.11.0)
+o2b brain idea-lineage Trace how a derived artifact was reached: observation -> synthesis -> conclusion over continuity sourceRefs or belief-evolution (since v1.11.0)
+o2b brain note-history Decompose a note's git history into episodic phases split on a commit-time gap (since v1.11.0)
o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence
```
diff --git a/docs/mcp.md b/docs/mcp.md
index b219ff8b..d373a831 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -58,6 +58,9 @@ flags for a narrower per-process full server.
| `brain_sources` | Read-only dashboard of signals grouped by (agent, source_type) with active/processed and distinct-topic counts. | — |
| `brain_create_note` | Write an actual vault note file (path + frontmatter + content) atomically inside the vault. Distinct from `brain_note` (log append); refuses traversal, the Brain root, excluded paths, and clobbering. | `path` |
| `brain_file_context` | Given a file path, surface prior vault work that mentions it (decisions, bug notes, refactor history) by querying the index with path-derived terms. Size gate skips trivial files. Read-only; no LLM. | `file_path` |
+| `brain_session_summary` | Session-scoped structured digest over request/decisions/learnings/next_steps: `write` stores agent-extracted categories, `get` returns a session's latest digest, `list` returns all. Append-only, deduped; an all-empty digest is rejected. | `operation` |
+| `brain_idea_lineage` | Read-only provenance tracer: reconstruct how a derived artifact was reached as an observation -> synthesis -> conclusion graph. A `ctn_` id walks the sourceRefs graph; a `pref-`/`ret-` id adapts belief-evolution. Cycle-guarded, depth-bounded; unknown id errors. | `id` |
+| `brain_note_history` | Decompose a note's git history into recallable episodic phases split on a deterministic commit-time gap (default 72h, language-agnostic). Each phase carries subjects/dates/authors. Missing repo → `available: false`; no commits → zero phases. Read-only. | `path` |
| `schema_inspect` | Read-only schema inspection for any view: `view: graph \| lint \| stats \| orphans \| explain_type \| active_pack \| packs`. | `view` (`token` for `explain_type`) |
| `schema_apply_mutations` | Apply audited, locked schema mutations to `Brain/_brain.yaml`. | `mutations` |
| `brain_watchdog` | Probe Brain config, required dirs, and search-index health; optionally apply safe directory remediation. | — |
@@ -107,6 +110,11 @@ and `telemetry`. `brain_context_receipts` supports `operation: "list"|"show"`;
deterministic media/base64 sanitization. `brain_session_grep`,
`brain_session_describe`, and `brain_session_expand` inspect the opt-in session
recall DAG populated by CLI `import-session --recall` or the core API.
+`brain_session_summary` accepts `operation: "write"|"get"|"list"` (write takes
+`session_id` plus any of `request`, `decisions`, `learnings`, `next_steps`,
+`source_turn_ids`, `host`). `brain_idea_lineage` accepts `id` and optional
+`max_depth`. `brain_note_history` accepts `path` and optional `gap_hours` /
+`max_count`.
`brain_recall_gate` accepts optional `previous_prompt` and
`explicit`; `explicit: true` always returns `retrieve: true`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index c4065e7d..424ea2b0 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.10.0",
+ "version": "1.11.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 2223df44..2b27ad79 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.10.0",
+ "version": "1.11.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 59b1bfec..12300925 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.10.0"
+version: "1.11.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index f12cd620..639dd0b2 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.10.0",
+ "version": "1.11.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 59b1bfec..12300925 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.10.0"
+version: "1.11.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 7a392f36..a9ed5673 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.10.0"
+version = "1.11.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/src/cli/brain.ts b/src/cli/brain.ts
index 7f46712e..de60a345 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -79,6 +79,9 @@ import {
cmdBrainProfile,
cmdBrainSgrep,
cmdBrainContinuity,
+ cmdBrainSessionSummary,
+ cmdBrainIdeaLineage,
+ cmdBrainNoteHistory,
cmdBrainBench,
cmdBrainGit,
cmdBrainArchitect,
@@ -267,6 +270,12 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainSgrep(rest);
case "continuity":
return await cmdBrainContinuity(rest);
+ case "session-summary":
+ return await cmdBrainSessionSummary(rest);
+ case "idea-lineage":
+ return await cmdBrainIdeaLineage(rest);
+ case "note-history":
+ return await cmdBrainNoteHistory(rest);
case "bench":
return await cmdBrainBench(rest);
case "git":
diff --git a/src/cli/brain/verbs/idea-lineage.ts b/src/cli/brain/verbs/idea-lineage.ts
new file mode 100644
index 00000000..7bfdc182
--- /dev/null
+++ b/src/cli/brain/verbs/idea-lineage.ts
@@ -0,0 +1,62 @@
+/**
+ * `o2b brain idea-lineage <id>` (Session Knowledge Synthesis, t_635a3ea5):
+ * read-only provenance trace of how a derived artifact was reached, as an
+ * observation -> synthesis -> conclusion graph. The id is a continuity
+ * record id (ctn_...) or a preference id (pref-.../ret-...).
+ *
+ * o2b brain idea-lineage <id> [--max-depth N] [--json]
+ */
+
+import {
+ traceIdeaLineage,
+ IdeaLineageError,
+ type IdeaLineageResult,
+} from "../../../core/brain/idea-lineage.ts";
+import { brainVerbContext, parse, usageError } from "../helpers.ts";
+
+const USAGE = "usage: o2b brain idea-lineage <id> [--max-depth N] [--json]";
+
+export async function cmdBrainIdeaLineage(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ "max-depth": { type: "string" },
+ json: { type: "boolean" },
+ });
+
+ const id = positional[0]?.trim() ?? "";
+ if (id.length === 0) return usageError(USAGE);
+
+ let maxDepth: number | undefined;
+ if (typeof flags["max-depth"] === "string") {
+ const parsed = Number(flags["max-depth"]);
+ if (!Number.isInteger(parsed) || parsed < 1) {
+ return usageError("brain idea-lineage: --max-depth must be a positive integer");
+ }
+ maxDepth = parsed;
+ }
+
+ const vault = brainVerbContext(flags).vault;
+ let result: IdeaLineageResult;
+ try {
+ result = traceIdeaLineage(vault, { id }, maxDepth !== undefined ? { maxDepth } : {});
+ } catch (error) {
+ if (error instanceof IdeaLineageError)
+ return usageError(`brain idea-lineage: ${error.message}`);
+ throw error;
+ }
+
+ if (flags["json"] === true) {
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
+ return 0;
+ }
+
+ process.stdout.write(`lineage of ${result.root.id} (${result.root.kind})\n`);
+ for (const node of result.nodes) {
+ const marker = node.id === result.root.id ? "*" : " ";
+ process.stdout.write(`${marker} [${node.stage}] d${node.depth} ${node.kind} ${node.label}\n`);
+ }
+ if (result.truncated) {
+ process.stdout.write(" (truncated at the depth bound; pass --max-depth to go deeper)\n");
+ }
+ return 0;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index c3f1c37c..cb3191f1 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -62,6 +62,9 @@ export { cmdBrainLinks } from "./links.ts";
export { cmdBrainProfile } from "./profile.ts";
export { cmdBrainSgrep } from "./sgrep.ts";
export { cmdBrainContinuity } from "./continuity.ts";
+export { cmdBrainSessionSummary } from "./session-summary.ts";
+export { cmdBrainIdeaLineage } from "./idea-lineage.ts";
+export { cmdBrainNoteHistory } from "./note-history.ts";
export { cmdBrainBench } from "./bench.ts";
export { cmdBrainGit } from "./git.ts";
export { cmdBrainArchitect } from "./architect.ts";
diff --git a/src/cli/brain/verbs/note-history.ts b/src/cli/brain/verbs/note-history.ts
new file mode 100644
index 00000000..09d05434
--- /dev/null
+++ b/src/cli/brain/verbs/note-history.ts
@@ -0,0 +1,70 @@
+/**
+ * `o2b brain note-history <path>` (Session Knowledge Synthesis, t_6a201155):
+ * decompose a note's git history into recallable episodic phases, split
+ * deterministically on a commit-time gap.
+ *
+ * o2b brain note-history <path> [--gap-hours N] [--max-count N] [--json]
+ */
+
+import { decomposeNoteHistory } from "../../../core/brain/note-history.ts";
+import { brainVerbContext, parse, usageError } from "../helpers.ts";
+
+const USAGE = "usage: o2b brain note-history <path> [--gap-hours N] [--max-count N] [--json]";
+
+export async function cmdBrainNoteHistory(argv: string[]): Promise<number> {
+ const { flags, positional } = parse(argv, {
+ vault: { type: "string" },
+ "gap-hours": { type: "string" },
+ "max-count": { type: "string" },
+ json: { type: "boolean" },
+ });
+
+ const path = positional[0]?.trim() ?? "";
+ if (path.length === 0) return usageError(USAGE);
+
+ const gapHours = parsePositiveInt(flags["gap-hours"]);
+ if (gapHours === "invalid")
+ return usageError("brain note-history: --gap-hours must be a positive integer");
+ const maxCount = parsePositiveInt(flags["max-count"]);
+ if (maxCount === "invalid")
+ return usageError("brain note-history: --max-count must be a positive integer");
+
+ const vault = brainVerbContext(flags).vault;
+ const result = decomposeNoteHistory(vault, path, {
+ ...(gapHours !== undefined ? { gapHours } : {}),
+ ...(maxCount !== undefined ? { maxCount } : {}),
+ });
+
+ if (flags["json"] === true) {
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
+ return 0;
+ }
+
+ if (!result.available) {
+ process.stdout.write(`${result.notePath}: ${result.reason ?? "no history available"}\n`);
+ return 0;
+ }
+ if (result.phases.length === 0) {
+ process.stdout.write(`${result.notePath}: ${result.reason ?? "no commits"}\n`);
+ return 0;
+ }
+ process.stdout.write(
+ `${result.notePath}: ${result.commitCount} commit(s) in ${result.phases.length} phase(s)\n`,
+ );
+ for (const phase of result.phases) {
+ process.stdout.write(
+ ` phase ${phase.index}: ${phase.firstDate} -> ${phase.lastDate} (${phase.commitCount} commit(s), ${phase.authors.join(", ")})\n`,
+ );
+ for (const subject of phase.subjects) process.stdout.write(` - ${subject}\n`);
+ }
+ return 0;
+}
+
+function parsePositiveInt(
+ value: string | boolean | string[] | undefined,
+): number | undefined | "invalid" {
+ if (typeof value !== "string") return undefined;
+ const parsed = Number(value);
+ if (!Number.isInteger(parsed) || parsed < 1) return "invalid";
+ return parsed;
+}
diff --git a/src/cli/brain/verbs/session-summary.ts b/src/cli/brain/verbs/session-summary.ts
new file mode 100644
index 00000000..4601a715
--- /dev/null
+++ b/src/cli/brain/verbs/session-summary.ts
@@ -0,0 +1,175 @@
+/**
+ * `o2b brain session-summary` (Session Knowledge Synthesis, t_325a7e4a):
+ * write or read a session-scoped structured digest over the four
+ * canonical categories (request / decisions / learnings / next_steps).
+ *
+ * write --session <id> [--request <s>] [--decision <s>]...
+ * [--learning <s>]... [--next-step <s>]... [--turn <id>]... [--host <h>]
+ * get --session <id>
+ * list [--session <id>]
+ *
+ * The kernel stores agent-supplied categories verbatim; it never parses
+ * prose into categories. An all-empty digest is rejected (exit 2).
+ */
+
+import {
+ appendSessionSummary,
+ getSessionSummary,
+ listSessionSummaries,
+ SessionSummaryError,
+ type SessionSummaryDigest,
+} from "../../../core/brain/session-summary.ts";
+import { brainVerbContext, fail, parse, usageError } from "../helpers.ts";
+
+const USAGE =
+ "usage: o2b brain session-summary write --session <id> [--request <s>] " +
+ "[--decision <s>]... [--learning <s>]... [--next-step <s>]... [--turn <id>]... [--host <h>] [--json]\n" +
+ " o2b brain session-summary get --session <id> [--json]\n" +
+ " o2b brain session-summary list [--session <id>] [--json]";
+
+export async function cmdBrainSessionSummary(argv: string[]): Promise<number> {
+ const subcommand = argv[0];
+ if (subcommand === "write") return writeSummary(argv.slice(1));
+ if (subcommand === "get") return getSummary(argv.slice(1));
+ if (subcommand === "list") return listSummaries(argv.slice(1));
+ return fail(USAGE);
+}
+
+function asStringArray(value: string | boolean | string[] | undefined): ReadonlyArray<string> {
+ return Array.isArray(value) ? value : [];
+}
+
+function writeSummary(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ session: { type: "string" },
+ request: { type: "string" },
+ decision: { type: "string-array" },
+ learning: { type: "string-array" },
+ "next-step": { type: "string-array" },
+ turn: { type: "string-array" },
+ host: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const session = typeof flags["session"] === "string" ? flags["session"].trim() : "";
+ if (session.length === 0) return usageError("brain session-summary write: --session is required");
+
+ const vault = brainVerbContext(flags).vault;
+ try {
+ const digest = appendSessionSummary(vault, {
+ sessionId: session,
+ ...(typeof flags["request"] === "string" ? { request: flags["request"] } : {}),
+ decisions: asStringArray(flags["decision"]),
+ learnings: asStringArray(flags["learning"]),
+ nextSteps: asStringArray(flags["next-step"]),
+ sourceTurnIds: asStringArray(flags["turn"]),
+ ...(typeof flags["host"] === "string" ? { host: flags["host"] } : {}),
+ });
+ return emit(
+ flags,
+ { written: true, digest: serialize(digest) },
+ () => `wrote session summary ${digest.id}`,
+ );
+ } catch (error) {
+ if (error instanceof SessionSummaryError)
+ return usageError(`brain session-summary write: ${error.message}`);
+ throw error;
+ }
+}
+
+function getSummary(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ session: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const session = typeof flags["session"] === "string" ? flags["session"].trim() : "";
+ if (session.length === 0) return usageError("brain session-summary get: --session is required");
+
+ const vault = brainVerbContext(flags).vault;
+ const digest = getSessionSummary(vault, session);
+ if (flags["json"] === true) {
+ process.stdout.write(
+ `${JSON.stringify(digest === null ? { found: false } : { found: true, digest: serialize(digest) }, null, 2)}\n`,
+ );
+ return 0;
+ }
+ if (digest === null) {
+ process.stdout.write(`no session summary for ${session}\n`);
+ return 0;
+ }
+ process.stdout.write(renderDigest(digest));
+ return 0;
+}
+
+function listSummaries(argv: string[]): number {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ session: { type: "string" },
+ json: { type: "boolean" },
+ });
+ const session = typeof flags["session"] === "string" ? flags["session"].trim() : undefined;
+ const vault = brainVerbContext(flags).vault;
+ const digests = listSessionSummaries(
+ vault,
+ session !== undefined && session.length > 0 ? { sessionId: session } : {},
+ );
+ if (flags["json"] === true) {
+ process.stdout.write(
+ `${JSON.stringify({ count: digests.length, digests: digests.map(serialize) }, null, 2)}\n`,
+ );
+ return 0;
+ }
+ if (digests.length === 0) {
+ process.stdout.write("no session summaries\n");
+ return 0;
+ }
+ process.stdout.write(`${digests.length} session summary record(s)\n`);
+ for (const digest of digests) {
+ process.stdout.write(
+ ` ${digest.createdAt} ${digest.sessionId} d=${digest.decisions.length} l=${digest.learnings.length} n=${digest.nextSteps.length}\n`,
+ );
+ }
+ return 0;
+}
+
+function serialize(digest: SessionSummaryDigest): Record<string, unknown> {
+ return {
+ id: digest.id,
+ session_id: digest.sessionId,
+ request: digest.request,
+ decisions: digest.decisions,
+ learnings: digest.learnings,
+ next_steps: digest.nextSteps,
+ created_at: digest.createdAt,
+ ...(digest.host !== undefined ? { host: digest.host } : {}),
+ };
+}
+
+function renderDigest(digest: SessionSummaryDigest): string {
+ const lines = [`session ${digest.sessionId} (${digest.createdAt})`];
+ if (digest.request !== null) lines.push(` request: ${digest.request}`);
+ appendCategory(lines, "decisions", digest.decisions);
+ appendCategory(lines, "learnings", digest.learnings);
+ appendCategory(lines, "next_steps", digest.nextSteps);
+ return `${lines.join("\n")}\n`;
+}
+
+function appendCategory(lines: string[], label: string, items: ReadonlyArray<string>): void {
+ if (items.length === 0) return;
+ lines.push(` ${label}:`);
+ for (const item of items) lines.push(` - ${item}`);
+}
+
+function emit(
+ flags: Record<string, string | boolean | string[] | undefined>,
+ json: Record<string, unknown>,
+ text: () => string,
+): number {
+ if (flags["json"] === true) {
+ process.stdout.write(`${JSON.stringify(json, null, 2)}\n`);
+ return 0;
+ }
+ process.stdout.write(`${text()}\n`);
+ return 0;
+}
diff --git a/src/core/brain/continuity/types.ts b/src/core/brain/continuity/types.ts
index b7f40c22..53acf145 100644
--- a/src/core/brain/continuity/types.ts
+++ b/src/core/brain/continuity/types.ts
@@ -16,6 +16,7 @@ export type ContinuityRecordKind =
| "pre_compact_extract"
| "session_turn"
| "session_summary_node"
+ | "session_summary_digest"
| "source_invalidation";
export type ContinuityPayload = Readonly<Record<string, unknown>>;
diff --git a/src/core/brain/git/reader.ts b/src/core/brain/git/reader.ts
index e7c8e610..160b8d14 100644
--- a/src/core/brain/git/reader.ts
+++ b/src/core/brain/git/reader.ts
@@ -52,6 +52,12 @@ export interface ReadCommitsOptions {
readonly sinceSha?: string;
/** Bound the walk; git keeps the NEWEST `maxCount` commits. */
readonly maxCount?: number;
+ /**
+ * Restrict the walk to commits that touched this repo-relative path
+ * (a git pathspec). Passed after a `--` separator so it can never be
+ * mistaken for a flag. Empty/whitespace is ignored (no restriction).
+ */
+ readonly path?: string;
}
// Output-side separators. argv strings cannot carry raw NUL bytes
@@ -112,6 +118,8 @@ export function readCommits(
args.push(`--max-count=${Math.max(1, Math.floor(opts.maxCount))}`);
}
if (opts.sinceSha !== undefined) args.push(`${opts.sinceSha}..HEAD`);
+ const pathspec = opts.path?.trim();
+ if (pathspec !== undefined && pathspec.length > 0) args.push("--", pathspec);
const raw = runGit(repoPath, args);
if (raw === null) {
// `git log` exits non-zero on a repo with zero commits; report that
diff --git a/src/core/brain/idea-lineage.ts b/src/core/brain/idea-lineage.ts
new file mode 100644
index 00000000..bfa8217b
--- /dev/null
+++ b/src/core/brain/idea-lineage.ts
@@ -0,0 +1,300 @@
+/**
+ * Idea lineage (Session Knowledge Synthesis, t_635a3ea5).
+ *
+ * A read-only provenance tracer: given a derived artifact, reconstruct
+ * the observation -> synthesis -> conclusion chain from edges that
+ * already exist - it writes nothing and computes nothing new.
+ *
+ * Two resolvers behind one shape:
+ * - continuity records (a ctn_ id): walk the `sourceRefs` graph
+ * backward. A raw `session_turn` is an observation, intermediate
+ * summary/extract/digest records are synthesis, the queried record
+ * is the conclusion. Edges resolve by record id (`session_summary_node`
+ * -> continuity_record) or by turn id (`session_summary_digest` ->
+ * `session_turn.payload.turn_id`). A seen-set guards cycles and a
+ * depth bound caps traversal (reported as `truncated`).
+ * - preferences (a pref-/ret- id): adapt the existing
+ * `buildBeliefEvolution` lifecycle into the same node/edge shape -
+ * creation is the observation, promotion the synthesis, retirement a
+ * terminal conclusion. No belief logic is reimplemented here.
+ *
+ * Unknown ids fail with {@link IdeaLineageError} rather than returning a
+ * silent empty chain.
+ */
+
+import { listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord } from "./continuity/types.ts";
+import { buildTimelineIndex } from "./temporal/build-index.ts";
+import { buildBeliefEvolution } from "./temporal/belief-evolution.ts";
+
+export class IdeaLineageError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "IdeaLineageError";
+ }
+}
+
+export type LineageStage = "observation" | "synthesis" | "conclusion";
+
+export interface IdeaLineageNode {
+ readonly id: string;
+ readonly kind: string;
+ readonly stage: LineageStage;
+ /** 0 for the queried artifact, increasing toward observations. */
+ readonly depth: number;
+ readonly createdAt: string | null;
+ readonly label: string;
+}
+
+export interface IdeaLineageEdge {
+ /** The more-derived node. */
+ readonly from: string;
+ /** The source it was derived from. */
+ readonly to: string;
+ readonly relation: string;
+}
+
+export interface IdeaLineageResult {
+ readonly root: IdeaLineageNode;
+ readonly nodes: ReadonlyArray<IdeaLineageNode>;
+ readonly edges: ReadonlyArray<IdeaLineageEdge>;
+ /** True when the depth bound stopped traversal before exhausting sources. */
+ readonly truncated: boolean;
+}
+
+export interface TraceIdeaLineageInput {
+ readonly id: string;
+}
+
+export interface TraceIdeaLineageOptions {
+ /** Maximum backward hops from the queried artifact. Default 8. */
+ readonly maxDepth?: number;
+}
+
+const DEFAULT_MAX_DEPTH = 8;
+const SNIPPET = 80;
+
+export function traceIdeaLineage(
+ vault: string,
+ input: TraceIdeaLineageInput,
+ opts: TraceIdeaLineageOptions = {},
+): IdeaLineageResult {
+ const id = input.id.trim();
+ if (id.length === 0) throw new IdeaLineageError("idea lineage requires a non-empty id");
+ if (id.startsWith("pref-") || id.startsWith("ret-")) {
+ return preferenceLineage(vault, id);
+ }
+ return continuityLineage(vault, id, Math.max(1, opts.maxDepth ?? DEFAULT_MAX_DEPTH));
+}
+
+// ----- continuity source graph ---------------------------------------------
+
+function continuityLineage(vault: string, id: string, maxDepth: number): IdeaLineageResult {
+ const records = listContinuityRecords(vault);
+ const byId = new Map<string, ContinuityRecord>();
+ const byTurnId = new Map<string, ContinuityRecord>();
+ const bySessionTurnId = new Map<string, ContinuityRecord>();
+ for (const record of records) {
+ byId.set(record.id, record);
+ if (record.kind === "session_turn") {
+ const turnId = String(record.payload["turn_id"] ?? "");
+ if (turnId.length === 0) continue;
+ if (!byTurnId.has(turnId)) byTurnId.set(turnId, record);
+ const sessionId = String(record.payload["session_id"] ?? "");
+ if (sessionId.length > 0) {
+ const scoped = sessionTurnKey(sessionId, turnId);
+ if (!bySessionTurnId.has(scoped)) bySessionTurnId.set(scoped, record);
+ }
+ }
+ }
+ const lookup: Lookup = { byId, byTurnId, bySessionTurnId };
+
+ const root = byId.get(id);
+ if (root === undefined) throw new IdeaLineageError(`no continuity record with id ${id}`);
+
+ const nodes: IdeaLineageNode[] = [continuityNode(root, 0, true)];
+ const edges: IdeaLineageEdge[] = [];
+ const seen = new Set<string>([root.id]);
+ const edgeKeys = new Set<string>();
+ let truncated = false;
+
+ let frontier: ContinuityRecord[] = [root];
+ let depth = 0;
+ while (frontier.length > 0) {
+ if (depth >= maxDepth) {
+ if (frontier.some((record) => hasUnseenSource(record, lookup, seen))) truncated = true;
+ break;
+ }
+ const next: ContinuityRecord[] = [];
+ for (const record of frontier) {
+ for (const source of resolveSources(record, lookup)) {
+ const edgeKey = `${record.id}->${source.record.id}`;
+ if (!edgeKeys.has(edgeKey)) {
+ edgeKeys.add(edgeKey);
+ edges.push(
+ Object.freeze({ from: record.id, to: source.record.id, relation: source.relation }),
+ );
+ }
+ if (!seen.has(source.record.id)) {
+ seen.add(source.record.id);
+ nodes.push(continuityNode(source.record, depth + 1, false));
+ next.push(source.record);
+ }
+ }
+ }
+ frontier = next;
+ depth += 1;
+ }
+
+ return Object.freeze({
+ root: nodes[0]!,
+ nodes: Object.freeze(nodes),
+ edges: Object.freeze(edges),
+ truncated,
+ });
+}
+
+interface ResolvedSource {
+ readonly record: ContinuityRecord;
+ readonly relation: string;
+}
+
+/**
+ * Record lookups for source resolution. `bySessionTurnId` is keyed
+ * `<session_id>:<turn_id>` so a turn reference resolves within the
+ * referring record's own session first, preventing a cross-session
+ * mislink when two sessions reuse the same `turn_id`.
+ */
+interface Lookup {
+ readonly byId: ReadonlyMap<string, ContinuityRecord>;
+ readonly byTurnId: ReadonlyMap<string, ContinuityRecord>;
+ readonly bySessionTurnId: ReadonlyMap<string, ContinuityRecord>;
+}
+
+function sessionTurnKey(sessionId: string, turnId: string): string {
+ return `${sessionId}:${turnId}`;
+}
+
+function resolveSources(record: ContinuityRecord, lookup: Lookup): ResolvedSource[] {
+ const sources: ResolvedSource[] = [];
+ const claimed = new Set<string>();
+ const recordSessionId = String(record.payload["session_id"] ?? "");
+ for (const ref of record.sourceRefs) {
+ const refId = typeof ref.id === "string" ? ref.id : "";
+ if (refId.length === 0 || refId === record.id) continue;
+ // A record-id edge wins; otherwise a turn id resolves within the
+ // referring record's own session before falling back to the global
+ // turn index (only reachable when the session is unknown).
+ const scoped =
+ recordSessionId.length > 0
+ ? lookup.bySessionTurnId.get(sessionTurnKey(recordSessionId, refId))
+ : undefined;
+ const candidate = lookup.byId.get(refId) ?? scoped ?? lookup.byTurnId.get(refId);
+ if (candidate === undefined || candidate.id === record.id || claimed.has(candidate.id))
+ continue;
+ claimed.add(candidate.id);
+ sources.push({ record: candidate, relation: refRelation(ref) });
+ }
+ return sources;
+}
+
+function hasUnseenSource(
+ record: ContinuityRecord,
+ lookup: Lookup,
+ seen: ReadonlySet<string>,
+): boolean {
+ return resolveSources(record, lookup).some((source) => !seen.has(source.record.id));
+}
+
+function refRelation(ref: { readonly kind?: string }): string {
+ return typeof ref.kind === "string" && ref.kind.length > 0 ? ref.kind : "source";
+}
+
+function continuityNode(record: ContinuityRecord, depth: number, isRoot: boolean): IdeaLineageNode {
+ return Object.freeze({
+ id: record.id,
+ kind: record.kind,
+ stage: continuityStage(record, isRoot),
+ depth,
+ createdAt: record.createdAt,
+ label: continuityLabel(record),
+ });
+}
+
+function continuityStage(record: ContinuityRecord, isRoot: boolean): LineageStage {
+ if (record.kind === "session_turn") return "observation";
+ if (isRoot) return "conclusion";
+ return "synthesis";
+}
+
+function continuityLabel(record: ContinuityRecord): string {
+ const payload = record.payload;
+ if (record.kind === "session_turn") {
+ const role = String(payload["role"] ?? "");
+ return `${role}: ${snippet(String(payload["text"] ?? ""))}`.trim();
+ }
+ if (record.kind === "session_summary_node") {
+ return `summary depth ${String(payload["depth"] ?? "?")}`;
+ }
+ if (record.kind === "session_summary_digest") {
+ return "session summary digest";
+ }
+ if (record.kind === "pre_compact_extract") {
+ return `${String(payload["extract_type"] ?? "extract")}: ${snippet(String(payload["text"] ?? ""))}`;
+ }
+ return record.kind;
+}
+
+function snippet(text: string): string {
+ const oneLine = text.replace(/\s+/g, " ").trim();
+ return oneLine.length > SNIPPET ? `${oneLine.slice(0, SNIPPET - 3)}...` : oneLine;
+}
+
+// ----- preference belief evolution -----------------------------------------
+
+function preferenceLineage(vault: string, prefId: string): IdeaLineageResult {
+ const index = buildTimelineIndex(vault, {});
+ const evo = buildBeliefEvolution(index, vault, { prefId });
+ if (evo.transitions.length === 0 && evo.evidence.length === 0 && evo.retirements.length === 0) {
+ throw new IdeaLineageError(`no belief lineage for ${prefId}`);
+ }
+
+ const firstAt = evo.transitions[0]?.at ?? null;
+ const root: IdeaLineageNode = Object.freeze({
+ id: prefId,
+ kind: "preference",
+ stage: "conclusion",
+ depth: 0,
+ createdAt: firstAt,
+ label: prefId,
+ });
+ const nodes: IdeaLineageNode[] = [root];
+ const edges: IdeaLineageEdge[] = [];
+ for (const transition of evo.transitions) {
+ const nodeId = `${transition.kind}:${transition.prefId}:${transition.at}`;
+ nodes.push(
+ Object.freeze({
+ id: nodeId,
+ kind: "belief_transition",
+ stage: transitionStage(transition.kind),
+ depth: 1,
+ createdAt: transition.at,
+ label: `${transition.kind} ${transition.at}`,
+ }),
+ );
+ edges.push(Object.freeze({ from: prefId, to: nodeId, relation: transition.kind }));
+ }
+
+ return Object.freeze({
+ root,
+ nodes: Object.freeze(nodes),
+ edges: Object.freeze(edges),
+ truncated: false,
+ });
+}
+
+function transitionStage(kind: "creation" | "promotion" | "retirement"): LineageStage {
+ if (kind === "creation") return "observation";
+ if (kind === "promotion") return "synthesis";
+ return "conclusion";
+}
diff --git a/src/core/brain/note-history.ts b/src/core/brain/note-history.ts
new file mode 100644
index 00000000..789567b2
--- /dev/null
+++ b/src/core/brain/note-history.ts
@@ -0,0 +1,153 @@
+/**
+ * Episodic note-history decomposition (Session Knowledge Synthesis,
+ * t_6a201155).
+ *
+ * Turns a note's git commit chain into recallable episodic phases. The
+ * split rule is deterministic and structural - a new phase starts when
+ * the gap between consecutive commits exceeds a threshold - so it is
+ * language-agnostic (commit-message wording never affects the split)
+ * and reproducible. Each phase carries the real commit subjects the
+ * author wrote, which is its summary; nothing is generated and the
+ * kernel never calls an LLM.
+ *
+ * Fail-soft and honest about absence: a missing repo or a git failure
+ * reports `available: false` (the underlying reader returns null); a
+ * real repo where no commit touches the path reports `available: true`
+ * with zero phases (empty != broken). No fabricated phase is ever
+ * returned for a path with no history.
+ */
+
+import { readCommits } from "./git/reader.ts";
+import type { GitCommit } from "./git/reader.ts";
+
+export interface NoteHistoryPhase {
+ /** 0-based phase index, oldest first. */
+ readonly index: number;
+ readonly firstSha: string;
+ readonly lastSha: string;
+ /** Author date of the earliest / latest commit in the phase (ISO-8601). */
+ readonly firstDate: string;
+ readonly lastDate: string;
+ readonly commitCount: number;
+ /** Distinct author names in the phase, first-seen order. */
+ readonly authors: ReadonlyArray<string>;
+ /** Commit subjects in the phase, oldest first - the phase's summary. */
+ readonly subjects: ReadonlyArray<string>;
+}
+
+export interface NoteHistoryResult {
+ readonly notePath: string;
+ /** False only when there is no git history to read (no repo / git failed). */
+ readonly available: boolean;
+ /** Human-readable reason when there are no phases. */
+ readonly reason?: string;
+ readonly commitCount: number;
+ readonly phases: ReadonlyArray<NoteHistoryPhase>;
+}
+
+export interface DecomposeNoteHistoryOptions {
+ /** A gap larger than this between consecutive commits starts a new phase. Default 72h. */
+ readonly gapHours?: number;
+ /** Repository root to read from. Default: the vault directory. */
+ readonly repoPath?: string;
+ /** Bound the walk to the newest N commits touching the path. */
+ readonly maxCount?: number;
+}
+
+const DEFAULT_GAP_HOURS = 72;
+const HOUR_MS = 60 * 60 * 1000;
+
+export function decomposeNoteHistory(
+ vault: string,
+ notePath: string,
+ opts: DecomposeNoteHistoryOptions = {},
+): NoteHistoryResult {
+ const path = notePath.trim();
+ if (path.length === 0) {
+ return Object.freeze({
+ notePath,
+ available: false,
+ reason: "no note path given",
+ commitCount: 0,
+ phases: Object.freeze([]),
+ });
+ }
+
+ const repoPath = opts.repoPath ?? vault;
+ const commits = readCommits(repoPath, {
+ path,
+ ...(opts.maxCount !== undefined ? { maxCount: opts.maxCount } : {}),
+ });
+
+ if (commits === null) {
+ return Object.freeze({
+ notePath: path,
+ available: false,
+ reason: "no history available (not a git repository or git unavailable)",
+ commitCount: 0,
+ phases: Object.freeze([]),
+ });
+ }
+ if (commits.length === 0) {
+ return Object.freeze({
+ notePath: path,
+ available: true,
+ reason: "no commits touch this path",
+ commitCount: 0,
+ phases: Object.freeze([]),
+ });
+ }
+
+ const gapMs = Math.max(0, opts.gapHours ?? DEFAULT_GAP_HOURS) * HOUR_MS;
+ const phases = splitIntoPhases(commits, gapMs);
+ return Object.freeze({
+ notePath: path,
+ available: true,
+ commitCount: commits.length,
+ phases: Object.freeze(phases),
+ });
+}
+
+function splitIntoPhases(commits: ReadonlyArray<GitCommit>, gapMs: number): NoteHistoryPhase[] {
+ const groups: GitCommit[][] = [];
+ let current: GitCommit[] = [];
+ let prevMs: number | null = null;
+ for (const commit of commits) {
+ const ms = parseMs(commit.committedAt);
+ const gap = prevMs !== null && ms !== null ? ms - prevMs : 0;
+ if (current.length > 0 && gap > gapMs) {
+ groups.push(current);
+ current = [];
+ }
+ current.push(commit);
+ if (ms !== null) prevMs = ms;
+ }
+ if (current.length > 0) groups.push(current);
+ return groups.map((group, index) => toPhase(group, index));
+}
+
+function toPhase(group: ReadonlyArray<GitCommit>, index: number): NoteHistoryPhase {
+ const first = group[0]!;
+ const last = group[group.length - 1]!;
+ const authors: string[] = [];
+ for (const commit of group) {
+ if (commit.authorName.length > 0 && !authors.includes(commit.authorName)) {
+ authors.push(commit.authorName);
+ }
+ }
+ return Object.freeze({
+ index,
+ firstSha: first.sha,
+ lastSha: last.sha,
+ firstDate: first.committedAt,
+ lastDate: last.committedAt,
+ commitCount: group.length,
+ authors: Object.freeze(authors),
+ subjects: Object.freeze(group.map((commit) => commit.subject)),
+ });
+}
+
+function parseMs(iso: string): number | null {
+ const ms = Date.parse(iso);
+ return Number.isNaN(ms) ? null : ms;
+}
diff --git a/src/core/brain/session-summary.ts b/src/core/brain/session-summary.ts
new file mode 100644
index 00000000..ca824710
--- /dev/null
+++ b/src/core/brain/session-summary.ts
@@ -0,0 +1,206 @@
+/**
+ * Structured session summary (Session Knowledge Synthesis, t_325a7e4a).
+ *
+ * A session-scoped digest over four canonical categories - request,
+ * decisions, learnings, next_steps - stored as one append-only
+ * continuity record (`kind: "session_summary_digest"`). This is
+ * distinct from `session_summary_node` (a hierarchical recall rollup of
+ * turns) and from `pre_compact_extract` (per-line labelled extracts):
+ * the digest answers "what was the request, what did we decide, what
+ * did we learn, what is next" for a whole session as a single unit.
+ *
+ * Provider-agnostic by construction: the agent supplies the already-
+ * extracted categories; this module only validates shape, dedupes by
+ * content hash, and appends. The kernel never parses prose into
+ * categories with a natural-language word list - that would break the
+ * language-agnostic guarantee. Absent agent extraction, no digest is
+ * written (no fabricated empty summary).
+ */
+
+import { createHash } from "node:crypto";
+
+import { appendContinuityRecord, listContinuityRecords } from "./continuity/store.ts";
+import type { ContinuityRecord, ContinuitySourceRef } from "./continuity/types.ts";
+
+export class SessionSummaryError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "SessionSummaryError";
+ }
+}
+
+export interface SessionSummaryInput {
+ readonly sessionId: string;
+ /** One-line statement of what the session set out to do. */
+ readonly request?: string;
+ readonly decisions?: ReadonlyArray<string>;
+ readonly learnings?: ReadonlyArray<string>;
+ readonly nextSteps?: ReadonlyArray<string>;
+ /** Originating runtime (claude, codex, ...); recorded when present. */
+ readonly host?: string;
+ /** Turn ids the digest was distilled from; recorded as lineage edges. */
+ readonly sourceTurnIds?: ReadonlyArray<string>;
+ readonly createdAt?: string;
+}
+
+export interface SessionSummaryDigest {
+ readonly id: string;
+ readonly sessionId: string;
+ readonly request: string | null;
+ readonly decisions: ReadonlyArray<string>;
+ readonly learnings: ReadonlyArray<string>;
+ readonly nextSteps: ReadonlyArray<string>;
+ readonly createdAt: string;
+ readonly host?: string;
+}
+
+const KIND = "session_summary_digest";
+
+/**
+ * Validate the agent-supplied categories, dedupe by content hash, and
+ * append one digest record. Throws {@link SessionSummaryError} when
+ * every category is empty - an empty digest is never written.
+ */
+export function appendSessionSummary(
+ vault: string,
+ input: SessionSummaryInput,
+): SessionSummaryDigest {
+ const sessionId = input.sessionId.trim();
+ if (sessionId.length === 0) {
+ throw new SessionSummaryError("session summary requires a non-empty session id");
+ }
+ const request = normalizeLine(input.request);
+ const decisions = normalizeList(input.decisions);
+ const learnings = normalizeList(input.learnings);
+ const nextSteps = normalizeList(input.nextSteps);
+
+ if (
+ request === null &&
+ decisions.length === 0 &&
+ learnings.length === 0 &&
+ nextSteps.length === 0
+ ) {
+ throw new SessionSummaryError(
+ "session summary requires at least one of request, decisions, learnings, or next_steps",
+ );
+ }
+
+ const host = input.host?.trim();
+ const contentHash = hash(JSON.stringify([request ?? "", decisions, learnings, nextSteps]));
+ const dedupeKey = [KIND, sessionId, contentHash].join(":");
+
+ const existing = findByDedupeKey(vault, dedupeKey);
+ if (existing !== null) return toDigest(existing);
+
+ const createdAt = input.createdAt ?? new Date().toISOString();
+ const record = appendContinuityRecord(vault, {
+ kind: KIND,
+ createdAt,
+ sourceRefs: buildSourceRefs(sessionId, input.sourceTurnIds),
+ payload: {
+ session_id: sessionId,
+ ...(request !== null ? { request } : {}),
+ decisions,
+ learnings,
+ next_steps: nextSteps,
+ ...(host !== undefined && host.length > 0 ? { host } : {}),
+ content_hash: contentHash,
+ dedupe_key: dedupeKey,
+ },
+ });
+ return toDigest(record);
+}
+
+/** Latest digest for a session, or null when none was ever written. */
+export function getSessionSummary(vault: string, sessionId: string): SessionSummaryDigest | null {
+ const id = sessionId.trim();
+ const records = sessionDigestRecords(vault).filter(
+ (record) => String(record.payload["session_id"] ?? "") === id,
+ );
+ if (records.length === 0) return null;
+ return toDigest(records[records.length - 1]!);
+}
+
+export interface ListSessionSummariesOptions {
+ readonly sessionId?: string;
+}
+
+/** All digests, oldest first; optionally scoped to one session. */
+export function listSessionSummaries(
+ vault: string,
+ opts: ListSessionSummariesOptions = {},
+): ReadonlyArray<SessionSummaryDigest> {
+ const scope = opts.sessionId?.trim();
+ return Object.freeze(
+ sessionDigestRecords(vault)
+ .filter(
+ (record) => scope === undefined || String(record.payload["session_id"] ?? "") === scope,
+ )
+ .map(toDigest),
+ );
+}
+
+function sessionDigestRecords(vault: string): ReadonlyArray<ContinuityRecord> {
+ return listContinuityRecords(vault, { kind: KIND }).toSorted((left, right) =>
+ compareByCreatedThenId(left, right),
+ );
+}
+
+function compareByCreatedThenId(left: ContinuityRecord, right: ContinuityRecord): number {
+ return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
+}
+
+function buildSourceRefs(
+ sessionId: string,
+ turnIds: ReadonlyArray<string> | undefined,
+): ReadonlyArray<ContinuitySourceRef> {
+ const refs: ContinuitySourceRef[] = [Object.freeze({ kind: "session", id: sessionId })];
+ for (const turnId of turnIds ?? []) {
+ const id = turnId.trim();
+ if (id.length > 0) refs.push(Object.freeze({ kind: "session_turn", id }));
+ }
+ return Object.freeze(refs);
+}
+
+function toDigest(record: ContinuityRecord): SessionSummaryDigest {
+ const payload = record.payload;
+ const host = typeof payload["host"] === "string" ? (payload["host"] as string) : undefined;
+ return Object.freeze({
+ id: record.id,
+ sessionId: String(payload["session_id"] ?? ""),
+ request: typeof payload["request"] === "string" ? (payload["request"] as string) : null,
+ decisions: readList(payload["decisions"]),
+ learnings: readList(payload["learnings"]),
+ nextSteps: readList(payload["next_steps"]),
+ createdAt: record.createdAt,
+ ...(host !== undefined ? { host } : {}),
+ });
+}
+
+function findByDedupeKey(vault: string, dedupeKey: string): ContinuityRecord | null {
+ return (
+ listContinuityRecords(vault, { kind: KIND }).find(
+ (record) => record.payload["dedupe_key"] === dedupeKey,
+ ) ?? null
+ );
+}
+
+function normalizeLine(value: string | undefined): string | null {
+ if (typeof value !== "string") return null;
+ const trimmed = value.trim();
+ return trimmed.length > 0 ? trimmed : null;
+}
+
+function normalizeList(values: ReadonlyArray<string> | undefined): ReadonlyArray<string> {
+ if (values === undefined) return Object.freeze([]);
+ return Object.freeze(values.map((value) => value.trim()).filter((value) => value.length > 0));
+}
+
+function readList(value: unknown): ReadonlyArray<string> {
+ if (!Array.isArray(value)) return Object.freeze([]);
+ return Object.freeze(value.filter((item): item is string => typeof item === "string"));
+}
+
+function hash(value: string): string {
+ return createHash("sha256").update(value).digest("hex").slice(0, 16);
+}
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 6cfdbb71..f2761999 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -31,6 +31,7 @@ import { INGEST_TOOLS } from "./brain/ingest-tools.ts";
import { RESEARCH_TOOLS } from "./brain/research-tools.ts";
import { DERIVE_TOOLS } from "./brain/derive-tools.ts";
import { NOTES_TOOLS } from "./brain/notes-tools.ts";
+import { SYNTHESIS_TOOLS } from "./brain/synthesis-tools.ts";
import type { ToolDefinition } from "./tools.ts";
export { vaultRelativeSafe } from "./brain/shared.ts";
@@ -57,4 +58,5 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
...RESEARCH_TOOLS,
...DERIVE_TOOLS,
...NOTES_TOOLS,
+ ...SYNTHESIS_TOOLS,
]);
diff --git a/src/mcp/brain/synthesis-tools.ts b/src/mcp/brain/synthesis-tools.ts
new file mode 100644
index 00000000..5372461b
--- /dev/null
+++ b/src/mcp/brain/synthesis-tools.ts
@@ -0,0 +1,283 @@
+/**
+ * Session Knowledge Synthesis tools (t_325a7e4a, t_635a3ea5, t_6a201155).
+ *
+ * Registered through the brain-tools.ts aggregator. Every tool here is
+ * agent-driven or read-only: the kernel validates and stores already-
+ * extracted structure or reads existing edges, and never calls an LLM.
+ */
+
+import {
+ appendSessionSummary,
+ getSessionSummary,
+ listSessionSummaries,
+ SessionSummaryError,
+ type SessionSummaryDigest,
+} from "../../core/brain/session-summary.ts";
+import {
+ traceIdeaLineage,
+ IdeaLineageError,
+ type IdeaLineageResult,
+} from "../../core/brain/idea-lineage.ts";
+import { decomposeNoteHistory } from "../../core/brain/note-history.ts";
+import { INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tools.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+
+const SUMMARY_TOOL = "brain_session_summary";
+
+function requiredSessionId(args: Record<string, unknown>): string {
+ const value = args["session_id"];
+ if (typeof value !== "string" || value.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, `${SUMMARY_TOOL}: session_id is required`);
+ }
+ return value.trim();
+}
+
+function stringArrayArg(
+ args: Record<string, unknown>,
+ name: string,
+): ReadonlyArray<string> | undefined {
+ const value = args[name];
+ if (value === undefined || value === null) return undefined;
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) {
+ throw new MCPError(INVALID_PARAMS, `${SUMMARY_TOOL}: ${name} must be an array of strings`);
+ }
+ return value as ReadonlyArray<string>;
+}
+
+function serializeDigest(digest: SessionSummaryDigest): Record<string, unknown> {
+ return {
+ id: digest.id,
+ session_id: digest.sessionId,
+ request: digest.request,
+ decisions: digest.decisions,
+ learnings: digest.learnings,
+ next_steps: digest.nextSteps,
+ created_at: digest.createdAt,
+ ...(digest.host !== undefined ? { host: digest.host } : {}),
+ };
+}
+
+async function toolBrainSessionSummary(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const operation = args["operation"];
+ if (operation !== "write" && operation !== "get" && operation !== "list") {
+ throw new MCPError(INVALID_PARAMS, `${SUMMARY_TOOL}: operation must be write|get|list`);
+ }
+
+ if (operation === "write") {
+ const sessionId = requiredSessionId(args);
+ const request = args["request"];
+ const decisions = stringArrayArg(args, "decisions");
+ const learnings = stringArrayArg(args, "learnings");
+ const nextSteps = stringArrayArg(args, "next_steps");
+ const host = args["host"];
+ const sourceTurnIds = stringArrayArg(args, "source_turn_ids");
+ try {
+ const digest = appendSessionSummary(ctx.vault, {
+ sessionId,
+ ...(typeof request === "string" ? { request } : {}),
+ ...(decisions !== undefined ? { decisions } : {}),
+ ...(learnings !== undefined ? { learnings } : {}),
+ ...(nextSteps !== undefined ? { nextSteps } : {}),
+ ...(typeof host === "string" ? { host } : {}),
+ ...(sourceTurnIds !== undefined ? { sourceTurnIds } : {}),
+ });
+ return { written: true, digest: serializeDigest(digest) };
+ } catch (error) {
+ if (error instanceof SessionSummaryError) {
+ throw new MCPError(INVALID_PARAMS, error.message);
+ }
+ throw error;
+ }
+ }
+
+ if (operation === "get") {
+ const sessionId = requiredSessionId(args);
+ const digest = getSessionSummary(ctx.vault, sessionId);
+ return digest === null ? { found: false } : { found: true, digest: serializeDigest(digest) };
+ }
+
+ // operation === "list"
+ const sessionIdRaw = args["session_id"];
+ const sessionId =
+ typeof sessionIdRaw === "string" && sessionIdRaw.trim().length > 0
+ ? sessionIdRaw.trim()
+ : undefined;
+ const digests = listSessionSummaries(ctx.vault, sessionId !== undefined ? { sessionId } : {});
+ return { count: digests.length, digests: digests.map(serializeDigest) };
+}
+
+const LINEAGE_TOOL = "brain_idea_lineage";
+
+function serializeLineage(result: IdeaLineageResult): Record<string, unknown> {
+ return {
+ root: result.root,
+ nodes: result.nodes,
+ edges: result.edges,
+ truncated: result.truncated,
+ };
+}
+
+function toolBrainIdeaLineage(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const idRaw = args["id"];
+ if (typeof idRaw !== "string" || idRaw.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, `${LINEAGE_TOOL}: id is required`);
+ }
+ const maxDepthRaw = args["max_depth"];
+ let maxDepth: number | undefined;
+ if (maxDepthRaw !== undefined && maxDepthRaw !== null) {
+ if (typeof maxDepthRaw !== "number" || !Number.isInteger(maxDepthRaw) || maxDepthRaw < 1) {
+ throw new MCPError(INVALID_PARAMS, `${LINEAGE_TOOL}: max_depth must be a positive integer`);
+ }
+ maxDepth = maxDepthRaw;
+ }
+ try {
+ return serializeLineage(
+ traceIdeaLineage(ctx.vault, { id: idRaw.trim() }, maxDepth !== undefined ? { maxDepth } : {}),
+ );
+ } catch (error) {
+ if (error instanceof IdeaLineageError) {
+ throw new MCPError(INVALID_PARAMS, error.message);
+ }
+ throw error;
+ }
+}
+
+const HISTORY_TOOL = "brain_note_history";
+
+function toolBrainNoteHistory(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const pathRaw = args["path"];
+ if (typeof pathRaw !== "string" || pathRaw.trim().length === 0) {
+ throw new MCPError(INVALID_PARAMS, `${HISTORY_TOOL}: path is required`);
+ }
+ const gapHours = positiveIntArg(args, "gap_hours");
+ const maxCount = positiveIntArg(args, "max_count");
+ const result = decomposeNoteHistory(ctx.vault, pathRaw.trim(), {
+ ...(gapHours !== undefined ? { gapHours } : {}),
+ ...(maxCount !== undefined ? { maxCount } : {}),
+ });
+ return {
+ note_path: result.notePath,
+ available: result.available,
+ ...(result.reason !== undefined ? { reason: result.reason } : {}),
+ commit_count: result.commitCount,
+ phases: result.phases,
+ };
+}
+
+function positiveIntArg(args: Record<string, unknown>, name: string): number | undefined {
+ const value = args[name];
+ if (value === undefined || value === null) return undefined;
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) {
+ throw new MCPError(INVALID_PARAMS, `${HISTORY_TOOL}: ${name} must be a positive integer`);
+ }
+ return value;
+}
+
+export const SYNTHESIS_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: SUMMARY_TOOL,
+ description:
+ "Session-scoped structured digest over request/decisions/learnings/next_steps. write stores agent-extracted categories; get returns a session's latest digest; list returns all (optionally one session). Append-only, deduped; an all-empty digest is rejected.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["write", "get", "list"],
+ description: "Tool operation.",
+ },
+ session_id: {
+ type: "string",
+ description: "Session id (required for write/get; optional scope for list).",
+ },
+ request: {
+ type: "string",
+ description: "write: one-line statement of the session's goal.",
+ },
+ decisions: {
+ type: "array",
+ items: { type: "string" },
+ description: "write: decisions made this session.",
+ },
+ learnings: {
+ type: "array",
+ items: { type: "string" },
+ description: "write: things learned this session.",
+ },
+ next_steps: {
+ type: "array",
+ items: { type: "string" },
+ description: "write: follow-up actions.",
+ },
+ source_turn_ids: {
+ type: "array",
+ items: { type: "string" },
+ description: "write: turn ids the digest was distilled from (lineage edges).",
+ },
+ host: { type: "string", description: "write: originating runtime (claude, codex, ...)." },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ handler: toolBrainSessionSummary,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: LINEAGE_TOOL,
+ description:
+ "Read-only provenance tracer: how a derived artifact was reached, as an observation -> synthesis -> conclusion graph. A ctn_ id walks the sourceRefs graph; a pref-/ret- id adapts belief-evolution. Cycle-guarded, depth-bounded; an unknown id errors.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ id: {
+ type: "string",
+ description: "Continuity record id (ctn_...) or preference id (pref-.../ret-...).",
+ },
+ max_depth: {
+ type: "integer",
+ minimum: 1,
+ description: "Maximum backward hops from the artifact (default 8).",
+ },
+ },
+ required: ["id"],
+ additionalProperties: false,
+ },
+ handler: toolBrainIdeaLineage,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+ {
+ name: HISTORY_TOOL,
+ description:
+ "Decompose a note's git history into episodic phases, split when the gap between commits exceeds gap_hours (default 72) - deterministic and language-agnostic. Each phase carries subjects, dates, authors. Missing repo: available=false; no commits: zero phases. Read-only.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ path: { type: "string", description: "Repo-relative note path (git pathspec)." },
+ gap_hours: {
+ type: "integer",
+ minimum: 1,
+ description: "Inter-commit gap that starts a new phase (default 72).",
+ },
+ max_count: {
+ type: "integer",
+ minimum: 1,
+ description: "Bound the walk to the newest N commits touching the path.",
+ },
+ },
+ required: ["path"],
+ additionalProperties: false,
+ },
+ handler: toolBrainNoteHistory,
+ previewBudget: MCP_PREVIEW_BUDGET,
+ },
+]);
diff --git a/tests/core/brain.idea-lineage.test.ts b/tests/core/brain.idea-lineage.test.ts
new file mode 100644
index 00000000..6c2dd0ca
--- /dev/null
+++ b/tests/core/brain.idea-lineage.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { traceIdeaLineage, IdeaLineageError } from "../../src/core/brain/idea-lineage.ts";
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { appendSessionSummary } from "../../src/core/brain/session-summary.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-idea-lineage-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeDream(date: string, body: Record<string, unknown>): void {
+ mkdirSync(join(vault, "Brain", "log"), { recursive: true });
+ const line = JSON.stringify({ ts: `${date}T08:00:00Z`, kind: "dream", payload: body });
+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), `${line}\n`);
+}
+
+describe("traceIdeaLineage over the continuity source graph", () => {
+ test("a digest traces back to the session turns it was distilled from", () => {
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-14T09:00:00.000Z",
+ payload: { session_id: "s1", turn_id: "t1", role: "user", text: "please add lineage" },
+ });
+ const digest = appendSessionSummary(vault, {
+ sessionId: "s1",
+ decisions: ["build the tracer"],
+ sourceTurnIds: ["t1"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+
+ const result = traceIdeaLineage(vault, { id: digest.id });
+ expect(result.root.id).toBe(digest.id);
+ expect(result.root.stage).toBe("conclusion");
+
+ const turn = result.nodes.find((n) => n.kind === "session_turn");
+ expect(turn).toBeDefined();
+ expect(turn!.stage).toBe("observation");
+ expect(result.edges.some((e) => e.from === digest.id && e.to === turn!.id)).toBe(true);
+ });
+
+ test("a source referenced more than once appears once and traversal terminates", () => {
+ const turn = appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-14T09:00:00.000Z",
+ payload: { session_id: "s2", turn_id: "t1", role: "user", text: "hi" },
+ });
+ // A node whose sourceRefs reference the same turn twice (by record id
+ // and by turn id) must not produce a duplicate node or loop.
+ const node = appendContinuityRecord(vault, {
+ kind: "session_summary_node",
+ createdAt: "2026-06-14T10:00:00.000Z",
+ sourceRefs: [
+ { id: turn.id, kind: "continuity_record" },
+ { id: "t1", kind: "session_turn" },
+ ],
+ payload: { session_id: "s2", depth: 1, summary: "rollup" },
+ });
+
+ const result = traceIdeaLineage(vault, { id: node.id });
+ const turnNodes = result.nodes.filter((n) => n.id === turn.id);
+ expect(turnNodes.length).toBe(1);
+ expect(result.truncated).toBe(false);
+ });
+
+ test("a turn ref resolves within the digest's own session when turn ids collide", () => {
+ // Two sessions reuse turn_id "t1". The digest in session A must link to
+ // A's turn, never B's.
+ const turnA = appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-14T09:00:00.000Z",
+ payload: { session_id: "A", turn_id: "t1", role: "user", text: "in A" },
+ });
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-14T09:30:00.000Z",
+ payload: { session_id: "B", turn_id: "t1", role: "user", text: "in B" },
+ });
+ const digestA = appendSessionSummary(vault, {
+ sessionId: "A",
+ decisions: ["decided in A"],
+ sourceTurnIds: ["t1"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+
+ const result = traceIdeaLineage(vault, { id: digestA.id });
+ const turnNodes = result.nodes.filter((n) => n.kind === "session_turn");
+ expect(turnNodes.length).toBe(1);
+ expect(turnNodes[0]!.id).toBe(turnA.id);
+ });
+
+ test("an unknown id is a typed error, not a silent empty chain", () => {
+ expect(() => traceIdeaLineage(vault, { id: "ctn_does_not_exist" })).toThrow(IdeaLineageError);
+ });
+
+ test("a depth bound is reported as truncated", () => {
+ // Chain: n2 -> n1 -> turn. maxDepth 1 stops before the turn.
+ const turn = appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-14T08:00:00.000Z",
+ payload: { session_id: "s3", turn_id: "t1", role: "user", text: "root cause" },
+ });
+ const n1 = appendContinuityRecord(vault, {
+ kind: "session_summary_node",
+ createdAt: "2026-06-14T09:00:00.000Z",
+ sourceRefs: [{ id: turn.id, kind: "continuity_record" }],
+ payload: { session_id: "s3", depth: 1, summary: "level 1" },
+ });
+ const n2 = appendContinuityRecord(vault, {
+ kind: "session_summary_node",
+ createdAt: "2026-06-14T10:00:00.000Z",
+ sourceRefs: [{ id: n1.id, kind: "continuity_record" }],
+ payload: { session_id: "s3", depth: 2, summary: "level 2" },
+ });
+
+ const result = traceIdeaLineage(vault, { id: n2.id }, { maxDepth: 1 });
+ expect(result.truncated).toBe(true);
+ });
+});
+
+describe("traceIdeaLineage for a preference (belief evolution)", () => {
+ test("traces creation then promotion of a preference", () => {
+ writeDream("2026-05-01", { run_id: "r1", new_unconfirmed: ["[[pref-foo|First rule]]"] });
+ writeDream("2026-05-10", { run_id: "r2", confirmed: ["[[pref-foo|First rule]]"] });
+
+ const result = traceIdeaLineage(vault, { id: "pref-foo" });
+ expect(result.root.id).toBe("pref-foo");
+ expect(result.root.kind).toBe("preference");
+ const stages = result.nodes.map((n) => n.stage);
+ expect(stages).toContain("observation"); // creation
+ expect(stages).toContain("synthesis"); // promotion
+ });
+
+ test("an unknown preference is a typed error", () => {
+ expect(() => traceIdeaLineage(vault, { id: "pref-missing" })).toThrow(IdeaLineageError);
+ });
+});
diff --git a/tests/core/brain.note-history.test.ts b/tests/core/brain.note-history.test.ts
new file mode 100644
index 00000000..2651d2e9
--- /dev/null
+++ b/tests/core/brain.note-history.test.ts
@@ -0,0 +1,116 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { decomposeNoteHistory } from "../../src/core/brain/note-history.ts";
+
+let tmp: string;
+let repo: string;
+
+function git(env: Record<string, string>, ...args: string[]): string {
+ return execFileSync(
+ "git",
+ [
+ "-C",
+ repo,
+ "-c",
+ "user.name=Fixture Author",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ ...args,
+ ],
+ { encoding: "utf8", env: { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", ...env } },
+ ).trim();
+}
+
+function commitFileAt(relPath: string, content: string, message: string, isoDate: string): void {
+ const abs = join(repo, relPath);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, content);
+ git({}, "add", "--", relPath);
+ git({ GIT_AUTHOR_DATE: isoDate, GIT_COMMITTER_DATE: isoDate }, "commit", "-q", "-m", message);
+}
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-note-history-"));
+ repo = join(tmp, "repo");
+ mkdirSync(repo, { recursive: true });
+ git({}, "init", "-q", "-b", "main");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+describe("decomposeNoteHistory", () => {
+ test("splits a commit chain into phases on a time gap above the threshold", () => {
+ // Phase 1: two commits a day apart. Then a 10-day gap. Phase 2: one commit.
+ commitFileAt("notes/topic.md", "v1", "start topic", "2026-05-01T10:00:00Z");
+ commitFileAt("notes/topic.md", "v2", "refine topic", "2026-05-02T10:00:00Z");
+ commitFileAt("notes/topic.md", "v3", "revisit topic", "2026-05-12T10:00:00Z");
+
+ const result = decomposeNoteHistory(repo, "notes/topic.md", {
+ repoPath: repo,
+ gapHours: 72,
+ });
+ expect(result.available).toBe(true);
+ expect(result.commitCount).toBe(3);
+ expect(result.phases.length).toBe(2);
+ expect(result.phases[0]!.commitCount).toBe(2);
+ expect(result.phases[0]!.subjects).toEqual(["start topic", "refine topic"]);
+ expect(result.phases[1]!.commitCount).toBe(1);
+ expect(result.phases[1]!.subjects).toEqual(["revisit topic"]);
+ });
+
+ test("keeps closely-spaced commits in a single phase", () => {
+ commitFileAt("notes/topic.md", "v1", "a", "2026-05-01T10:00:00Z");
+ commitFileAt("notes/topic.md", "v2", "b", "2026-05-01T12:00:00Z");
+ commitFileAt("notes/topic.md", "v3", "c", "2026-05-01T15:00:00Z");
+
+ const result = decomposeNoteHistory(repo, "notes/topic.md", { repoPath: repo, gapHours: 72 });
+ expect(result.phases.length).toBe(1);
+ expect(result.phases[0]!.commitCount).toBe(3);
+ });
+
+ test("only counts commits that touched the note path", () => {
+ commitFileAt("notes/topic.md", "v1", "topic", "2026-05-01T10:00:00Z");
+ commitFileAt("other/unrelated.md", "x", "unrelated", "2026-05-01T11:00:00Z");
+
+ const result = decomposeNoteHistory(repo, "notes/topic.md", { repoPath: repo });
+ expect(result.commitCount).toBe(1);
+ expect(result.phases.length).toBe(1);
+ });
+
+ test("a path with no commits is available with zero phases (empty != broken)", () => {
+ commitFileAt("notes/topic.md", "v1", "topic", "2026-05-01T10:00:00Z");
+ const result = decomposeNoteHistory(repo, "notes/never-existed.md", { repoPath: repo });
+ expect(result.available).toBe(true);
+ expect(result.commitCount).toBe(0);
+ expect(result.phases.length).toBe(0);
+ expect(result.reason).toBeDefined();
+ });
+
+ test("a non-repository directory reports no history available, not an empty success", () => {
+ const notRepo = mkdtempSync(join(tmpdir(), "o2b-not-a-repo-"));
+ try {
+ const result = decomposeNoteHistory(notRepo, "notes/topic.md", { repoPath: notRepo });
+ expect(result.available).toBe(false);
+ expect(result.phases.length).toBe(0);
+ expect(result.reason).toContain("no history available");
+ } finally {
+ rmSync(notRepo, { recursive: true, force: true });
+ }
+ });
+
+ test("phase splitting is independent of commit-message language", () => {
+ // Same dates and structure, non-Latin subjects: the split is identical.
+ commitFileAt("notes/topic.md", "v1", "начало темы", "2026-05-01T10:00:00Z");
+ commitFileAt("notes/topic.md", "v2", "主题更新", "2026-05-12T10:00:00Z");
+ const result = decomposeNoteHistory(repo, "notes/topic.md", { repoPath: repo, gapHours: 72 });
+ expect(result.phases.length).toBe(2);
+ });
+});
diff --git a/tests/core/brain.session-summary.test.ts b/tests/core/brain.session-summary.test.ts
new file mode 100644
index 00000000..d7e2cf3f
--- /dev/null
+++ b/tests/core/brain.session-summary.test.ts
@@ -0,0 +1,117 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ appendSessionSummary,
+ getSessionSummary,
+ listSessionSummaries,
+ SessionSummaryError,
+} from "../../src/core/brain/session-summary.ts";
+import { listContinuityRecords } from "../../src/core/brain/continuity/store.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-session-summary-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+describe("appendSessionSummary", () => {
+ test("writes a session-scoped digest and reads it back as a unit", () => {
+ const digest = appendSessionSummary(vault, {
+ sessionId: "sess-1",
+ request: "Add a structured session summary",
+ decisions: ["Reuse the continuity store", "Agent supplies categories"],
+ learnings: ["session_summary_node is a recall rollup, not a digest"],
+ nextSteps: ["Wire the MCP tool"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ expect(digest.sessionId).toBe("sess-1");
+ expect(digest.request).toBe("Add a structured session summary");
+ expect(digest.decisions).toEqual(["Reuse the continuity store", "Agent supplies categories"]);
+ expect(digest.learnings.length).toBe(1);
+ expect(digest.nextSteps).toEqual(["Wire the MCP tool"]);
+
+ const read = getSessionSummary(vault, "sess-1");
+ expect(read).not.toBeNull();
+ expect(read!.id).toBe(digest.id);
+ expect(read!.decisions).toEqual(digest.decisions);
+ });
+
+ test("rejects a digest with no content in any category (no empty digest)", () => {
+ expect(() =>
+ appendSessionSummary(vault, {
+ sessionId: "sess-empty",
+ request: " ",
+ decisions: ["", " "],
+ learnings: [],
+ nextSteps: [],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ }),
+ ).toThrow(SessionSummaryError);
+ });
+
+ test("trims and drops empty category entries", () => {
+ const digest = appendSessionSummary(vault, {
+ sessionId: "sess-trim",
+ decisions: [" keep me ", "", " "],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ expect(digest.decisions).toEqual(["keep me"]);
+ expect(digest.request).toBeNull();
+ expect(digest.learnings).toEqual([]);
+ });
+
+ test("dedupes an identical re-append for the same session", () => {
+ const input = {
+ sessionId: "sess-dup",
+ decisions: ["one decision"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ } as const;
+ const first = appendSessionSummary(vault, input);
+ const second = appendSessionSummary(vault, input);
+ expect(second.id).toBe(first.id);
+ expect(listContinuityRecords(vault, { kind: "session_summary_digest" }).length).toBe(1);
+ });
+
+ test("getSessionSummary returns the latest digest when several exist", () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-multi",
+ decisions: ["older"],
+ createdAt: "2026-06-14T09:00:00.000Z",
+ });
+ const newer = appendSessionSummary(vault, {
+ sessionId: "sess-multi",
+ decisions: ["newer"],
+ createdAt: "2026-06-14T11:00:00.000Z",
+ });
+ expect(getSessionSummary(vault, "sess-multi")!.id).toBe(newer.id);
+ });
+
+ test("records source refs to the session and its turns for lineage", () => {
+ appendSessionSummary(vault, {
+ sessionId: "sess-refs",
+ decisions: ["decided"],
+ sourceTurnIds: ["t-1", "t-2"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const record = listContinuityRecords(vault, { kind: "session_summary_digest" })[0]!;
+ const refKinds = record.sourceRefs.map((r) => `${r.kind}:${r.id}`);
+ expect(refKinds).toContain("session:sess-refs");
+ expect(refKinds).toContain("session_turn:t-1");
+ expect(refKinds).toContain("session_turn:t-2");
+ });
+});
+
+describe("byte-identical when unused", () => {
+ test("getSessionSummary returns null and the store stays empty when nothing is written", () => {
+ expect(getSessionSummary(vault, "never")).toBeNull();
+ expect(listSessionSummaries(vault).length).toBe(0);
+ expect(listContinuityRecords(vault).length).toBe(0);
+ });
+});
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index d9bcbe10..54778fa2 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -46,6 +46,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_health",
"brain_hygiene",
"brain_idea_discovery",
+ "brain_idea_lineage",
"brain_ingest_source",
"brain_intake_entities",
"brain_intent_review",
@@ -55,6 +56,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_mcp_landscape",
"brain_moc_audit",
"brain_note",
+ "brain_note_history",
"brain_pinned_context",
"brain_pre_compact_extract",
"brain_pre_compress_pack",
@@ -70,6 +72,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_session_describe",
"brain_session_expand",
"brain_session_grep",
+ "brain_session_summary",
"brain_skill_proposals",
"brain_sources",
"brain_stale_scan",
diff --git a/tests/mcp/idea-lineage-tool.test.ts b/tests/mcp/idea-lineage-tool.test.ts
new file mode 100644
index 00000000..1c12386b
--- /dev/null
+++ b/tests/mcp/idea-lineage-tool.test.ts
@@ -0,0 +1,86 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+import { appendContinuityRecord } from "../../src/core/brain/continuity/store.ts";
+import { appendSessionSummary } from "../../src/core/brain/session-summary.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-idea-lineage-tool-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "idea-lineage-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+async function call(args: Record<string, unknown>): Promise<{ result?: unknown; error?: unknown }> {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_idea_lineage", arguments: args },
+ })) as { result?: unknown; error?: unknown };
+}
+
+function payload(response: { result?: unknown }): Record<string, unknown> {
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ return JSON.parse(result.content[0]!.text);
+}
+
+describe("brain_idea_lineage tool", () => {
+ test("registered in the full tool table only", () => {
+ expect(buildToolTable("full").find((t) => t.name === "brain_idea_lineage")).toBeDefined();
+ expect(buildToolTable("writer").find((t) => t.name === "brain_idea_lineage")).toBeUndefined();
+ });
+
+ test("traces a digest back to its source turn", async () => {
+ appendContinuityRecord(vault, {
+ kind: "session_turn",
+ createdAt: "2026-06-14T09:00:00.000Z",
+ payload: { session_id: "s1", turn_id: "t1", role: "user", text: "trace me" },
+ });
+ const digest = appendSessionSummary(vault, {
+ sessionId: "s1",
+ decisions: ["d"],
+ sourceTurnIds: ["t1"],
+ createdAt: "2026-06-14T10:00:00.000Z",
+ });
+ const out = payload(await call({ id: digest.id }));
+ expect((out["root"] as Record<string, unknown>)["id"]).toBe(digest.id);
+ const nodes = out["nodes"] as Array<Record<string, unknown>>;
+ expect(nodes.some((n) => n["kind"] === "session_turn" && n["stage"] === "observation")).toBe(
+ true,
+ );
+ });
+
+ test("missing id is an invalid-params error", async () => {
+ const response = await call({});
+ expect((response.error as { code: number }).code).toBe(-32602);
+ });
+
+ test("unknown id is an invalid-params error", async () => {
+ const response = await call({ id: "ctn_nope" });
+ expect((response.error as { code: number }).code).toBe(-32602);
+ });
+});
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index c8eeee39..90b1e6bd 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -240,6 +240,10 @@ describe("tool listing", () => {
"brain_search",
"brain_eval",
"brain_file_context",
+ // Session Knowledge Synthesis Suite (v1.11.0).
+ "brain_session_summary",
+ "brain_idea_lineage",
+ "brain_note_history",
// Schema admin + watchdog recovery probes.
"schema_apply_mutations",
"schema_inspect",
@@ -538,7 +542,9 @@ describe("stdio loop", () => {
// / brain_derive_fact (Knowledge Provenance Suite, v1.7.0) = 76.
// + brain_create_note (Brain Portability & Interop Suite) = 77.
// + brain_file_context (Recall & Working-Memory Quality Suite) = 78.
- expect(list.result.tools.length).toBe(78);
+ // + brain_session_summary / brain_idea_lineage / brain_note_history
+ // (Session Knowledge Synthesis Suite, v1.11.0) = 81.
+ expect(list.result.tools.length).toBe(81);
});
test("returns parse error for invalid JSON", async () => {
diff --git a/tests/mcp/note-history-tool.test.ts b/tests/mcp/note-history-tool.test.ts
new file mode 100644
index 00000000..eaab59a8
--- /dev/null
+++ b/tests/mcp/note-history-tool.test.ts
@@ -0,0 +1,96 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let vault: string;
+
+function git(env: Record<string, string>, ...args: string[]): void {
+ execFileSync(
+ "git",
+ [
+ "-C",
+ vault,
+ "-c",
+ "user.name=Fix",
+ "-c",
+ "-c",
+ "commit.gpgsign=false",
+ ...args,
+ ],
+ { encoding: "utf8", env: { ...process.env, GIT_CONFIG_GLOBAL: "/dev/null", ...env } },
+ );
+}
+
+function commit(rel: string, content: string, msg: string, iso: string): void {
+ const abs = join(vault, rel);
+ mkdirSync(join(abs, ".."), { recursive: true });
+ writeFileSync(abs, content);
+ git({}, "add", "--", rel);
+ git({ GIT_AUTHOR_DATE: iso, GIT_COMMITTER_DATE: iso }, "commit", "-q", "-m", msg);
+}
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-note-history-tool-"));
+ git({}, "init", "-q", "-b", "main");
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "note-history-test", version: "0" },
+ },
+ });
+ await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });
+}
+
+async function call(args: Record<string, unknown>): Promise<{ result?: unknown; error?: unknown }> {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_note_history", arguments: args },
+ })) as { result?: unknown; error?: unknown };
+}
+
+function payload(response: { result?: unknown }): Record<string, unknown> {
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ return JSON.parse(result.content[0]!.text);
+}
+
+describe("brain_note_history tool", () => {
+ test("registered in the full tool table only", () => {
+ expect(buildToolTable("full").find((t) => t.name === "brain_note_history")).toBeDefined();
+ expect(buildToolTable("writer").find((t) => t.name === "brain_note_history")).toBeUndefined();
+ });
+
+ test("decomposes a note's history into phases on a gap", async () => {
+ commit("notes/topic.md", "v1", "start", "2026-05-01T10:00:00Z");
+ commit("notes/topic.md", "v2", "later", "2026-05-20T10:00:00Z");
+ const out = payload(await call({ path: "notes/topic.md", gap_hours: 72 }));
+ expect(out["available"]).toBe(true);
+ expect(out["commit_count"]).toBe(2);
+ expect((out["phases"] as unknown[]).length).toBe(2);
+ });
+
+ test("missing path is an invalid-params error", async () => {
+ const response = await call({});
+ expect((response.error as { code: number }).code).toBe(-32602);
+ });
+});
diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.ts
index baa91d27..bb033720 100644
--- a/tests/mcp/removed-tools.test.ts
+++ b/tests/mcp/removed-tools.test.ts
@@ -140,5 +140,7 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn
})) as { result: { tools: Array<{ name: string }> } };
// 76 + brain_create_note (Brain Portability & Interop Suite) = 77.
// + brain_file_context (Recall & Working-Memory Quality Suite) = 78.
- expect(list.result.tools.length).toBe(78);
+ // + brain_session_summary, brain_idea_lineage, brain_note_history
+ // (Session Knowledge Synthesis Suite) = 81.
+ expect(list.result.tools.length).toBe(81);
});
diff --git a/tests/mcp/session-summary-tool.test.ts b/tests/mcp/session-summary-tool.test.ts
new file mode 100644
index 00000000..b2d2c088
--- /dev/null
+++ b/tests/mcp/session-summary-tool.test.ts
@@ -0,0 +1,110 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
+import { buildToolTable } from "../../src/mcp/tools.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-session-summary-tool-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+async function initialize(server: MCPServer): Promise<void> {
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 1,
+ method: "initialize",
+ params: {
+ protocolVersion: PROTOCOL_VERSION,
+ capabilities: {},
+ clientInfo: { name: "session-summary-test", version: "0" },
+ },
+ });
+ await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ method: "notifications/initialized",
+ });
+}
+
+async function call(args: Record<string, unknown>): Promise<{ result?: unknown; error?: unknown }> {
+ const server = new MCPServer({ vault, configPath: null });
+ await initialize(server);
+ return (await server.handleRequest({
+ jsonrpc: JSONRPC_VERSION,
+ id: 9,
+ method: "tools/call",
+ params: { name: "brain_session_summary", arguments: args },
+ })) as { result?: unknown; error?: unknown };
+}
+
+function payload(response: { result?: unknown }): Record<string, unknown> {
+ const result = response.result as { content: ReadonlyArray<{ type: string; text: string }> };
+ return JSON.parse(result.content[0]!.text);
+}
+
+describe("brain_session_summary tool", () => {
+ test("registered in the full tool table only", () => {
+ expect(
+ buildToolTable("full").find((tool) => tool.name === "brain_session_summary"),
+ ).toBeDefined();
+ expect(
+ buildToolTable("writer").find((tool) => tool.name === "brain_session_summary"),
+ ).toBeUndefined();
+ });
+
+ test("write then get round-trips the digest", async () => {
+ const written = payload(
+ await call({
+ operation: "write",
+ session_id: "s1",
+ request: "Build the digest",
+ decisions: ["reuse continuity store"],
+ learnings: ["node != digest"],
+ next_steps: ["ship the tool"],
+ }),
+ );
+ expect(written["written"]).toBe(true);
+
+ const got = payload(await call({ operation: "get", session_id: "s1" }));
+ expect(got["found"]).toBe(true);
+ const digest = got["digest"] as Record<string, unknown>;
+ expect(digest["session_id"]).toBe("s1");
+ expect(digest["decisions"]).toEqual(["reuse continuity store"]);
+ expect(digest["next_steps"]).toEqual(["ship the tool"]);
+ });
+
+ test("get for an unknown session reports not found, not a fabricated digest", async () => {
+ const got = payload(await call({ operation: "get", session_id: "missing" }));
+ expect(got["found"]).toBe(false);
+ expect(got["digest"]).toBeUndefined();
+ });
+
+ test("write with no categories is an invalid-params error", async () => {
+ const response = await call({ operation: "write", session_id: "empty" });
+ expect(response.error).toBeDefined();
+ expect((response.error as { code: number }).code).toBe(-32602);
+ });
+
+ test("bad operation is an invalid-params error", async () => {
+ const response = await call({ operation: "frobnicate", session_id: "x" });
+ expect(response.error).toBeDefined();
+ expect((response.error as { code: number }).code).toBe(-32602);
+ });
+
+ test("list returns digests scoped to a session", async () => {
+ await call({ operation: "write", session_id: "a", decisions: ["da"] });
+ await call({ operation: "write", session_id: "b", decisions: ["db"] });
+ const all = payload(await call({ operation: "list" }));
+ expect(all["count"]).toBe(2);
+ const scoped = payload(await call({ operation: "list", session_id: "a" }));
+ expect(scoped["count"]).toBe(1);
+ expect((scoped["digests"] as Array<Record<string, unknown>>)[0]!["session_id"]).toBe("a");
+ });
+});