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: ingestion & import robustness (v1.27.0) (#132)
Sol Aitken99adb65f51fe
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex bee1b178..1cb7f5c4 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.26.1",+ "version": "1.27.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 30c6d19f..2a88fc97 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.26.1",+ "version": "1.27.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a2e9827b..e968d1e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,17 @@ 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.27.0] - 2026-07-10++An ingestion and import robustness layer that hardens and extends the source pipeline in one coherent scope: interrupted batches resume, more memory stores import, deterministic refresh skips when nothing changed, and sources distill into citeable claims. Every new surface is additive and off by default where it changes an existing path; the kernel still calls no LLM.++### Added++- **Resumable per-item batch checkpointing.** A plan-scoped checkpoint under `<vault>/.open-second-brain/ingest-checkpoints/<plan_id>.json` records completed items union-as-you-go, so an interrupted large-folder ingest resumes at the item boundary instead of re-planning from scratch. `planBatches` accepts `resume`, which excludes checkpointed items before content-hash classification (a fast-path that avoids re-hashing completed work on a large-vault resume) and returns a stable `plan_id` plus a `resumed_completed` count; `ingestSource` records completion when handed a `plan_id`. The `brain_ingest_batch_plan` MCP tool gains `resume` and returns `plan_id`, clearing a drained plan; `brain_ingest_source` and the `o2b brain batch-plan --resume` CLI carry it through. The content-hash manifest stays the authoritative final state. Opt out with `OSB_INGEST_NO_CHECKPOINT`.+- **mem0 and generic-JSON memory-store importers.** The `MemorySourceBackend` seam widened from one-file-one-entry to discover-files plus parse-entries, so a single JSON export maps to many Brain preferences. New `mem0` and `generic` backends parse a memory export (a top-level array or a `results`/`memories`/`entries` envelope) into preferences on the shared render path; the `claude` backend stays byte-identical. The `o2b brain import-claude-memory` CLI gains `--from`/`--backend` to select a non-default backend and can be pointed at a single export file. Unknown ids fail loudly with the registered list.+- **Staleness fast-path for deterministic refresh.** A reusable mtime staleness gate plus an opt-in `o2b brain clusters run --if-stale` that no-ops when the materialized `Brain/clusters/` notes are already newer than every input note, recording a freshness-skip metric and skipping the recompute entirely. Default behavior is unchanged; the `>=` comparison errs toward recompute, and a missing input never forces a needless rebuild.+- **Source distillation into atomic claims.** A new `o2b brain distill` CLI verb and `brain_distill_source` MCP tool condense a source into agent-supplied atomic claims, each with an optional source block id, and write an idempotent `Brain/distillations/` page that cites each claim as `[[source#^block]]` alongside a Sources provenance section and a content sha256 the verifier can reproduce. Provider-agnostic: the core runs no model, validates claims structurally, and rewrites one page per source in place.+## [1.26.1] - 2026-07-08An upstream-alignment guard release. Two regression suites now pin Open Second Brain's Hermes-facing surface against two landed upstream Hermes changes, with no source edits and no runtime behavior changes. The kernel still calls no LLM.@@ -6393,6 +6404,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.27.0]: https://github.com/itechmeat/open-second-brain/compare/v1.26.1...v1.27.0[1.24.0]: https://github.com/itechmeat/open-second-brain/compare/v1.23.1...v1.24.0[1.23.1]: https://github.com/itechmeat/open-second-brain/compare/v1.23.0...v1.23.1[1.23.0]: https://github.com/itechmeat/open-second-brain/compare/v1.22.0...v1.23.0diff --git a/docs/brainstorm/ingestion-import-robustness/design.md b/docs/brainstorm/ingestion-import-robustness/design.mdnew file mode 100644index 00000000..8f5cce22--- /dev/null+++ b/docs/brainstorm/ingestion-import-robustness/design.md@@ -0,0 +1,196 @@+# Design - Ingestion & Import Robustness++## Problem++Open Second Brain's ingestion/import pipeline has four concrete gaps, all in+the same subsystem:++1. **No within-pass resumability.** A large folder ingest is planned by+ `planBatches` and dispatched batch-by-batch; the content-hash manifest only+ records a source once its full `ingestSource` write lands. An interruption+ mid-plan leaves no durable ledger of *which planned items already completed*+ beyond what the manifest happens to have flushed - a resumed plan re-derives+ its work list from scratch, and the caller has no plan-scoped progress signal.+2. **Only the `claude` memory backend is importable.** The `MemorySourceBackend`+ registry exposes exactly one adapter, so a user migrating off mem0 (a popular+ agent-memory store) or holding a generic memory-store JSON dump has no path+ into Brain preferences.+3. **No cheap freshness gate on deterministic refresh.** `clusters run`+ re-materializes `Brain/clusters/` from the whole vault on every invocation.+ An agent that wants "refresh-on-demand at the start of graph work" must pay a+ full recompute even when nothing changed.+4. **No command turns a source into citeable atomic claims.** The block-id+ wikilink parser, source sha256 provenance, and session-summary lineage all+ exist, but nothing composes them into a distillation of a source into+ discrete, block-traceable claims.++## Scope++- `t_ba1fa5f6` Incremental per-item checkpointing (resumable batch ingest).+- `t_ac9d2588` mem0 / generic-JSON importers on the `MemorySourceBackend` seam.+- `t_845fe240` Staleness fast-path (`--if-stale`) for `clusters run`.+- `t_2e2e959f` Source distillation into atomic claims with block-level provenance.++## Out of scope++- Granola connector (`t_df66855f`) and ZeroEntropy provider (`t_8d49f059`) -+ distinct subsystems (connector family / embedding-provider family).+- Onboarding checklist (`t_84500f39`), LoCoMo eval (`t_8dabe2b0`) - unrelated themes.+- Applying the staleness gate to the `dream` learning pass: `dream` is not a+ clean input-mtime->output-mtime materialization (it reads log events and+ signals and already carries extensive content-hash no-op idempotency). Forcing+ an mtime gate onto it would be a misfit, not a completion. The gate is built+ as a reusable primitive; only the deterministic materialize path (`clusters+ run`) is wired in this release.+- Any model call in the deterministic core (unchanged invariant: the kernel+ calls no LLM; agents supply extractions/claims).++## Chosen approach++Variant 1 (compose on existing seams). See `variants.md`.++### Card 1 - Incremental per-item checkpointing++New module `src/core/brain/ingest/checkpoint.ts`, modeled on+`content-manifest.ts`:++- `IngestCheckpoint = { schema_version: 1, plan_id, source_dir, completed: string[], updated_at }`.+- `computePlanId(sourceDir, discoveredPaths)` - short SHA-256 hex over the+ canonical `sourceDir` and the sorted full discovered path set, so the id is+ stable across resume even as the remaining set shrinks.+- `checkpointPath(vault, planId)` -> `<vault>/.open-second-brain/ingest-checkpoints/<plan_id>.json`+ (a machine artifact, not curated memory - mirrors the manifest location).+- `readCheckpoint`, `recordCompleted` (union-as-you-go, atomic, byte-identity+ no-op skip), `clearCheckpoint`. A corrupt file or unknown `schema_version` is a+ hard error, never a silent reset (mirrors `readManifest`).+- Opt-out env `OSB_INGEST_NO_CHECKPOINT` (truthy) makes record/read inert -+ the deterministic-test escape hatch mirroring upstream's+ `GRAPHIFY_NO_INCREMENTAL_CACHE`.++Wiring:+- `planBatches` gains `opts.resume?: boolean`. When resuming it computes the+ stable `planId` from the full discovered set, reads the checkpoint, and+ excludes already-completed paths *before* content-hash classification - so a+ resumed plan never re-hashes completed items (the fast-path that keeps a+ large-vault resume near-free). The content manifest stays authoritative for+ everything the checkpoint does not cover. `BatchPlan` gains `planId` and+ `resumedCompleted` (count excluded via the checkpoint).+- `ingestSource` gains `opts.planId?: string`. On a successful ingest of a+ vault-file source, when a `planId` is set and checkpointing is enabled, it+ records the source path into that plan's checkpoint. The content manifest stays+ the authoritative final state; the checkpoint is plan-scoped progress.+- MCP `brain_ingest_batch_plan` gains `resume` (bool) and returns `plan_id` ++ `resumed_completed`; when a resumed plan comes back empty (fully drained) it+ clears the checkpoint (authoritative-final cleanup). `brain_ingest_source`+ gains an optional `plan_id`.+- CLI `brain batch-plan` gains `--resume` and prints the `plan_id`.++### Card 2 - mem0 / generic-JSON importers++The current seam is one-file-one-entry (`readdirSync` `*.md`, one+`parseMemoryFile(text)` -> one entry). mem0 and generic exports are one JSON+file holding many records, so the seam is generalized (not worked around):++- `MemorySourceBackend` gains `discoverMemoryFiles(dir): string[]` (default:+ sorted `*.md`, excluding `MEMORY.md`) and `parseMemoryEntries(text):+ MemorySourceParse[]` (0..N). The `claude` backend implements+ `discoverMemoryFiles` as today's `*.md` walk and `parseMemoryEntries` as a+ single-element wrap of `parseClaudeMemoryFile` - byte-identical output,+ regression-pinned.+- `import-claude-memory.ts` iterates `discoverMemoryFiles` then flattens+ `parseMemoryEntries`; the manifest/dedup key becomes `basename` for+ single-entry files and `basename#<slug>` for multi-entry files, so one JSON+ file mapping to many preferences is tracked per entry without collisions.+- New backends:+ - `agent-backend/mem0.ts` (id `mem0`): parses a mem0 export - a top-level+ array, or `{results|memories: [...]}`. Each record maps `memory|text|data` ->+ body, `id|name` -> name, `metadata.description` (or a truncated body) ->+ description. Structure-only; no natural-language gating.+ - `agent-backend/generic.ts` (id `generic`): a documented neutral schema - an+ array of `{ name, description, body }` objects (the catch-all dump format).+- Registry entries added; `--from <id>` / `--backend <id>` selector added to the+ `import-claude-memory` CLI verb (overrides the `memory_backend` config key);+ unknown id fails loudly with the registered list (existing `getMemoryBackend`).++### Card 3 - Staleness fast-path++New `src/core/brain/staleness.ts`:+- `newestMtimeMs(paths)` / `oldestMtimeMs(paths)` and+ `evaluateStaleness({inputs, outputs}): { fresh, newest_input_ms, oldest_output_ms }`.+ Fresh iff outputs is non-empty AND every output's mtime >= every input's mtime.++`clusters run` gains `--if-stale`: inputs = `listVaultPages(vault)`, outputs =+`Brain/clusters/*.md`. When fresh it prints a freshness-skip line, appends a+`communities` metric tagged `skipped: "fresh"`, and returns 0 without opening the+store or recomputing. Otherwise it runs as today.++### Card 4 - Source distillation++New `src/core/brain/distill/distill-source.ts`:+- `distillSource(vault, { sourcePath, claims, agent, now })` where `claims` is a+ non-empty list of `{ text, block? }`. Provider-agnostic: the agent supplies the+ atomic claims and the block ids; the core runs no model.+- Validates each claim has non-empty text; block ids are validated structurally+ via `parseWikilinkRich` (no vocabulary gating).+- Writes `Brain/distillations/dist-<slug>-<hash>.md`: frontmatter+ (`kind: brain-distillation`, `source_path`, `source_hash`, `provenance`,+ `created_at`/`updated_at`, `tags`), body = a `## Claims` section (one bullet per+ claim, each carrying `[[<source>#^<block>]]` when a block is given) plus the+ shared `## Sources` provenance section. Idempotent on the source identity hash;+ a byte-identical re-run is a no-op (mirrors `ingestSource`).+- New `BRAIN_DISTILLATIONS_REL` + `distillationPagePath(vault, slug)` in `paths.ts`.+- CLI verb `o2b brain distill` and MCP tool `brain_distill_source`.++## Design decisions++- **Content manifest stays authoritative; the checkpoint is plan-scoped+ progress.** Avoids two competing sources of truth for "is this source done."+- **`planId` keys on the full discovered set, not the remaining set**, so it is+ stable across resume.+- **The `claude` backend must stay byte-identical** through the seam widening -+ enforced by a regression test, matching the existing contract in+ `agent-backend/claude.ts`.+- **Staleness is not applied to `dream`** (justified under Out of scope).+- **Distillation composes existing primitives** (`parseWikilinkRich`,+ `provenance`) rather than re-deriving them.+- **All new machine artifacts live under `.open-second-brain/`**, all new curated+ pages under `Brain/`, consistent with existing layout.++## File changes++New:+- `src/core/brain/ingest/checkpoint.ts`+- `src/core/brain/agent-backend/mem0.ts`, `.../generic.ts`+- `src/core/brain/staleness.ts`+- `src/core/brain/distill/distill-source.ts`+- `src/cli/brain/verbs/distill.ts`+- `src/mcp/brain/distill-tools.ts` (or fold `brain_distill_source` into an existing group)+- tests mirroring each new module + CLI + MCP surface.++Modified:+- `src/core/brain/agent-backend/types.ts` (seam widening)+- `src/core/brain/agent-backend/claude.ts` (implement new methods, byte-identical)+- `src/core/brain/agent-backend/registry.ts` (register mem0, generic)+- `src/core/brain/import-claude-memory.ts` (collection-aware iteration + keys)+- `src/cli/brain/verbs/import-claude-memory.ts` (`--from`/`--backend`)+- `src/core/brain/ingest/batch-plan.ts` (`resume`, `planId`)+- `src/core/brain/ingest/ingest.ts` (`planId` completion recording)+- `src/mcp/brain/ingest-tools.ts` (`resume`, `plan_id`, `brain_ingest_source` `plan_id`)+- `src/cli/brain/verbs/batch-plan.ts` (`--resume`)+- `src/cli/brain/verbs/clusters.ts` (`--if-stale`)+- `src/core/brain/paths.ts` (distillations path)+- CLI/MCP registration for the new `distill` verb/tool.+- `CHANGELOG.md`, `package.json` (version bump), version mirrors via `sync-version.ts`.++## Risks++- **Seam widening regressions** on the `claude` import path - mitigated by a+ byte-identity regression test and by keeping `parseMemoryEntries` a thin wrap.+- **Manifest key change** for multi-entry files could collide - mitigated by the+ `basename#<slug>` scheme and the existing duplicate-prefId guard.+- **mtime coarseness** on fast filesystems could mark just-written outputs+ "fresh" against a same-second input change - mitigated by `>=` semantics that+ err toward recompute only when an input is strictly newer, and the gate is+ opt-in (`--if-stale`), never the default.+- **Distillation page proliferation** - mitigated by idempotency on the source+ identity hash (one source -> one page, rewritten in place).diff --git a/docs/brainstorm/ingestion-import-robustness/plan.md b/docs/brainstorm/ingestion-import-robustness/plan.mdnew file mode 100644index 00000000..406d7ac9--- /dev/null+++ b/docs/brainstorm/ingestion-import-robustness/plan.md@@ -0,0 +1,114 @@+# Implementation Plan - Ingestion & Import Robustness++TDD throughout: write the failing test first, watch it fail, then the minimal+code to pass. Keep `bun run validate` at zero warnings after every card.++---++## Card t_ba1fa5f6 - Incremental per-item checkpointing++**Files**+- New: `src/core/brain/ingest/checkpoint.ts`+- Modified: `src/core/brain/ingest/batch-plan.ts`, `src/core/brain/ingest/ingest.ts`,+ `src/mcp/brain/ingest-tools.ts`, `src/cli/brain/verbs/batch-plan.ts`+- Tests: `tests/core/brain/ingest/checkpoint.test.ts`,+ extend `tests/core/brain/ingest/batch-plan*.test.ts`, ingest + MCP tests.++**Acceptance**+- `recordCompleted` unions items across calls, writes atomically, and is a+ byte-identity no-op on a re-record of the same set.+- A corrupt checkpoint / unknown `schema_version` throws (no silent reset).+- `planBatches(..., { resume: true })` on a folder whose checkpoint records K of+ the N new/modified items returns a plan covering exactly the remaining N-K+ items and reports `resumedCompleted = K`; the `planId` is identical to the+ pre-interruption plan id.+- `OSB_INGEST_NO_CHECKPOINT=1` makes record/read inert (plan resumes nothing).+- `ingestSource(..., { planId })` records the ingested source into that plan's+ checkpoint on success; without `planId` no checkpoint is written.++**Depends on:** content-manifest (shipped).++---++## Card t_ac9d2588 - mem0 / generic-JSON importers++**Files**+- New: `src/core/brain/agent-backend/mem0.ts`, `src/core/brain/agent-backend/generic.ts`+- Modified: `src/core/brain/agent-backend/types.ts`,+ `src/core/brain/agent-backend/claude.ts`,+ `src/core/brain/agent-backend/registry.ts`,+ `src/core/brain/import-claude-memory.ts`,+ `src/cli/brain/verbs/import-claude-memory.ts`+- Tests: `tests/core/brain/agent-backend/mem0.test.ts`, `.../generic.test.ts`,+ claude byte-identity regression, orchestrator multi-entry test, CLI `--from` test.++**Acceptance**+- The `claude` backend's import output is byte-identical to the pre-change path+ for the existing orchestrator fixtures (regression pinned).+- `import --from mem0 --memory <mem0-export.json> --dry-run` plans one preference+ per mem0 record (array and `{results:[...]}` shapes both parse); non-mapping+ records skip with a clear reason.+- `import --from generic --memory <dump.json> --dry-run` plans one preference per+ `{name, description, body}` object.+- `getMemoryBackend("nope")` / `--from nope` fails loudly listing registered ids.+- Two entries in one JSON file that slugify to the same pref id: one applies, the+ other lands in `skipped` with the duplicate reason (existing guard holds).++**Depends on:** `MemorySourceBackend` seam (shipped) - widened here.++---++## Card t_845fe240 - Staleness fast-path (`--if-stale`)++**Files**+- New: `src/core/brain/staleness.ts`+- Modified: `src/cli/brain/verbs/clusters.ts`+- Tests: `tests/core/brain/staleness.test.ts`, `tests/cli/brain-clusters-if-stale.test.ts`.++**Acceptance**+- `evaluateStaleness` returns `fresh: false` when outputs is empty; `fresh: true`+ iff every output mtime >= every input mtime.+- `clusters run --if-stale` with cluster notes newer than every vault page+ no-ops: exit 0, no store open, a `communities` metric tagged `skipped: "fresh"`+ is appended, and no cluster note is rewritten.+- After touching a vault page so an input is newer than the outputs,+ `clusters run --if-stale` recomputes as normal.+- `clusters run` without `--if-stale` is unchanged.++**Depends on:** clusters materialize path (shipped).++---++## Card t_2e2e959f - Source distillation++**Files**+- New: `src/core/brain/distill/distill-source.ts`, `src/cli/brain/verbs/distill.ts`,+ MCP tool `brain_distill_source`+- Modified: `src/core/brain/paths.ts`, CLI + MCP registration+- Tests: `tests/core/brain/distill/distill-source.test.ts`,+ `tests/cli/brain-distill.test.ts`, `tests/mcp/distill-tool.test.ts`.++**Acceptance**+- `distillSource` with two claims (one carrying a block id) writes a+ `brain-distillation` page with two atomic-claim bullets; the block-bearing+ claim renders `[[<source>#^<block>]]`; the `source_hash` equals sha256 of the+ source bytes; a `## Sources` section links the source.+- Empty claims list, or a claim with empty text, is rejected (no page written).+- Re-running with identical input is a byte-identity no-op; re-running with a+ changed claim rewrites the same page in place (idempotent on source identity).+- `o2b brain distill` (CLI) and `brain_distill_source` (MCP) drive the same core+ and return the summary page path.++**Depends on:** `parseWikilinkRich`, `provenance` (shipped).++---++## Sequencing++1. Card t_ba1fa5f6 (checkpoint core -> batch-plan/ingest wiring -> MCP/CLI).+2. Card t_ac9d2588 (seam widen + claude regression -> mem0/generic -> CLI `--from`).+3. Card t_845fe240 (staleness primitive -> clusters `--if-stale`).+4. Card t_2e2e959f (distill core -> paths -> CLI/MCP).+5. Docs + version bump (`1.27.0`, minor) in the same branch/PR.++Each card is committed as its own logical unit with a conventional-commit message.diff --git a/docs/brainstorm/ingestion-import-robustness/variants.md b/docs/brainstorm/ingestion-import-robustness/variants.mdnew file mode 100644index 00000000..5093052e--- /dev/null+++ b/docs/brainstorm/ingestion-import-robustness/variants.md@@ -0,0 +1,90 @@+# Variants - Ingestion & Import Robustness++Scope: one coherent release hardening and extending Open Second Brain's+ingestion/import pipeline across four drivable leaf cards:++- `t_ba1fa5f6` (p4) Incremental per-item checkpointing for a resumable batch ingest.+- `t_ac9d2588` (p4) mem0 / generic-JSON memory-store importers on the `MemorySourceBackend` seam.+- `t_845fe240` (p3) Staleness fast-path (`--if-stale`) so a deterministic refresh no-ops when outputs are newer than inputs.+- `t_2e2e959f` (p3) Source distillation into citeable atomic claims with block-level provenance.++All four live in the same subsystem: `ingest/`, `agent-backend/`, the+freshness/materialize paths, and the provenance primitives. Excluded from scope+(distinct subsystems): `t_df66855f` Granola (connector family), `t_8d49f059`+ZeroEntropy (embedding-provider family), `t_84500f39` onboarding and+`t_8dabe2b0` LoCoMo (unrelated single-theme p4 cards).++---++## Variant 1 - Compose on existing seams (in-place extension)++**Approach.** Deliver each card by extending the seam the codebase already+exposes, adding at most one new module per capability and never a new+orchestration layer.++- Checkpointing: a standalone `ingest/checkpoint.ts` (mirrors `content-manifest.ts`+ file/format conventions); `planBatches` gains an optional `resume`, `ingestSource`+ gains an optional `planId` that records completion union-as-you-go as a side+ effect of the write it already performs. Content manifest stays authoritative.+- Importers: generalize `MemorySourceBackend` from one-file-one-entry to+ discover-files + parse-entries (0..N), keeping the `claude` backend+ byte-identical; add `mem0` and `generic` backend modules and register them;+ add a `--from` CLI selector.+- Staleness: a shared `staleness.ts` mtime gate; wire `--if-stale` into+ `clusters run` (the deterministic materialize path anchored by the card).+- Distillation: a `distill/` core that composes `parseWikilinkRich` (block ids),+ `provenance` (source sha256, Sources section), and the source-page idempotency+ idiom; add a CLI verb and an MCP tool.++**Trade-offs.** Matches every established repo pattern (registry seam, atomic+machine artifacts under `.open-second-brain/`, provider-agnostic model-free+core, idempotent page writes). Smallest blast radius, cleanest TDD, each card+independently testable. The `MemorySourceBackend` widening is the only shared+contract change and is covered by a claude-backend byte-identity regression.++**Complexity:** medium. **Risk:** low.++## Variant 2 - Unified ingestion-runner subsystem++**Approach.** Introduce a new `IngestionRunner` abstraction that owns a pass:+checkpoint state, staleness gating, source-backend plugins, and a distill stage+all become steps of one runner object the CLI/MCP drive.++**Trade-offs.** One conceptual surface for "run an ingestion pass"; future+sources/stages plug in uniformly. But it forces a large rewrite of `ingest.ts`,+`batch-plan.ts`, and the clusters/dream paths onto an abstraction none of them+needs today; couples four independent cards into one big-bang change; inflates+the diff and the review surface; and fights the codebase's deliberate+"one narrow module per capability, no speculative coupling" ethos (stated+verbatim in `agent-backend/types.ts`). High regression risk against the existing+no-op idempotency guarantees.++**Complexity:** large. **Risk:** high.++## Variant 3 - Staged independent mini-layers++**Approach.** Ship each card as a fully independent slice with its own module+graph and zero shared helpers, sequenced on the branch but not cross-composed+(e.g. distillation builds its own block-parse and provenance helpers rather than+reusing `parseWikilinkRich` / `provenance.ts`; staleness inlines its own mtime+logic in the clusters verb).++**Trade-offs.** Maximum isolation between cards, so a problem in one cannot touch+another. But it duplicates logic the repo already has (block parsing, provenance+rendering, mtime helpers), violating DRY, and leaves the release feeling like+four unrelated patches rather than one coherent subsystem hardening. Higher+long-term maintenance cost and more code to test for the same behavior.++**Complexity:** medium. **Risk:** medium (duplication-driven drift).++---++## Recommended: Variant 1++Variant 1 is the only option that honors the codebase's explicit design+principles - narrow modules on existing seams, model-free deterministic core,+atomic machine artifacts, idempotent writes - while keeping each card+independently test-driven. Variant 2's runner is speculative coupling the code+comments already warn against; Variant 3 re-implements primitives the repo+already ships. Variant 1 delivers the full scope (no half-fixes) at the lowest+regression risk against the existing no-op/idempotency contracts.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 22f4cdda..540519c0 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.26.1",+ "version": "1.27.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 0e392557..7749f695 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.26.1",+ "version": "1.27.0","private": false,"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.","keywords": [diff --git a/plugin.yaml b/plugin.yamlindex 1396b901..a2811751 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.26.1"+version: "1.27.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 052a185e..114de668 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.26.1",+ "version": "1.27.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 1396b901..a2811751 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.26.1"+version: "1.27.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 9e98eecb..1b2d285f 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.26.1"+version = "1.27.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex d044c071..44ac71a7 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -75,6 +75,7 @@ import {cmdBrainImportSession,cmdBrainForgetSource,cmdBrainBatchPlan,+ cmdBrainDistill,cmdBrainHandoff,cmdBrainIntention,cmdBrainProject,@@ -276,6 +277,8 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainForgetSource(rest);case "batch-plan":return await cmdBrainBatchPlan(rest);+ case "distill":+ return await cmdBrainDistill(rest);case "links":return await cmdBrainLinks(rest);case "profile":diff --git a/src/cli/brain/verbs/batch-plan.ts b/src/cli/brain/verbs/batch-plan.tsindex f3d46e42..031078cd 100644--- a/src/cli/brain/verbs/batch-plan.ts+++ b/src/cli/brain/verbs/batch-plan.ts@@ -31,12 +31,13 @@ export async function cmdBrainBatchPlan(argv: string[]): Promise<number> {vault: { type: "string" },"max-bytes": { type: "string" },"max-files": { type: "string" },+ resume: { type: "boolean" },json: { type: "boolean" },});const sourceDir = positional[0];if (!sourceDir) {return usageError(- "usage: o2b brain batch-plan <source-dir> [--max-bytes N] [--max-files N] [--json]",+ "usage: o2b brain batch-plan <source-dir> [--max-bytes N] [--max-files N] [--resume] [--json]",);}@@ -44,7 +45,8 @@ export async function cmdBrainBatchPlan(argv: string[]): Promise<number> {const { vault } = brainVerbContext(flags);const maxBatchBytes = parseCap(flags["max-bytes"], "--max-bytes", DEFAULT_MAX_BATCH_BYTES);const maxBatchFiles = parseCap(flags["max-files"], "--max-files", DEFAULT_MAX_BATCH_FILES);- const plan = planBatches(vault, sourceDir, { maxBatchBytes, maxBatchFiles });+ const resume = flags["resume"] === true;+ const plan = planBatches(vault, sourceDir, { maxBatchBytes, maxBatchFiles, resume });if (flags["json"]) {okJson({@@ -54,6 +56,8 @@ export async function cmdBrainBatchPlan(argv: string[]): Promise<number> {total_files: plan.totalFiles,total_bytes: plan.totalBytes,skipped: [...plan.skipped],+ plan_id: plan.planId,+ resumed_completed: plan.resumedCompleted,batches: plan.batches.map((b) => ({index: b.index,total_bytes: b.totalBytes,@@ -63,10 +67,11 @@ export async function cmdBrainBatchPlan(argv: string[]): Promise<number> {return 0;}- ok(`batch-plan: ${plan.sourceDir}`);+ ok(`batch-plan: ${plan.sourceDir} (plan ${plan.planId})`);ok(` ${plan.totalFiles} file(s) to ingest in ${plan.batches.length} batch(es); ` +- `${plan.skipped.length} unchanged skipped`,+ `${plan.skipped.length} unchanged skipped` ++ (plan.resumedCompleted > 0 ? `; ${plan.resumedCompleted} resumed (checkpointed)` : ""),);for (const b of plan.batches) {ok(` batch ${b.index}: ${b.files.length} file(s), ${b.totalBytes} byte(s)`);diff --git a/src/cli/brain/verbs/clusters.ts b/src/cli/brain/verbs/clusters.tsindex b940eb38..4baaa37f 100644--- a/src/cli/brain/verbs/clusters.ts+++ b/src/cli/brain/verbs/clusters.ts@@ -25,21 +25,44 @@ import {resolveSafeguardTimeoutMs,SafeguardTimeoutError,} from "../../../core/brain/safeguard.ts";+import { evaluateStaleness } from "../../../core/brain/staleness.ts";import { isoSecond } from "../../../core/brain/time.ts";import { resolveSearchConfig } from "../../../core/search/index.ts";import { Store } from "../../../core/search/store.ts";import { SearchError } from "../../../core/search/types.ts";-import { parseFrontmatter } from "../../../core/vault.ts";+import { listVaultPages, parseFrontmatter } from "../../../core/vault.ts";import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";const USAGE =- "usage: o2b brain clusters run [--min-size N] [--batch-size N] | list [--vault <path>] [--json]";+ "usage: o2b brain clusters run [--min-size N] [--batch-size N] [--if-stale] | list [--vault <path>] [--json]";++/** Vault-relative directory holding the materialized cluster notes. */+const CLUSTERS_DIR_REL = join("Brain", "clusters");++/**+ * Compare the materialized cluster notes against the vault's notes (their+ * inputs) for the `--if-stale` fast-path. Cluster notes are excluded from the+ * input set so an output never counts as its own input.+ */+function clustersStaleness(vault: string): ReturnType<typeof evaluateStaleness> {+ const clustersDir = join(vault, CLUSTERS_DIR_REL);+ const inputs = listVaultPages(vault)+ .map((p) => p.path)+ .filter((p) => !p.startsWith(clustersDir));+ const outputs = existsSync(clustersDir)+ ? readdirSync(clustersDir)+ .filter((f) => f.endsWith(".md"))+ .map((f) => join(clustersDir, f))+ : [];+ return evaluateStaleness(inputs, outputs);+}export async function cmdBrainClusters(argv: string[]): Promise<number> {const { flags, positional } = parse(argv, {vault: { type: "string" },"min-size": { type: "string" },"batch-size": { type: "string" },+ "if-stale": { type: "boolean" },json: { type: "boolean" },});const asJson = flags["json"] === true;@@ -97,6 +120,31 @@ export async function cmdBrainClusters(argv: string[]): Promise<number> {return 2;}+ // Staleness fast-path (t_845fe240): when the materialized cluster notes are+ // already newer than every input note, skip the recompute entirely. Opt-in+ // so the default behavior is unchanged; records a freshness-skip metric.+ if (flags["if-stale"] === true) {+ const staleness = clustersStaleness(vault);+ if (staleness.fresh) {+ try {+ appendMetric(vault, {+ surface: "communities",+ runAt: isoSecond(new Date()),+ payload: {+ skipped: "fresh",+ newest_input_ms: staleness.newestInputMs ?? 0,+ oldest_output_ms: staleness.oldestOutputMs ?? 0,+ },+ });+ } catch {+ // Metrics are observability, not correctness.+ }+ if (asJson) okJson({ communities: 0, skipped: "fresh" });+ else ok("clusters run: outputs already fresh - skipped (--if-stale)");+ return 0;+ }+ }+const searchConfig = resolveSearchConfig({ vault, configPath: config ?? undefined });let store: Store;try {diff --git a/src/cli/brain/verbs/distill.ts b/src/cli/brain/verbs/distill.tsnew file mode 100644index 00000000..af7d40a5--- /dev/null+++ b/src/cli/brain/verbs/distill.ts@@ -0,0 +1,105 @@+/**+ * `o2b brain distill <source> --claims <json>` (t_2e2e959f): condense a source+ * into atomic claims with block-level provenance.+ *+ * Provider-agnostic: the agent supplies the atomic claims (and optional source+ * block ids) as JSON - a `[{ "text": "...", "block": "^abc" }]` array via+ * `--claims` or `--claims-file`. OSB validates them and writes one idempotent+ * distillation page per source. No model, no extraction here.+ *+ * Exit codes: 0 on success, 1 on an operational failure, 2 on usage errors.+ */++import { readFileSync } from "node:fs";++import {+ distillSource,+ DistillValidationError,+ normalizeClaim,+ type DistillClaim,+} from "../../../core/brain/distill/distill-source.ts";+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";++const USAGE =+ "usage: o2b brain distill <source> (--claims <json> | --claims-file <path>) [--vault <path>] [--json]";++/** Parse and structurally validate the claims JSON into DistillClaim[]. */+function parseClaims(raw: string): DistillClaim[] {+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ throw new Error("claims must be valid JSON");+ }+ const arr = Array.isArray(parsed)+ ? parsed+ : parsed !== null &&+ typeof parsed === "object" &&+ Array.isArray((parsed as { claims?: unknown }).claims)+ ? (parsed as { claims: unknown[] }).claims+ : null;+ if (arr === null) {+ throw new Error("claims must be a JSON array of { text, block? } objects");+ }+ return arr.map((item, i) => {+ if (item === null || typeof item !== "object" || Array.isArray(item)) {+ throw new Error(`claim ${i} must be an object with a text field`);+ }+ return normalizeClaim(item as Record<string, unknown>);+ });+}++export async function cmdBrainDistill(argv: string[]): Promise<number> {+ const { flags, positional } = parse(argv, {+ vault: { type: "string" },+ agent: { type: "string" },+ claims: { type: "string" },+ "claims-file": { type: "string" },+ json: { type: "boolean" },+ });+ const source = positional[0];+ // Usage errors exit 2 (the command's documented contract), distinct from the+ // operational exit 1 the catch below returns.+ if (!source) {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }+ if (typeof flags["claims"] !== "string" && typeof flags["claims-file"] !== "string") {+ process.stderr.write(`${USAGE}\n`);+ return 2;+ }++ try {+ const { config, vault } = brainVerbContext(flags);+ // Read the claims source inside the try so a missing --claims-file is a+ // clean error, not an uncaught throw.+ const claimsRaw =+ typeof flags["claims"] === "string"+ ? (flags["claims"] as string)+ : readFileSync(flags["claims-file"] as string, "utf8");+ const claims = parseClaims(claimsRaw);+ const res = distillSource(+ vault,+ { sourcePath: source, claims },+ { agent: resolveBrainAgent(flags, config), now: new Date() },+ );+ if (flags["json"]) {+ okJson({+ distillation_path: res.distillationPath,+ created: res.created,+ claim_count: res.claimCount,+ source_hash: res.sourceHash,+ });+ return 0;+ }+ ok(+ `distilled ${res.claimCount} claim(s) -> ${res.distillationPath}${res.created ? "" : " (updated)"}`,+ );+ return 0;+ } catch (err) {+ if (err instanceof DistillValidationError) {+ return fail(`distill: ${err.message}`);+ }+ return fail(`distill failed: ${(err as Error).message ?? err}`);+ }+}diff --git a/src/cli/brain/verbs/import-claude-memory.ts b/src/cli/brain/verbs/import-claude-memory.tsindex 7529ec97..7056d58c 100644--- a/src/cli/brain/verbs/import-claude-memory.ts+++ b/src/cli/brain/verbs/import-claude-memory.ts@@ -1,6 +1,9 @@import { defaultConfigPath } from "../../../core/config.ts";import { importClaudeMemory, ConflictsError } from "../../../core/brain/import-claude-memory.ts";-import { resolveMemoryBackend } from "../../../core/brain/agent-backend/registry.ts";+import {+ getMemoryBackend,+ resolveMemoryBackend,+} from "../../../core/brain/agent-backend/registry.ts";import { resolveBrainVault } from "../helpers.ts";export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number> {@@ -13,6 +16,7 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<numberlet yes = false;let asJson = false;let vaultFlag: string | undefined;+ let backendId: string | undefined;const consumeValue = (flag: string, next: string | undefined): string | null => {if (next === undefined || next.startsWith("--")) {@@ -36,6 +40,12 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<numbermemory = v;continue;}+ if (a === "--from" || a === "--backend") {+ const v = consumeValue(a, argv[++i]);+ if (v === null) return 2;+ backendId = v;+ continue;+ }if (a === "--dry-run") {if (modeSet && mode !== "dry-run") {process.stderr.write(@@ -82,13 +92,16 @@ export async function cmdBrainImportClaudeMemory(argv: string[]): Promise<number}const vault = resolveBrainVault(vaultFlag, config);- // t_53f9f67f: the memory-format backend is config-selected- // (`memory_backend`, default claude) - unknown ids fail loudly here,- // before any filesystem work.- const backend = resolveMemoryBackend(config);- const memDir = memory ?? backend.discoverMemoryDir(vault);try {+ // t_53f9f67f/t_ac9d2588: the memory-format backend is `--from`-selected,+ // else config-selected (`memory_backend`, default claude). Unknown ids fail+ // loudly with the registered list, before any filesystem work. mem0/generic+ // have no default location, so their `discoverMemoryDir` throws unless+ // `--memory` was given - caught here, not crashed.+ const backend =+ backendId !== undefined ? getMemoryBackend(backendId) : resolveMemoryBackend(config);+ const memDir = memory ?? backend.discoverMemoryDir(vault);const res = importClaudeMemory({vault,memoryDir: memDir,diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 65d84151..985a3661 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -62,6 +62,7 @@ export { cmdBrainProject } from "./project.ts";export { cmdBrainSource } from "./source.ts";export { cmdBrainForgetSource } from "./forget-source.ts";export { cmdBrainBatchPlan } from "./batch-plan.ts";+export { cmdBrainDistill } from "./distill.ts";export { cmdBrainLinks } from "./links.ts";export { cmdBrainProfile } from "./profile.ts";export { cmdBrainSgrep } from "./sgrep.ts";diff --git a/src/core/brain/agent-backend/claude.ts b/src/core/brain/agent-backend/claude.tsindex 09e9aad8..6596df4a 100644--- a/src/core/brain/agent-backend/claude.ts+++ b/src/core/brain/agent-backend/claude.ts@@ -8,6 +8,8 @@* modules directly (regression-tested).*/+import { readdirSync } from "node:fs";+import { defaultMemoryDir } from "../claude-memory-paths.ts";import { parseClaudeMemoryFile } from "../claude-memory-parser.ts";import { renderPreferenceFromMemory, slugifyMemoryName } from "../claude-memory-render.ts";@@ -19,8 +21,17 @@ export const claudeMemoryBackend: MemorySourceBackend = Object.freeze({discoverMemoryDir(vault: string): string {return defaultMemoryDir(vault);},- parseMemoryFile(text: string): MemorySourceParse {- return parseClaudeMemoryFile(text);+ discoverMemoryFiles(dir: string): string[] {+ // One memory file per `.md`, minus the human-facing index. Sorted for a+ // deterministic import order - identical to the walk the core used before+ // the seam widened.+ return readdirSync(dir)+ .toSorted()+ .filter((name) => name !== "MEMORY.md" && name.endsWith(".md"));+ },+ parseMemoryEntries(text: string): MemorySourceParse[] {+ // A Claude memory file is exactly one entry (feedback or skip).+ return [parseClaudeMemoryFile(text)];},renderPreference(input: MemoryRenderInput): string {return renderPreferenceFromMemory(input);diff --git a/src/core/brain/agent-backend/generic.ts b/src/core/brain/agent-backend/generic.tsnew file mode 100644index 00000000..a85c336f--- /dev/null+++ b/src/core/brain/agent-backend/generic.ts@@ -0,0 +1,33 @@+/**+ * Generic JSON memory-store backend (Ingestion & Import Robustness suite,+ * t_ac9d2588).+ *+ * The catch-all importer for any memory store that can emit a neutral JSON+ * dump. The documented schema is a list of memory objects - a top-level array,+ * or an object with the list under `memories` / `entries` - where each object+ * carries a `body` (or `text` / `memory`), an optional `name`, and an optional+ * `description`:+ *+ * [ { "name": "no-shouting", "description": "Tone rule", "body": "Never..." } ]+ *+ * Missing name/description fall back to a body-derived value, so a minimal+ * `[{ "body": "..." }]` still imports. Built from the shared JSON-backend+ * factory (see {@link makeJsonBackend}); rendering and slugging reuse the+ * Claude-memory functions for a uniform Brain preference format.+ *+ * Pointed at a single dump file via `--memory`; no per-vault default location.+ */++import { makeJsonBackend } from "./json-source.ts";+import type { MemorySourceBackend } from "./types.ts";++export const genericMemoryBackend: MemorySourceBackend = makeJsonBackend({+ id: "generic",+ label: "Generic JSON",+ collectionKeys: ["memories", "entries", "data"],+ bodyKeys: ["body", "text", "memory", "content"],+ errorPrefix: "generic dump",+ recordNoun: "generic record",+ noDefaultDirMessage:+ "the generic backend has no default memory location - pass the dump with --memory <dump.json>",+});diff --git a/src/core/brain/agent-backend/json-source.ts b/src/core/brain/agent-backend/json-source.tsnew file mode 100644index 00000000..e0dacdf6--- /dev/null+++ b/src/core/brain/agent-backend/json-source.ts@@ -0,0 +1,169 @@+/**+ * Shared helpers for JSON memory-store backends (Ingestion & Import Robustness+ * suite, t_ac9d2588).+ *+ * mem0 and the generic catch-all both import ONE JSON export file that holds+ * MANY memory records, unlike the Claude Code backend's one-file-one-entry+ * layout. These helpers centralize the two concerns those backends share:+ * pulling the record array out of an export (a top-level array, or an object+ * keyed by a known collection field), and coercing one record into the+ * feedback/skip {@link MemorySourceParse} the import core already understands.+ *+ * Language-agnostic: field selection is structural (JSON keys), and no+ * natural-language vocabulary is inspected. A record with no usable text is+ * skipped with a reason, never fabricated.+ */++import { createHash } from "node:crypto";+import { readdirSync } from "node:fs";++import { renderPreferenceFromMemory, slugifyMemoryName } from "../claude-memory-render.ts";+import type { MemoryRenderInput, MemorySourceBackend, MemorySourceParse } from "./types.ts";++/** Cap for a description synthesized from a record's body. */+const DERIVED_DESCRIPTION_MAX = 200;++/**+ * Pull the record array out of a JSON export. Accepts a top-level array or an+ * object whose value at one of `collectionKeys` is an array. Returns the raw+ * items (each still `unknown` - the backend coerces per record) or a structural+ * error string that becomes a single skip entry.+ */+export function readJsonItems(+ text: string,+ collectionKeys: readonly string[],+): { items: readonly unknown[] } | { error: string } {+ let parsed: unknown;+ try {+ parsed = JSON.parse(text);+ } catch {+ return { error: "not valid JSON" };+ }+ if (Array.isArray(parsed)) return { items: parsed };+ if (parsed !== null && typeof parsed === "object") {+ const obj = parsed as Record<string, unknown>;+ for (const key of collectionKeys) {+ const value = obj[key];+ if (Array.isArray(value)) return { items: value };+ }+ }+ return {+ error: `expected a JSON array or an object with an array at one of: ${collectionKeys.join(", ")}`,+ };+}++/** Trimmed string value, or "" for any non-string. */+export function asTrimmedString(value: unknown): string {+ return typeof value === "string" ? value.trim() : "";+}++/** First non-empty trimmed string found at `keys` in `record`. */+export function firstString(record: Record<string, unknown>, keys: readonly string[]): string {+ for (const key of keys) {+ const s = asTrimmedString(record[key]);+ if (s) return s;+ }+ return "";+}++/** A record's `metadata.<field>` when metadata is an object, else "". */+export function metadataString(record: Record<string, unknown>, field: string): string {+ const meta = record["metadata"];+ if (meta !== null && typeof meta === "object" && !Array.isArray(meta)) {+ return asTrimmedString((meta as Record<string, unknown>)[field]);+ }+ return "";+}++/** First non-empty line of `body`, capped - a readable description fallback. */+export function deriveDescription(body: string): string {+ const line = body+ .split("\n")+ .map((l) => l.trim())+ .find((l) => l.length > 0);+ const base = line ?? body.trim();+ return base.length > DERIVED_DESCRIPTION_MAX+ ? `${base.slice(0, DERIVED_DESCRIPTION_MAX - 1).trimEnd()}…`+ : base;+}++/**+ * Build a feedback (or skip) parse from the three fields every source reduces+ * to. Body is required; a missing name or description falls back to a+ * body-derived value so a minimal record (mem0's `{memory: "..."}`) still+ * imports. The sha256 is over the trimmed body, matching the Claude parser.+ */+export function buildFeedbackEntry(input: {+ name: string;+ description: string;+ body: string;+}): MemorySourceParse {+ const body = input.body.trim();+ if (!body) return { kind: "skip", skipReason: "record has no memory text" };+ const name = input.name.trim() || deriveDescription(body);+ if (!name) return { kind: "skip", skipReason: "record has no derivable name" };+ const description = input.description.trim() || deriveDescription(body);+ const bodySha256 = createHash("sha256").update(body).digest("hex");+ return { kind: "feedback", name, description, body, bodySha256 };+}++/** Config for a JSON memory-store backend built by {@link makeJsonBackend}. */+export interface JsonBackendConfig {+ /** Stable selector for the `memory_backend` config key / `--from`. */+ readonly id: string;+ /** Human-readable name for messages. */+ readonly label: string;+ /** Keys under which the export nests its record array. */+ readonly collectionKeys: readonly string[];+ /** Record keys tried in order for the memory body text. */+ readonly bodyKeys: readonly string[];+ /** Prefix for a whole-file parse error (e.g. `mem0 export`). */+ readonly errorPrefix: string;+ /** Noun for a per-record skip (e.g. `mem0 record`). */+ readonly recordNoun: string;+ /** Message thrown when no `--memory` was given (no default location). */+ readonly noDefaultDirMessage: string;+}++/**+ * Build a JSON memory-store backend from a small config. mem0 and the generic+ * catch-all differ only in their id/label, which keys hold the record array and+ * the body text, and their diagnostic wording - everything else (name/+ * description selection, `.json` discovery, the shared Claude render/slug, and+ * the no-default-location guard) is identical, so it lives here once.+ */+export function makeJsonBackend(cfg: JsonBackendConfig): MemorySourceBackend {+ return Object.freeze({+ id: cfg.id,+ label: cfg.label,+ discoverMemoryDir(_vault: string): string {+ throw new Error(cfg.noDefaultDirMessage);+ },+ discoverMemoryFiles(dir: string): string[] {+ return readdirSync(dir)+ .toSorted()+ .filter((name) => name.toLowerCase().endsWith(".json"));+ },+ parseMemoryEntries(text: string): MemorySourceParse[] {+ const res = readJsonItems(text, cfg.collectionKeys);+ if ("error" in res) return [{ kind: "skip", skipReason: `${cfg.errorPrefix} ${res.error}` }];+ return res.items.map((item) => {+ if (item === null || typeof item !== "object" || Array.isArray(item)) {+ return { kind: "skip", skipReason: `${cfg.recordNoun} is not an object` };+ }+ const rec = item as Record<string, unknown>;+ return buildFeedbackEntry({+ name: firstString(rec, ["name", "title", "id"]),+ description: firstString(rec, ["description"]) || metadataString(rec, "description"),+ body: firstString(rec, cfg.bodyKeys),+ });+ });+ },+ renderPreference(input: MemoryRenderInput): string {+ return renderPreferenceFromMemory(input);+ },+ slugifyName(name: string): string {+ return slugifyMemoryName(name);+ },+ });+}diff --git a/src/core/brain/agent-backend/mem0.ts b/src/core/brain/agent-backend/mem0.tsnew file mode 100644index 00000000..7f440b41--- /dev/null+++ b/src/core/brain/agent-backend/mem0.ts@@ -0,0 +1,29 @@+/**+ * mem0 memory-store backend (Ingestion & Import Robustness suite, t_ac9d2588).+ *+ * Imports a mem0 export - a popular agent-memory store - into Brain+ * preferences. mem0's `get_all` / export shape is a list of memory records,+ * delivered either as a top-level JSON array or under a `results` / `memories`+ * key. Each record's memory text becomes a preference body; its id / name and+ * metadata description fill the frontmatter. Built from the shared JSON-backend+ * factory (see {@link makeJsonBackend}); rendering and slugging reuse the+ * Claude-memory functions, so an imported mem0 memory is a first-class Brain+ * preference indistinguishable in format from any other.+ *+ * Pointed at a single export file via `--memory`; it has no per-vault default+ * location, so `discoverMemoryDir` fails loudly rather than guessing.+ */++import { makeJsonBackend } from "./json-source.ts";+import type { MemorySourceBackend } from "./types.ts";++export const mem0MemoryBackend: MemorySourceBackend = makeJsonBackend({+ id: "mem0",+ label: "mem0",+ collectionKeys: ["results", "memories", "data"],+ bodyKeys: ["memory", "text", "data", "content"],+ errorPrefix: "mem0 export",+ recordNoun: "mem0 record",+ noDefaultDirMessage:+ "the mem0 backend has no default memory location - pass the export with --memory <mem0-export.json>",+});diff --git a/src/core/brain/agent-backend/registry.ts b/src/core/brain/agent-backend/registry.tsindex ccfc9d35..20d5720b 100644--- a/src/core/brain/agent-backend/registry.ts+++ b/src/core/brain/agent-backend/registry.ts@@ -9,12 +9,16 @@import { discoverConfig } from "../../config.ts";import { claudeMemoryBackend } from "./claude.ts";+import { genericMemoryBackend } from "./generic.ts";+import { mem0MemoryBackend } from "./mem0.ts";import type { MemorySourceBackend } from "./types.ts";export const DEFAULT_MEMORY_BACKEND_ID = "claude";const REGISTRY: ReadonlyMap<string, MemorySourceBackend> = new Map([[claudeMemoryBackend.id, claudeMemoryBackend],+ [mem0MemoryBackend.id, mem0MemoryBackend],+ [genericMemoryBackend.id, genericMemoryBackend],]);/** Registered backends in registration order. */diff --git a/src/core/brain/agent-backend/types.ts b/src/core/brain/agent-backend/types.tsindex f0e6ca01..b5ae7df5 100644--- a/src/core/brain/agent-backend/types.ts+++ b/src/core/brain/agent-backend/types.ts@@ -49,8 +49,21 @@ export interface MemorySourceBackend {readonly label: string;/** Default memory directory for a vault under this runtime. */discoverMemoryDir(vault: string): string;- /** Parse one memory file's text. */- parseMemoryFile(text: string): MemorySourceParse;+ /**+ * The basenames under `dir` this backend parses, in deterministic order.+ * A per-file backend (Claude Code) returns its `*.md` files minus the+ * index; a collection backend (mem0 / generic JSON) returns its `*.json`+ * export files. The import core reads each returned basename and feeds its+ * text to {@link parseMemoryEntries}.+ */+ discoverMemoryFiles(dir: string): string[];+ /**+ * Parse one memory file's text into 0..N entries. A per-file format yields+ * exactly one entry (feedback or skip); a collection format (a JSON export+ * holding many memories) yields one entry per record. The single seam that+ * lets one source file map to many Brain preferences.+ */+ parseMemoryEntries(text: string): MemorySourceParse[];/** Render a parsed entry as a Brain preference markdown body. */renderPreference(input: MemoryRenderInput): string;/** Deterministic name -> preference-slug transform. */diff --git a/src/core/brain/distill/distill-source.ts b/src/core/brain/distill/distill-source.tsnew file mode 100644index 00000000..a0fee166--- /dev/null+++ b/src/core/brain/distill/distill-source.ts@@ -0,0 +1,207 @@+/**+ * Source distillation (Ingestion & Import Robustness suite, t_2e2e959f).+ *+ * Condenses one source into discrete atomic claims, each carrying provenance+ * back to the exact block it was drawn from. Composes the primitives OSB+ * already has - block-id wikilinks (`[[Note#^abc]]`), source sha256 provenance,+ * and the idempotent per-source page write - rather than building extraction+ * from scratch.+ *+ * Provider-agnostic: the calling agent supplies the atomic claims and their+ * block references; this core runs NO model. It validates the claims+ * structurally (non-empty text, well-formed block ids), stamps a content+ * sha256 the verifier can reproduce from the source file, and writes one+ * distillation page per source identity, rewritten in place on re-distill+ * (never duplicated). A byte-identical re-run is inert.+ *+ * Language-agnostic: block-id validation is structural (the Obsidian `^id`+ * grammar), never over natural-language vocabulary.+ */++import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join, relative } from "node:path";++import type { FrontmatterMap } from "../../types.ts";+import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { canonicalNotePath } from "../../path-safety.ts";+import { formatFrontmatter, parseFrontmatter, slugify } from "../../vault.ts";+import { distillationPagePath } from "../paths.ts";+import {+ renderProvenanceSection,+ sourceIdentityHash,+ type Provenance,+} from "../provenance/provenance.ts";+import { isoSecond } from "../time.ts";++/** Frontmatter `kind:` marker of a distillation page. */+export const BRAIN_DISTILLATION_KIND = "brain-distillation";++/** Hash recorded for a source whose bytes are not on disk (a URL identity). */+const MISSING_SOURCE_HASH = "missing";++/** Structural grammar of an Obsidian block id (the text after `#^`). */+const BLOCK_ID_RE = /^[A-Za-z0-9][A-Za-z0-9-]*$/;++/** One atomic claim distilled from the source, with an optional block ref. */+export interface DistillClaim {+ /** The atomic claim text. */+ readonly text: string;+ /** Block id in the source the claim was drawn from (the `^abc` sigil, id only). */+ readonly block?: string;+}++/**+ * Normalize one agent-supplied claim record into a {@link DistillClaim}. Shared+ * by the CLI and MCP surfaces so both accept the same shape: a `text` string and+ * an optional `block` id (a leading `^` sigil is stripped; an empty block is+ * dropped). Structural validation of the block id happens later, in `validate`.+ */+export function normalizeClaim(rec: Record<string, unknown>): DistillClaim {+ const text = typeof rec["text"] === "string" ? rec["text"] : "";+ const block = typeof rec["block"] === "string" ? rec["block"].replace(/^\^/, "") : undefined;+ return { text, ...(block !== undefined && block.length > 0 ? { block } : {}) };+}++export interface DistillSourceInput {+ /** Source identity: a vault-relative path or a URL. Canonicalized on write. */+ readonly sourcePath: string;+ /** The atomic claims the agent distilled from the source (non-empty). */+ readonly claims: readonly DistillClaim[];+}++export interface DistillSourceOptions {+ readonly agent: string;+ readonly now: Date;+}++export interface DistillSourceResult {+ /** Vault-relative path of the distillation page. */+ readonly distillationPath: string;+ /** `false` when the page already existed and was rewritten. */+ readonly created: boolean;+ /** Number of atomic claims written. */+ readonly claimCount: number;+ /** sha256 over the source bytes, or `missing` when the source has no bytes. */+ readonly sourceHash: string;+}++/** A distillation failed structural validation; nothing was written. */+export class DistillValidationError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "DistillValidationError";+ }+}++function validate(input: DistillSourceInput): void {+ if (input.claims.length === 0) {+ throw new DistillValidationError("distillation requires at least one claim");+ }+ input.claims.forEach((claim, i) => {+ if (claim.text.trim().length === 0) {+ throw new DistillValidationError(`claim ${i} has empty text`);+ }+ if (claim.block !== undefined && !BLOCK_ID_RE.test(claim.block)) {+ throw new DistillValidationError(+ `claim ${i} has a malformed block id ${JSON.stringify(claim.block)} - expected an Obsidian block id (alphanumerics and hyphens)`,+ );+ }+ });+}++/** Render one claim bullet, citing its source block when the claim carries one. */+function renderClaim(claim: DistillClaim, canonicalSource: string): string {+ const text = claim.text.trim();+ return claim.block !== undefined+ ? `- ${text} ([[${canonicalSource}#^${claim.block}]])`+ : `- ${text}`;+}++/**+ * Distill a source into atomic claims. Validates the claims (throwing+ * {@link DistillValidationError} with no write on failure), then writes a+ * distillation page listing each claim with its block-level citation and a+ * `## Sources` provenance section. Idempotent on the source identity.+ */+export function distillSource(+ vault: string,+ input: DistillSourceInput,+ opts: DistillSourceOptions,+): DistillSourceResult {+ validate(input);++ const canonicalSource = canonicalNotePath(input.sourcePath);+ const sourceLink = `[[${canonicalSource}]]`;+ const provenance: Provenance = { level: "stated", sources: [sourceLink], premises: [] };++ // Content sha256 the verifier can reproduce from the file (provenance the+ // block citations hang off). URL / identity-only sources have no bytes.+ const absSource = join(vault, canonicalSource);+ const sourceHash = existsSync(absSource)+ ? createHash("sha256").update(readFileSync(absSource)).digest("hex")+ : MISSING_SOURCE_HASH;++ const idHash = sourceIdentityHash([canonicalSource]);+ const absPath = distillationPagePath(vault, `${slugify(canonicalSource)}-${idHash.slice(0, 12)}`);+ const existed = existsSync(absPath);+ const stamp = isoSecond(opts.now);+ const createdAt = existed ? readCreatedAt(absPath, stamp) : stamp;+ const priorUpdatedAt = existed ? readUpdatedAt(absPath, stamp) : stamp;++ const claimsSection = [+ "## Claims",+ "",+ ...input.claims.map((c) => renderClaim(c, canonicalSource)),+ ].join("\n");+ const body = [claimsSection, renderProvenanceSection(provenance)]+ .filter((section) => section.length > 0)+ .join("\n\n");++ const buildContents = (updatedAt: string): string => {+ const meta: FrontmatterMap = {+ kind: BRAIN_DISTILLATION_KIND,+ source_path: canonicalSource,+ source_hash: sourceHash,+ provenance: provenance.level,+ agent: opts.agent,+ claim_count: input.claims.length,+ created_at: createdAt,+ updated_at: updatedAt,+ tags: ["brain", "brain/distillation"],+ };+ return formatFrontmatter(meta, body);+ };++ // Idempotent no-op: if the page would be byte-identical with its EXISTING+ // updated_at preserved, nothing meaningful changed - skip the write and leave+ // updated_at (and the mtime) alone. A real content change bumps updated_at.+ const onDisk = existed ? readFileSync(absPath, "utf8") : null;+ if (onDisk === null || onDisk !== buildContents(priorUpdatedAt)) {+ mkdirSync(dirname(absPath), { recursive: true });+ atomicWriteFileSync(absPath, buildContents(stamp));+ }++ return {+ distillationPath: canonicalNotePath(relative(vault, absPath)),+ created: !existed,+ claimCount: input.claims.length,+ sourceHash,+ };+}++/** Read a stable `created_at` from an existing distillation page, else fall back. */+function readCreatedAt(absPath: string, fallback: string): string {+ return readStampField(absPath, "created_at", fallback);+}++/** Read the existing `updated_at` so an unchanged re-run preserves it. */+function readUpdatedAt(absPath: string, fallback: string): string {+ return readStampField(absPath, "updated_at", fallback);+}++function readStampField(absPath: string, field: string, fallback: string): string {+ const [meta] = parseFrontmatter(absPath);+ const value = meta[field];+ return typeof value === "string" && value.length > 0 ? value : fallback;+}diff --git a/src/core/brain/import-claude-memory.ts b/src/core/brain/import-claude-memory.tsindex b01417ba..89346c4d 100644--- a/src/core/brain/import-claude-memory.ts+++ b/src/core/brain/import-claude-memory.ts@@ -1,5 +1,5 @@-import { existsSync, mkdirSync, readFileSync, readdirSync } from "node:fs";-import { join } from "node:path";+import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";+import { basename, dirname, join } from "node:path";import { atomicWriteFileSync } from "../fs-atomic.ts";import { appendLogEvent } from "./log.ts";@@ -103,48 +103,65 @@ export function importClaudeMemory(opts: ImportClaudeMemoryOpts): ImportClaudeMe// any duplicate into the skipped list with a clear reason.const seenPrefIds = new Map<string, string>();- for (const name of readdirSync(opts.memoryDir).toSorted()) {- if (name === "MEMORY.md") continue;- if (!name.endsWith(".md")) continue;- const text = readFileSync(join(opts.memoryDir, name), "utf8");- const parsed = backend.parseMemoryFile(text);- if (parsed.kind === "skip") {- skipped.push({ basename: name, reason: parsed.skipReason });- continue;- }- const slug = backend.slugifyName(parsed.name);- const prefId = `pref-${slug}`;- const dupOf = seenPrefIds.get(prefId);- if (dupOf) {- skipped.push({- basename: name,- reason: `duplicate target preference id ${prefId} (also produced by ${dupOf}); rename the memory entry to disambiguate`,+ // A backend either walks a directory of per-memory files (Claude Code) or is+ // pointed at a single export file that holds many records (mem0 / generic+ // JSON). When `memoryDir` resolves to a file, that file is the sole input and+ // its extension is trusted (the operator chose it); otherwise the backend's+ // own `discoverMemoryFiles` selects the ingestible basenames.+ const memIsFile = statSync(opts.memoryDir).isFile();+ const baseDir = memIsFile ? dirname(opts.memoryDir) : opts.memoryDir;+ const files = memIsFile+ ? [basename(opts.memoryDir)]+ : backend.discoverMemoryFiles(opts.memoryDir);++ for (const name of files) {+ const text = readFileSync(join(baseDir, name), "utf8");+ const entries = backend.parseMemoryEntries(text);+ const multi = entries.length > 1;+ entries.forEach((parsed, idx) => {+ // The manifest/dedup key is the source basename for a single-entry file+ // (byte-identical to the pre-seam Claude behavior) and `basename#slug`+ // for one of many entries in a collection file, so a single JSON export+ // maps to many preferences without colliding manifest rows.+ if (parsed.kind === "skip") {+ skipped.push({ basename: multi ? `${name}#${idx}` : name, reason: parsed.skipReason });+ return;+ }+ const slug = backend.slugifyName(parsed.name);+ const prefId = `pref-${slug}`;+ const entryKey = multi ? `${name}#${slug}` : name;+ const dupOf = seenPrefIds.get(prefId);+ if (dupOf) {+ skipped.push({+ basename: entryKey,+ reason: `duplicate target preference id ${prefId} (also produced by ${dupOf}); rename the memory entry to disambiguate`,+ });+ return;+ }+ seenPrefIds.set(prefId, entryKey);+ // preferencePath adds pref- prefix itself, so pass just the slug+ const prefFile = preferencePath(opts.vault, slug);+ const manifestEntry = manifest.imports[entryKey];+ const plan = planAction({+ basename: entryKey,+ prefId,+ sha256: parsed.bodySha256,+ inManifest: manifestEntry ? { sha256: manifestEntry.sha256 } : null,+ prefExists: existsSync(prefFile),});- continue;- }- seenPrefIds.set(prefId, name);- // preferencePath adds pref- prefix itself, so pass just the slug- const prefFile = preferencePath(opts.vault, slug);- const manifestEntry = manifest.imports[name];- const plan = planAction({- basename: name,- prefId,- sha256: parsed.bodySha256,- inManifest: manifestEntry ? { sha256: manifestEntry.sha256 } : null,- prefExists: existsSync(prefFile),+ plans.push(plan);+ if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {+ const body = backend.renderPreference({+ name: parsed.name,+ description: parsed.description,+ body: parsed.body,+ memoryPath: join(baseDir, name),+ importedAt,+ bodySha256: parsed.bodySha256,+ });+ filesToWrite.push({ plan, body, sha256: parsed.bodySha256, slug });+ }});- plans.push(plan);- if (plan.action === "CREATE" || plan.action === "RECREATE" || plan.action === "UPDATE") {- const body = backend.renderPreference({- name: parsed.name,- description: parsed.description,- body: parsed.body,- memoryPath: join(opts.memoryDir, name),- importedAt,- bodySha256: parsed.bodySha256,- });- filesToWrite.push({ plan, body, sha256: parsed.bodySha256, slug });- }}const conflicts = plans.filter((p) => p.action === "CONFLICT");diff --git a/src/core/brain/ingest/batch-plan.ts b/src/core/brain/ingest/batch-plan.tsindex 97f2e379..7b7273c1 100644--- a/src/core/brain/ingest/batch-plan.ts+++ b/src/core/brain/ingest/batch-plan.ts@@ -27,6 +27,7 @@ import { existsSync, readdirSync, statSync } from "node:fs";import { join, posix, relative } from "node:path";import { canonicalNotePath, ensureInsideVault } from "../../path-safety.ts";+import { computePlanId, readCheckpoint } from "./checkpoint.ts";import { classifyPaths, readManifest } from "./content-manifest.ts";/**@@ -54,6 +55,13 @@ export interface BatchPlanOptions {* {@link DEFAULT_INGESTIBLE_EXTENSIONS}.*/readonly extensions?: readonly string[];+ /**+ * Resume an interrupted plan (t_ba1fa5f6): when true, items already recorded+ * in this plan's checkpoint are excluded from the batches, on top of the+ * manifest-`unchanged` skip. The plan id is derived from the full discovered+ * set so it is stable across resumes. Absent → a fresh, checkpoint-blind plan.+ */+ readonly resume?: boolean;}/** One file selected for (re-)ingest, with the reason it was selected. */@@ -89,6 +97,16 @@ export interface BatchPlan {readonly totalFiles: number;/** Total bytes across all batches. */readonly totalBytes: number;+ /**+ * Stable id for this plan (t_ba1fa5f6), derived from the source dir and the+ * full discovered path set. The key an interrupted run resumes against.+ */+ readonly planId: string;+ /**+ * Count of new/modified items excluded because this plan's checkpoint already+ * recorded them completed. Zero on a fresh plan or when `resume` is off.+ */+ readonly resumedCompleted: number;}/**@@ -127,8 +145,23 @@ export function planBatches(vault: string, sourceDir: string, opts: BatchPlanOptcollectIngestible(dirAbs, extensions, discovered);const relPaths = discovered.map((abs) => canonicalNotePath(toPosixRel(vault, abs))).toSorted();+ // The plan id keys on the FULL discovered set, so it is identical before and+ // after an interruption regardless of how many items have completed.+ const planId = computePlanId(dirRel, relPaths);++ // On resume, drop items this plan's checkpoint already recorded completed+ // BEFORE classification, so those items are not re-hashed at all - the+ // resume fast-path that keeps a large-vault resume near-free. The content+ // manifest stays authoritative for anything the checkpoint does not cover.+ const completed =+ opts.resume === true+ ? new Set(readCheckpoint(vault, planId)?.completed ?? [])+ : new Set<string>();+ const toClassify = relPaths.filter((p) => !completed.has(p));+ const resumedCompleted = relPaths.length - toClassify.length;+// Consult A1's manifest: only `new`/`modified` sources are worth ingesting.- const classification = classifyPaths(vault, relPaths, readManifest(vault));+ const classification = classifyPaths(vault, toClassify, readManifest(vault));const skipped = [...classification.unchanged].toSorted();// Build the planned-file list, tagging each with why it was selected, in@@ -152,6 +185,8 @@ export function planBatches(vault: string, sourceDir: string, opts: BatchPlanOptskipped,totalFiles: planned.length,totalBytes: planned.reduce((sum, f) => sum + f.bytes, 0),+ planId,+ resumedCompleted,};}diff --git a/src/core/brain/ingest/checkpoint.ts b/src/core/brain/ingest/checkpoint.tsnew file mode 100644index 00000000..648b406e--- /dev/null+++ b/src/core/brain/ingest/checkpoint.ts@@ -0,0 +1,203 @@+/**+ * Per-plan ingest checkpoint (Ingestion & Import Robustness suite,+ * t_ba1fa5f6).+ *+ * The content-hash manifest ({@link ../ingest/content-manifest.ts}) records a+ * source only once its full {@link ../ingest/ingest.ts:ingestSource} write has+ * landed, so it answers "have we ever fully ingested this file". This module+ * answers a finer, plan-scoped question: "within THIS batch plan, which items+ * have completed so far" - so an interrupted large-folder ingest resumes at the+ * item boundary instead of re-planning from scratch.+ *+ * Union-as-you-go: each completed item is folded into the checkpoint as it+ * finishes; the content manifest stays the authoritative final state. The+ * checkpoint lives at `<vault>/.open-second-brain/ingest-checkpoints/<plan_id>.json`,+ * a machine artifact (not curated memory), mirroring the manifest's location and+ * atomic-write / no-op-on-unchanged discipline.+ *+ * Opt-out: setting `OSB_INGEST_NO_CHECKPOINT` to a truthy value makes record and+ * read inert - the deterministic-test escape hatch mirroring upstream graphify's+ * `GRAPHIFY_NO_INCREMENTAL_CACHE`.+ *+ * Language-agnostic: keys are canonical vault-relative paths and content hashes;+ * no natural-language content is inspected.+ */++import { createHash } from "node:crypto";+import { existsSync, readFileSync, rmSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import { canonicalNotePath } from "../../path-safety.ts";+import { isoSecond } from "../time.ts";++/** Only schema version currently understood. Unknown versions are refused. */+const SCHEMA_VERSION = 1 as const;++/** Vault-relative directory holding OSB machine artifacts (not curated memory). */+const MACHINE_ARTIFACT_DIR = ".open-second-brain";++/** Subdirectory holding one JSON checkpoint per batch plan. */+const CHECKPOINT_DIR = "ingest-checkpoints";++/** Env var that, when truthy, disables checkpoint reads and writes. */+export const NO_CHECKPOINT_ENV = "OSB_INGEST_NO_CHECKPOINT";++/** The persisted per-plan checkpoint. */+export interface IngestCheckpoint {+ readonly schema_version: typeof SCHEMA_VERSION;+ /** Stable id derived from the source dir and the full discovered path set. */+ readonly plan_id: string;+ /** Canonical vault-relative source directory the plan covers. */+ readonly source_dir: string;+ /** Canonical vault-relative paths completed so far, sorted. */+ readonly completed: readonly string[];+ readonly updated_at: string;+}++/**+ * Whether checkpointing is active. Off only when {@link NO_CHECKPOINT_ENV} holds+ * a truthy value; the empty string, `0`, and `false` are all treated as unset so+ * an accidentally-exported empty var does not silently disable resumability.+ */+export function checkpointingEnabled(): boolean {+ const raw = process.env[NO_CHECKPOINT_ENV];+ if (raw === undefined) return true;+ const v = raw.trim().toLowerCase();+ return v === "" || v === "0" || v === "false";+}++/**+ * Deterministic plan id: a short SHA-256 hex over the canonical source dir and+ * the sorted full discovered path set. Keying on the FULL set (not the remaining+ * work) keeps the id stable across a resume even as items complete.+ */+export function computePlanId(sourceDir: string, discoveredPaths: readonly string[]): string {+ const dir = canonicalNotePath(sourceDir);+ const paths = discoveredPaths.map((p) => canonicalNotePath(p)).toSorted();+ const hash = createHash("sha256");+ hash.update(dir);+ hash.update("\0");+ for (const p of paths) {+ hash.update(p);+ hash.update("\n");+ }+ return hash.digest("hex").slice(0, 16);+}++function assertPlanId(planId: string): void {+ if (!/^[0-9a-f]{6,64}$/.test(planId)) {+ throw new Error(`invalid plan id (expected lowercase hex): ${JSON.stringify(planId)}`);+ }+}++/** Absolute path of one plan's checkpoint file. */+export function checkpointPath(vault: string, planId: string): string {+ assertPlanId(planId);+ return join(vault, MACHINE_ARTIFACT_DIR, CHECKPOINT_DIR, `${planId}.json`);+}++function serialize(cp: IngestCheckpoint): string {+ return (+ JSON.stringify(+ {+ schema_version: cp.schema_version,+ plan_id: cp.plan_id,+ source_dir: cp.source_dir,+ completed: [...cp.completed].toSorted(),+ updated_at: cp.updated_at,+ },+ null,+ 2,+ ) + "\n"+ );+}++/**+ * Read a plan's checkpoint. A missing file (or checkpointing disabled) returns+ * `null`. A corrupt file or an unknown `schema_version` is a hard error - never+ * a silent reset that would masquerade completed items as pending.+ */+export function readCheckpoint(vault: string, planId: string): IngestCheckpoint | null {+ if (!checkpointingEnabled()) return null;+ const path = checkpointPath(vault, planId);+ if (!existsSync(path)) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(readFileSync(path, "utf8"));+ } catch (e) {+ throw new Error(`ingest checkpoint is corrupted JSON: ${path}`, { cause: e });+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ throw new Error(`ingest checkpoint is not an object: ${path}`);+ }+ const obj = parsed as Record<string, unknown>;+ if (obj["schema_version"] !== SCHEMA_VERSION) {+ throw new Error(+ `ingest checkpoint schema_version ${String(obj["schema_version"])} not supported (expected ${SCHEMA_VERSION}): ${path}`,+ );+ }+ const rawCompleted = obj["completed"];+ const completed = Array.isArray(rawCompleted)+ ? rawCompleted+ .filter((x): x is string => typeof x === "string")+ .map((p) => canonicalNotePath(p))+ .toSorted()+ : [];+ return Object.freeze({+ schema_version: SCHEMA_VERSION,+ plan_id: planId,+ source_dir: typeof obj["source_dir"] === "string" ? obj["source_dir"] : "",+ completed: Object.freeze(completed),+ updated_at: typeof obj["updated_at"] === "string" ? obj["updated_at"] : "",+ });+}++function sameSet(a: readonly string[], b: readonly string[]): boolean {+ if (a.length !== b.length) return false;+ const set = new Set(a);+ return b.every((x) => set.has(x));+}++/**+ * Fold `paths` into a plan's checkpoint (union-as-you-go), atomically. Returns+ * `true` when the checkpoint was written, `false` on a no-op - checkpointing+ * disabled, or the completed set (and hence the serialized bytes) unchanged. The+ * `updated_at` stamp is only bumped when the set actually grows, so a re-record+ * of an already-recorded set leaves the file byte-identical.+ */+export function recordCompleted(+ vault: string,+ planId: string,+ sourceDir: string,+ paths: readonly string[],+ now: Date,+): boolean {+ if (!checkpointingEnabled()) return false;+ const prev = readCheckpoint(vault, planId);+ const merged = new Set<string>(prev?.completed ?? []);+ for (const p of paths) merged.add(canonicalNotePath(p));+ const completed = [...merged].toSorted();+ if (prev && sameSet(prev.completed, completed)) return false;+ const next: IngestCheckpoint = {+ schema_version: SCHEMA_VERSION,+ plan_id: planId,+ source_dir: canonicalNotePath(sourceDir),+ completed,+ updated_at: isoSecond(now),+ };+ atomicWriteFileSync(checkpointPath(vault, planId), serialize(next));+ return true;+}++/**+ * Remove a plan's checkpoint (the authoritative-final cleanup once a plan is+ * fully drained). Returns `true` when a file was removed, `false` when none+ * existed.+ */+export function clearCheckpoint(vault: string, planId: string): boolean {+ const path = checkpointPath(vault, planId);+ if (!existsSync(path)) return false;+ rmSync(path);+ return true;+}diff --git a/src/core/brain/ingest/ingest.ts b/src/core/brain/ingest/ingest.tsindex 4c668510..8c89fb12 100644--- a/src/core/brain/ingest/ingest.ts+++ b/src/core/brain/ingest/ingest.ts@@ -38,6 +38,7 @@ import {sourceIdentityHash,type Provenance,} from "../provenance/provenance.ts";+import { recordCompleted } from "./checkpoint.ts";import { updateManifest } from "./content-manifest.ts";/** Frontmatter `kind:` marker of an ingested source summary page. */@@ -55,6 +56,13 @@ export interface IngestSourceInput {export interface IngestSourceOptions {readonly agent: string;readonly now: Date;+ /**+ * Batch-plan id (t_ba1fa5f6). When set, a successful ingest of a vault-file+ * source records the source into that plan's resume checkpoint+ * (union-as-you-go). The content manifest stays the authoritative final+ * state; the checkpoint only tracks plan progress. Absent → no checkpoint.+ */+ readonly planId?: string;}export interface IngestSourceResult {@@ -145,6 +153,17 @@ export function ingestSource(// bytes to hash and must leave the manifest untouched (backward-compatible).if (existsSync(join(vault, canonicalSource))) {updateManifest(vault, [canonicalSource]);+ // Record plan-scoped progress so an interrupted batch resumes at the item+ // boundary (t_ba1fa5f6). Only for real vault files - a URL/identity-only+ // source has no place in a folder plan's checkpoint. Best-effort: a+ // checkpoint write failure must never fail the ingest that already landed.+ if (opts.planId !== undefined && opts.planId.length > 0) {+ try {+ recordCompleted(vault, opts.planId, dirname(canonicalSource), [canonicalSource], opts.now);+ } catch {+ // Checkpointing is a resumability optimization, not correctness.+ }+ }}return {diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex 8f8b1c18..620d6ee7 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -62,6 +62,8 @@ export const BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");export const BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");/** Cited research report pages: `Brain/reports/<date>-<slug>.md` (v1.7.0). */export const BRAIN_REPORTS_REL = posix.join(BRAIN_ROOT_REL, "reports");+/** Source-distillation pages: `Brain/distillations/dist-<slug>.md` (t_2e2e959f). */+export const BRAIN_DISTILLATIONS_REL = posix.join(BRAIN_ROOT_REL, "distillations");export const BRAIN_SNAPSHOTS_REL = posix.join(BRAIN_ROOT_REL, ".snapshots");/*** Ephemeral MCP tool-result artifacts (v0.18.0). Dot-directory so the@@ -188,6 +190,12 @@ export function sourcePagePath(vault: string, slug: string): string {return ensureInsideVault(join(vault, BRAIN_SOURCES_REL, `src-${s}.md`), vault);}+/** Source-distillation page: `Brain/distillations/dist-<slug>.md`. */+export function distillationPagePath(vault: string, slug: string): string {+ const s = validateSlug(slug);+ return ensureInsideVault(join(vault, BRAIN_DISTILLATIONS_REL, `dist-${s}.md`), vault);+}+/** Cited research report page: `Brain/reports/<date>-<slug>.md`. */export function reportPagePath(vault: string, date: string, slug: string): string {const d = validateIsoDate(date);diff --git a/src/core/brain/staleness.ts b/src/core/brain/staleness.tsnew file mode 100644index 00000000..163bdbde--- /dev/null+++ b/src/core/brain/staleness.ts@@ -0,0 +1,63 @@+/**+ * Materialize-freshness staleness gate (Ingestion & Import Robustness suite,+ * t_845fe240).+ *+ * A deterministic refresh that materializes outputs from inputs (e.g. the+ * clusters pass writes `Brain/clusters/` from the vault's notes) can be a+ * no-op when the outputs are already newer than every input. This primitive+ * answers that mtime question so an agent can invoke the refresh cheaply at the+ * start of graph work - the expensive recompute runs only when an input+ * actually changed.+ *+ * mtime-based by design: the gate is an OPT-IN fast-path (`--if-stale`), and+ * the `>=` comparison errs toward recompute (an input strictly newer than the+ * oldest output is stale). A missing/unreadable path contributes no mtime+ * rather than being treated as infinitely new, so a transient stat failure+ * never forces a needless recompute.+ *+ * Language-agnostic: only filesystem mtimes are compared; no content is read.+ */++import { statSync } from "node:fs";++export interface StalenessResult {+ /** True when outputs exist and every output is at least as new as every input. */+ readonly fresh: boolean;+ /** Newest input mtime in ms, or null when no input has a readable mtime. */+ readonly newestInputMs: number | null;+ /** Oldest output mtime in ms, or null when no output exists/reads. */+ readonly oldestOutputMs: number | null;+}++/** File mtime in ms, or null when the path is missing or unreadable. */+export function mtimeMs(path: string): number | null {+ try {+ return statSync(path).mtimeMs;+ } catch {+ return null;+ }+}++/**+ * Evaluate whether materialized `outputs` are fresh with respect to `inputs`.+ *+ * Fresh iff at least one output has a readable mtime AND the oldest output+ * mtime is >= the newest input mtime. With no outputs the result is never+ * fresh (nothing has been materialized yet); with outputs but no readable+ * inputs it is fresh (there is nothing that could have changed).+ */+export function evaluateStaleness(+ inputs: readonly string[],+ outputs: readonly string[],+): StalenessResult {+ const inputMs = inputs.map(mtimeMs).filter((m): m is number => m !== null);+ const outputMs = outputs.map(mtimeMs).filter((m): m is number => m !== null);++ const newestInputMs = inputMs.length > 0 ? Math.max(...inputMs) : null;+ if (outputMs.length === 0) {+ return Object.freeze({ fresh: false, newestInputMs, oldestOutputMs: null });+ }+ const oldestOutputMs = Math.min(...outputMs);+ const fresh = newestInputMs === null || oldestOutputMs >= newestInputMs;+ return Object.freeze({ fresh, newestInputMs, oldestOutputMs });+}diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex a1570ba8..7df89100 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -28,6 +28,7 @@ import { LANDSCAPE_TOOLS } from "./brain/landscape-tools.ts";import { HYGIENE_TOOLS } from "./brain/hygiene-tools.ts";import { NER_TOOLS } from "./brain/ner-tools.ts";import { INGEST_TOOLS } from "./brain/ingest-tools.ts";+import { DISTILL_TOOLS } from "./brain/distill-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";@@ -58,6 +59,7 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([...HYGIENE_TOOLS,...NER_TOOLS,...INGEST_TOOLS,+ ...DISTILL_TOOLS,...RESEARCH_TOOLS,...DERIVE_TOOLS,...NOTES_TOOLS,diff --git a/src/mcp/brain/distill-tools.ts b/src/mcp/brain/distill-tools.tsnew file mode 100644index 00000000..c7f044fe--- /dev/null+++ b/src/mcp/brain/distill-tools.ts@@ -0,0 +1,100 @@+/**+ * Source-distillation tool (Ingestion & Import Robustness suite, t_2e2e959f).+ *+ * The calling agent reads a source and distills it into atomic claims, each+ * with an optional block id pointing back to the source block it came from,+ * and submits them here. OSB runs no model - it validates the claims and writes+ * one idempotent distillation page per source, listing each claim with its+ * block-level citation and a provenance section.+ */++import {+ distillSource,+ DistillValidationError,+ normalizeClaim,+ type DistillClaim,+} from "../../core/brain/distill/distill-source.ts";+import { resolveAgentName } from "../../core/config.ts";+import { coerceStr } from "../coerce.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext, ToolDefinition } from "../tools.ts";+import { wrapToolErrors } from "./shared.ts";++const TOOL = "brain_distill_source";++/** Coerce the `claims` arg into DistillClaim[], rejecting a malformed shape. */+function parseClaims(args: Record<string, unknown>): DistillClaim[] {+ const raw = args["claims"];+ if (!Array.isArray(raw) || raw.length === 0) {+ throw new MCPError(INVALID_PARAMS, `${TOOL}: 'claims' must be a non-empty array`);+ }+ return raw.map((item, i) => {+ if (item === null || typeof item !== "object" || Array.isArray(item)) {+ throw new MCPError(INVALID_PARAMS, `${TOOL}: claim ${i} must be an object`);+ }+ return normalizeClaim(item as Record<string, unknown>);+ });+}++async function toolBrainDistillSource(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const sourcePath = coerceStr(args, "source_path", true)!;+ const claims = parseClaims(args);+ const agentArg = coerceStr(args, "agent", false);+ const agent =+ agentArg && agentArg.trim().length > 0+ ? agentArg+ : resolveAgentName(ctx.configPath ?? undefined);++ return wrapToolErrors(TOOL, [DistillValidationError], async () => {+ const res = distillSource(ctx.vault, { sourcePath, claims }, { agent, now: new Date() });+ return {+ distillation_path: res.distillationPath,+ created: res.created,+ claim_count: res.claimCount,+ source_hash: res.sourceHash,+ };+ });+}++export const DISTILL_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([+ {+ name: TOOL,+ description:+ "Distill one source into atomic claims with block-level provenance. Supply `source_path` (vault path or URL) and `claims`: a non-empty array of { text, block? } (`block` is the source's Obsidian block id). Writes one idempotent page citing each claim as `[[source#^block]]`. No model.",+ inputSchema: {+ type: "object",+ properties: {+ source_path: {+ type: "string",+ description: "Source identity: a vault-relative path or a URL.",+ },+ claims: {+ type: "array",+ description: "Atomic claims distilled from the source (non-empty).",+ items: {+ type: "object",+ properties: {+ text: { type: "string", description: "The atomic claim text." },+ block: {+ type: "string",+ description: "Optional source block id the claim was drawn from (the `^abc` id).",+ },+ },+ required: ["text"],+ additionalProperties: false,+ },+ },+ agent: {+ type: "string",+ description: "Optional agent identity override; defaults to the server-resolved name.",+ },+ },+ required: ["source_path", "claims"],+ additionalProperties: false,+ },+ handler: toolBrainDistillSource,+ },+]);diff --git a/src/mcp/brain/ingest-tools.ts b/src/mcp/brain/ingest-tools.tsindex d28165d2..db7c4b72 100644--- a/src/mcp/brain/ingest-tools.ts+++ b/src/mcp/brain/ingest-tools.ts@@ -10,6 +10,7 @@*/import { planBatches, type BatchPlan } from "../../core/brain/ingest/batch-plan.ts";+import { clearCheckpoint } from "../../core/brain/ingest/checkpoint.ts";import { ingestSource } from "../../core/brain/ingest/ingest.ts";import { IntakeValidationError } from "../../core/brain/intake/extract-intake.ts";import {@@ -40,6 +41,7 @@ async function toolBrainIngestSource(): Promise<Record<string, unknown>> {const sourcePath = coerceStr(args, "source_path", true)!;const summary = coerceStr(args, "summary", true)!;+ const planId = coerceStr(args, "plan_id", false) ?? undefined;const parsed = parseExtractionIntakeArgs(args, TOOL);const agent =parsed.agent && parsed.agent.trim().length > 0@@ -50,7 +52,7 @@ async function toolBrainIngestSource(const res = ingestSource(ctx.vault,{ sourcePath, summary, extraction: parsed.intake },- { agent, now: new Date() },+ { agent, now: new Date(), ...(planId !== undefined ? { planId } : {}) },);return {summary_path: res.summaryPath,@@ -127,6 +129,8 @@ function serializeBatchPlan(plan: BatchPlan): Record<string, unknown> {total_files: plan.totalFiles,total_bytes: plan.totalBytes,skipped: [...plan.skipped],+ plan_id: plan.planId,+ resumed_completed: plan.resumedCompleted,batches: plan.batches.map((b) => ({index: b.index,total_bytes: b.totalBytes,@@ -154,7 +158,13 @@ async function toolBrainIngestBatchPlan(1,Number.MAX_SAFE_INTEGER,);- const plan = planBatches(ctx.vault, sourceDir, { maxBatchBytes, maxBatchFiles });+ const resume = coerceBoolOptional(args, "resume") ?? false;+ const plan = planBatches(ctx.vault, sourceDir, { maxBatchBytes, maxBatchFiles, resume });+ // A resumed plan that comes back empty is fully drained: drop its checkpoint+ // (the content manifest is the authoritative final state from here on).+ if (resume && plan.batches.length === 0) {+ clearCheckpoint(ctx.vault, plan.planId);+ }return serializeBatchPlan(plan);}@@ -209,6 +219,11 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([type: "string",description: "Optional agent identity override; defaults to the server-resolved name.",},+ plan_id: {+ type: "string",+ description:+ "Optional batch-plan id (from brain_ingest_batch_plan). When set, a successful ingest records this source into that plan's resume checkpoint.",+ },},required: ["source_path", "summary", "entities"],additionalProperties: false,@@ -284,6 +299,11 @@ export const INGEST_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([minimum: 1,description: `File-count cap per batch. Default ${DEFAULT_MAX_BATCH_FILES}.`,},+ resume: {+ type: "boolean",+ description:+ "Resume an interrupted plan: exclude items already recorded completed in this plan's checkpoint. Default false.",+ },},required: ["source_dir"],additionalProperties: false,diff --git a/src/mcp/registry-guard.ts b/src/mcp/registry-guard.tsindex 0dcdcd63..9c13988a 100644--- a/src/mcp/registry-guard.ts+++ b/src/mcp/registry-guard.ts@@ -91,6 +91,7 @@ export const PREVIEW_BUDGET_EXEMPT: Readonly<Record<string, string>> = Object.frschema_apply_mutations: "write; returns a bounded mutation receipt",brain_intake_entities: "write; returns created/updated id lists and a relation count",brain_ingest_source: "write; returns the summary path plus bounded id lists",+ brain_distill_source: "write; returns the distillation path plus a claim count and source hash",brain_research_report: "write; returns the report path and a finding count",brain_derive_fact: "write; returns one derived preference id, its level and premises",brain_memory_bridge:diff --git a/tests/cli/brain-clusters.test.ts b/tests/cli/brain-clusters.test.tsindex 37eb497e..01ce7bbf 100644--- a/tests/cli/brain-clusters.test.ts+++ b/tests/cli/brain-clusters.test.ts@@ -6,7 +6,7 @@*/import { afterEach, beforeEach, expect, test } from "bun:test";-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -144,6 +144,39 @@ test("run without --batch-size omits the batches field", async () => {expect(JSON.parse(run.stdout)).not.toHaveProperty("batches");});+test("run --if-stale skips when outputs are already fresh (t_845fe240)", async () => {+ await index();+ const first = await runCli(["brain", "clusters", "run", "--vault", vault, "--json"]);+ expect(first.returncode).toBe(0);+ // Nothing changed since the materialization → outputs fresh → skip.+ const second = await runCli([+ "brain",+ "clusters",+ "run",+ "--vault",+ vault,+ "--if-stale",+ "--json",+ ]);+ expect(second.returncode).toBe(0);+ expect(JSON.parse(second.stdout)).toMatchObject({ skipped: "fresh" });+ const skipMetric = listMetrics(vault, { surface: "communities" }).some(+ (m) => (m.payload as { skipped?: string }).skipped === "fresh",+ );+ expect(skipMetric).toBe(true);+});++test("run --if-stale recomputes after an input note changes (t_845fe240)", async () => {+ await index();+ await runCli(["brain", "clusters", "run", "--vault", vault]);+ // Make an input note strictly newer than the materialized outputs.+ const future = Date.now() / 1000 + 100;+ utimesSync(join(vault, "team-a.md"), future, future);+ const r = await runCli(["brain", "clusters", "run", "--vault", vault, "--if-stale", "--json"]);+ expect(r.returncode).toBe(0);+ expect(JSON.parse(r.stdout).skipped).toBeUndefined();+});+test("usage errors exit 2", async () => {const r = await runCli(["brain", "clusters", "nope", "--vault", vault]);expect(r.returncode).toBe(2);diff --git a/tests/cli/brain-distill.test.ts b/tests/cli/brain-distill.test.tsnew file mode 100644index 00000000..403a0728--- /dev/null+++ b/tests/cli/brain-distill.test.ts@@ -0,0 +1,63 @@+/**+ * `o2b brain distill` CLI (t_2e2e959f): condense a source into atomic claims+ * with block-level provenance, supplied as JSON.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let env: Record<string, string>;++beforeEach(async () => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-cli-distill-"));+ vault = join(tmp, "vault");+ const config = join(tmp, "config.yaml");+ env = { OPEN_SECOND_BRAIN_CONFIG: config };+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });+ await runCli(["brain", "init", "--vault", vault], { env });+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, "Articles", "src.md"), "# Src\n\nBody.\n", "utf8");+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++test("distills a source into a citeable claims page", async () => {+ const claims = JSON.stringify([+ { text: "First atomic claim.", block: "abc" },+ { text: "Second atomic claim." },+ ]);+ const res = await runCli(+ ["brain", "distill", "Articles/src.md", "--claims", claims, "--vault", vault, "--json"],+ { env },+ );+ expect(res.returncode).toBe(0);+ const out = JSON.parse(res.stdout) as { distillation_path: string; claim_count: number };+ expect(out.claim_count).toBe(2);+ const md = readFileSync(join(vault, out.distillation_path), "utf8");+ expect(md).toContain("## Claims");+ expect(md).toContain("([[Articles/src.md#^abc]])");+ expect(existsSync(join(vault, out.distillation_path))).toBe(true);+});++test("an empty claim list is rejected (validation error, exit 1)", async () => {+ const res = await runCli(+ ["brain", "distill", "Articles/src.md", "--claims", "[]", "--vault", vault],+ { env },+ );+ expect(res.returncode).toBe(1);+});++test("missing <source> or --claims is a usage error (exit 2)", async () => {+ const noSource = await runCli(["brain", "distill", "--claims", "[]", "--vault", vault], { env });+ expect(noSource.returncode).toBe(2);+ const noClaims = await runCli(["brain", "distill", "Articles/src.md", "--vault", vault], { env });+ expect(noClaims.returncode).toBe(2);+});diff --git a/tests/cli/brain-import-claude-memory.test.ts b/tests/cli/brain-import-claude-memory.test.tsindex 6a910b05..d989c95c 100644--- a/tests/cli/brain-import-claude-memory.test.ts+++ b/tests/cli/brain-import-claude-memory.test.ts@@ -84,4 +84,53 @@ describe("o2b brain import-claude-memory CLI", () => {expect(res.returncode).toBe(2);expect(res.stderr).toMatch(/--apply.*--dry-run|--dry-run.*--apply/);});++ test("--from mem0 imports a mem0 export (t_ac9d2588)", async () => {+ const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli-mem0-"));+ const vault = join(tmp, "vault");+ const config = join(tmp, "config.yaml");+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });+ await runCli(["brain", "init", "--vault", vault], { env });+ const exportFile = join(tmp, "mem0-export.json");+ writeFileSync(+ exportFile,+ JSON.stringify([{ name: "from-mem0", memory: "Imported from mem0." }]),+ "utf8",+ );+ const res = await runCli(+ [+ "brain",+ "import-claude-memory",+ "--vault",+ vault,+ "--from",+ "mem0",+ "--memory",+ exportFile,+ "--dry-run",+ "--allow-arbitrary-memory-path",+ ],+ { env },+ );+ expect(res.returncode).toBe(0);+ expect(res.stdout).toContain("CREATE pref-from-mem0");+ rmSync(tmp, { recursive: true });+ });++ test("--from with an unknown backend fails loudly", async () => {+ const tmp = mkdtempSync(join(tmpdir(), "o2b-cm-cli-badbackend-"));+ const vault = join(tmp, "vault");+ const config = join(tmp, "config.yaml");+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ await runCli(["init", "--vault", vault, "--name", "Test"], { env });+ await runCli(["brain", "init", "--vault", vault], { env });+ const res = await runCli(+ ["brain", "import-claude-memory", "--vault", vault, "--from", "nope"],+ { env },+ );+ expect(res.returncode).toBe(1);+ expect(res.stderr).toMatch(/unknown memory backend 'nope'/);+ rmSync(tmp, { recursive: true });+ });});diff --git a/tests/cli/install-verb.test.ts b/tests/cli/install-verb.test.tsindex 1af93c7c..e71a12f0 100644--- a/tests/cli/install-verb.test.ts+++ b/tests/cli/install-verb.test.ts@@ -11,7 +11,15 @@ import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync, utimesSynimport { tmpdir } from "node:os";import { join } from "node:path";-import { runCli } from "../helpers/run-cli.ts";+import { runCli as baseRunCli, type RunCliOptions, type RunResult } from "../helpers/run-cli.ts";++// The install/uninstall adapters resolve the target home directory from the+// environment at module-load time, so they need a fresh child process per call+// to honor this test's per-case temp HOME (the in-process fast path shares one+// already-loaded module graph). Force the subprocess path for every call here.+function runCli(args: ReadonlyArray<string>, opts: RunCliOptions = {}): Promise<RunResult> {+ return baseRunCli(args, { ...opts, subprocess: true });+}let vault: string;let home: string;diff --git a/tests/core/brain/agent-backend-json.test.ts b/tests/core/brain/agent-backend-json.test.tsnew file mode 100644index 00000000..62a60d51--- /dev/null+++ b/tests/core/brain/agent-backend-json.test.ts@@ -0,0 +1,147 @@+/**+ * mem0 / generic JSON memory-store backends (t_ac9d2588). The seam widened to+ * discover-files + parse-entries so one JSON export maps to many preferences.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";++import { mem0MemoryBackend } from "../../../src/core/brain/agent-backend/mem0.ts";+import { genericMemoryBackend } from "../../../src/core/brain/agent-backend/generic.ts";+import { getMemoryBackend } from "../../../src/core/brain/agent-backend/registry.ts";+import { importClaudeMemory } from "../../../src/core/brain/import-claude-memory.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-json-backend-"));+});+afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++describe("mem0 backend", () => {+ test("parses a top-level array export into one entry per record", () => {+ const text = JSON.stringify([+ { id: "abc", memory: "Prefer pipeline() over barriers." },+ { name: "tone", memory: "Keep a neutral tone.", metadata: { description: "Voice rule" } },+ ]);+ const entries = mem0MemoryBackend.parseMemoryEntries(text);+ expect(entries).toHaveLength(2);+ expect(entries[0]).toMatchObject({+ kind: "feedback",+ body: "Prefer pipeline() over barriers.",+ });+ expect(entries[1]).toMatchObject({ kind: "feedback", name: "tone", description: "Voice rule" });+ });++ test("parses the {results:[...]} envelope shape", () => {+ const text = JSON.stringify({ results: [{ memory: "Alpha." }, { memory: "Bravo." }] });+ const entries = mem0MemoryBackend.parseMemoryEntries(text);+ expect(entries).toHaveLength(2);+ expect(entries.every((e) => e.kind === "feedback")).toBe(true);+ });++ test("a record with no memory text skips with a reason", () => {+ const entries = mem0MemoryBackend.parseMemoryEntries(JSON.stringify([{ id: "x" }]));+ expect(entries[0]).toMatchObject({ kind: "skip" });+ });++ test("a non-object record and invalid JSON both skip", () => {+ expect(mem0MemoryBackend.parseMemoryEntries(JSON.stringify(["nope"]))[0]).toMatchObject({+ kind: "skip",+ });+ expect(mem0MemoryBackend.parseMemoryEntries("{ not json")[0]).toMatchObject({ kind: "skip" });+ });++ test("discoverMemoryFiles selects .json exports only", () => {+ writeFileSync(join(tmp, "export.json"), "[]", "utf8");+ writeFileSync(join(tmp, "notes.md"), "x", "utf8");+ expect(mem0MemoryBackend.discoverMemoryFiles(tmp)).toEqual(["export.json"]);+ });++ test("discoverMemoryDir has no default and fails loudly", () => {+ expect(() => mem0MemoryBackend.discoverMemoryDir("/srv/x")).toThrow(/--memory/);+ });+});++describe("generic backend", () => {+ test("parses the neutral {name,description,body} array", () => {+ const text = JSON.stringify([+ { name: "no-shouting", description: "Tone rule", body: "Never use all caps." },+ { body: "Minimal entry with body only." },+ ]);+ const entries = genericMemoryBackend.parseMemoryEntries(text);+ expect(entries).toHaveLength(2);+ expect(entries[0]).toMatchObject({+ kind: "feedback",+ name: "no-shouting",+ description: "Tone rule",+ });+ // Minimal entry: name/description fall back to a body-derived value.+ expect(entries[1]).toMatchObject({ kind: "feedback", body: "Minimal entry with body only." });+ });++ test("registered under its id; unknown id fails with the registered list", () => {+ expect(getMemoryBackend("mem0").id).toBe("mem0");+ expect(getMemoryBackend("generic").id).toBe("generic");+ expect(() => getMemoryBackend("nope")).toThrow(/registered: claude, mem0, generic/);+ });+});++describe("importClaudeMemory through the mem0 backend (end-to-end)", () => {+ function setupVault(): string {+ const v = join(tmp, "vault");+ mkdirSync(v, { recursive: true });+ bootstrapBrain(v);+ return v;+ }++ test("dry-run plans one preference per mem0 record", () => {+ const vault = setupVault();+ const memDir = join(tmp, "mem0");+ mkdirSync(memDir, { recursive: true });+ writeFileSync(+ join(memDir, "export.json"),+ JSON.stringify([+ { name: "rule-a", memory: "Body A." },+ { name: "rule-b", memory: "Body B." },+ ]),+ "utf8",+ );+ const res = importClaudeMemory({+ vault,+ memoryDir: memDir,+ mode: "dry-run",+ allowArbitraryMemoryPath: true,+ backend: mem0MemoryBackend,+ });+ expect(res.plans).toHaveLength(2);+ expect(res.plans.every((p) => p.action === "CREATE")).toBe(true);+ });++ test("apply writes one preference file per record, pointed at a single export file", () => {+ const vault = setupVault();+ const memFile = join(tmp, "mem0-export.json");+ writeFileSync(+ memFile,+ JSON.stringify({ results: [{ name: "keep-neutral", memory: "Stay neutral." }] }),+ "utf8",+ );+ const res = importClaudeMemory({+ vault,+ memoryDir: memFile,+ mode: "apply",+ allowArbitraryMemoryPath: true,+ backend: mem0MemoryBackend,+ });+ expect(res.applied).toHaveLength(1);+ const prefFile = join(vault, "Brain", "preferences", "pref-keep-neutral.md");+ expect(existsSync(prefFile)).toBe(true);+ const body = readFileSync(prefFile, "utf8");+ expect(body).toContain("Stay neutral.");+ });+});diff --git a/tests/core/brain/agent-backend.test.ts b/tests/core/brain/agent-backend.test.tsindex 4517d681..90ffdf0a 100644--- a/tests/core/brain/agent-backend.test.ts+++ b/tests/core/brain/agent-backend.test.ts@@ -49,9 +49,9 @@ const MEMORY_FILE = ["**How to apply:** Use neutral punctuation.",].join("\n");-test("registry lists the claude backend and resolves it by id", () => {+test("registry lists the registered backends and resolves them by id", () => {const ids = listMemoryBackends().map((b) => b.id);- expect(ids).toEqual(["claude"]);+ expect(ids).toEqual(["claude", "mem0", "generic"]);expect(getMemoryBackend("claude").id).toBe("claude");expect(DEFAULT_MEMORY_BACKEND_ID).toBe("claude");});@@ -75,8 +75,9 @@ test("resolveMemoryBackend defaults to claude and honors the memory_backend conf});test("the claude adapter is byte-identical to the claude-memory modules", () => {- const parsed = claudeMemoryBackend.parseMemoryFile(MEMORY_FILE);- expect(parsed).toEqual(parseClaudeMemoryFile(MEMORY_FILE));+ const entries = claudeMemoryBackend.parseMemoryEntries(MEMORY_FILE);+ expect(entries).toEqual([parseClaudeMemoryFile(MEMORY_FILE)]);+ const parsed = entries[0]!;if (parsed.kind !== "feedback") throw new Error("fixture must parse as feedback");expect(claudeMemoryBackend.slugifyName(parsed.name)).toBe(slugifyMemoryName(parsed.name));diff --git a/tests/core/brain/distill/distill-source.test.ts b/tests/core/brain/distill/distill-source.test.tsnew file mode 100644index 00000000..7ee32820--- /dev/null+++ b/tests/core/brain/distill/distill-source.test.ts@@ -0,0 +1,122 @@+/**+ * Source distillation core (t_2e2e959f): condense a source into atomic claims+ * with block-level provenance. Provider-agnostic; idempotent on the source.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { createHash } from "node:crypto";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";++import {+ distillSource,+ DistillValidationError,+} from "../../../../src/core/brain/distill/distill-source.ts";+import { bootstrapBrain } from "../../../../src/core/brain/init.ts";++let vault: string;+const NOW = new Date("2026-07-10T08:00:00Z");+const LATER = new Date("2026-07-11T09:00:00Z");++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-distill-"));+ bootstrapBrain(vault);+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, "Articles", "restaking.md"), "# Restaking\n\nBody text.\n", "utf8");+});+afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++const INPUT = {+ sourcePath: "Articles/restaking.md",+ claims: [+ { text: "Restaking reuses staked capital to secure additional services.", block: "abc" },+ { text: "It introduces correlated slashing risk." },+ ],+};++function readPage(path: string): string {+ return readFileSync(join(vault, path), "utf8");+}++describe("distillSource", () => {+ test("writes a distillation page with atomic claims and block-level citations", () => {+ const res = distillSource(vault, INPUT, { agent: "claude", now: NOW });+ expect(res.created).toBe(true);+ expect(res.claimCount).toBe(2);++ const md = readPage(res.distillationPath);+ expect(md).toContain("kind: brain-distillation");+ expect(md).toContain("## Claims");+ // The block-bearing claim renders a block-level citation; the other does not.+ expect(md).toContain(+ "- Restaking reuses staked capital to secure additional services. ([[Articles/restaking.md#^abc]])",+ );+ expect(md).toContain("- It introduces correlated slashing risk.");+ expect(md).toContain("## Sources");+ expect(md).toContain("[[Articles/restaking.md]]");+ });++ test("stamps a source_hash equal to sha256 of the source bytes", () => {+ const res = distillSource(vault, INPUT, { agent: "claude", now: NOW });+ const expected = createHash("sha256")+ .update(readFileSync(join(vault, "Articles", "restaking.md")))+ .digest("hex");+ expect(res.sourceHash).toBe(expected);+ expect(readPage(res.distillationPath)).toContain(`source_hash: ${expected}`);+ });++ test("rejects an empty claim list and an empty-text claim (no page written)", () => {+ expect(() =>+ distillSource(+ vault,+ { sourcePath: "Articles/restaking.md", claims: [] },+ {+ agent: "claude",+ now: NOW,+ },+ ),+ ).toThrow(DistillValidationError);+ expect(() =>+ distillSource(+ vault,+ { sourcePath: "Articles/restaking.md", claims: [{ text: " " }] },+ { agent: "claude", now: NOW },+ ),+ ).toThrow(DistillValidationError);+ });++ test("rejects a malformed block id", () => {+ expect(() =>+ distillSource(+ vault,+ { sourcePath: "Articles/restaking.md", claims: [{ text: "x", block: "bad id!" }] },+ { agent: "claude", now: NOW },+ ),+ ).toThrow(/block id/);+ });++ test("is idempotent on the source: same input rewrites nothing, changed input rewrites in place", () => {+ const first = distillSource(vault, INPUT, { agent: "claude", now: NOW });+ const before = readPage(first.distillationPath);++ const second = distillSource(vault, INPUT, { agent: "claude", now: LATER });+ expect(second.created).toBe(false);+ expect(second.distillationPath).toBe(first.distillationPath);+ // Byte-identical re-run: created_at preserved, no updated_at churn.+ expect(readPage(second.distillationPath)).toBe(before);++ const changed = distillSource(+ vault,+ { sourcePath: INPUT.sourcePath, claims: [{ text: "A single revised claim." }] },+ { agent: "claude", now: LATER },+ );+ expect(changed.distillationPath).toBe(first.distillationPath);+ const md = readPage(changed.distillationPath);+ expect(md).toContain("- A single revised claim.");+ expect(md).toContain('created_at: "2026-07-10T08:00:00Z"');+ expect(md).toContain('updated_at: "2026-07-11T09:00:00Z"');+ });+});diff --git a/tests/core/brain/ingest/batch-plan.test.ts b/tests/core/brain/ingest/batch-plan.test.tsindex 81e2cc66..1259c781 100644--- a/tests/core/brain/ingest/batch-plan.test.ts+++ b/tests/core/brain/ingest/batch-plan.test.ts@@ -16,6 +16,7 @@ import { bootstrapBrain } from "../../../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";import { updateManifest } from "../../../../src/core/brain/ingest/content-manifest.ts";import { planBatches } from "../../../../src/core/brain/ingest/batch-plan.ts";+import { recordCompleted } from "../../../../src/core/brain/ingest/checkpoint.ts";let vault: string;let configHome: string;@@ -166,3 +167,63 @@ describe("planBatches — determinism + empty", () => {expect(() => planBatches(vault, "Nope", { maxBatchBytes: 100, maxBatchFiles: 10 })).toThrow();});});++describe("planBatches — resume (t_ba1fa5f6)", () => {+ test("resume excludes checkpointed items but keeps the plan id stable", () => {+ writeSized("Big/a.md", 100);+ writeSized("Big/b.md", 100);+ writeSized("Big/c.md", 100);++ // Fresh plan sees all three; its id is derived from the full discovered set.+ const fresh = planBatches(vault, "Big", { maxBatchBytes: 10_000, maxBatchFiles: 100 });+ expect(fresh.totalFiles).toBe(3);+ expect(fresh.resumedCompleted).toBe(0);++ // Simulate an interruption after two items completed.+ recordCompleted(vault, fresh.planId, "Big", ["Big/a.md", "Big/b.md"], new Date());++ const resumed = planBatches(vault, "Big", {+ maxBatchBytes: 10_000,+ maxBatchFiles: 100,+ resume: true,+ });+ expect(resumed.planId).toBe(fresh.planId);+ expect(allPlannedPaths(resumed)).toEqual(["Big/c.md"]);+ expect(resumed.totalFiles).toBe(1);+ expect(resumed.resumedCompleted).toBe(2);+ });++ test("without resume the checkpoint is ignored", () => {+ writeSized("Big/a.md", 100);+ writeSized("Big/b.md", 100);+ const planId = planBatches(vault, "Big", {+ maxBatchBytes: 10_000,+ maxBatchFiles: 100,+ }).planId;+ recordCompleted(vault, planId, "Big", ["Big/a.md"], new Date());++ const plan = planBatches(vault, "Big", { maxBatchBytes: 10_000, maxBatchFiles: 100 });+ expect(plan.totalFiles).toBe(2);+ expect(plan.resumedCompleted).toBe(0);+ });++ test("OSB_INGEST_NO_CHECKPOINT makes resume a no-op (nothing excluded)", () => {+ writeSized("Big/a.md", 100);+ writeSized("Big/b.md", 100);+ const fresh = planBatches(vault, "Big", { maxBatchBytes: 10_000, maxBatchFiles: 100 });+ try {+ process.env["OSB_INGEST_NO_CHECKPOINT"] = "1";+ // record is inert under the opt-out, and so is the resume read.+ recordCompleted(vault, fresh.planId, "Big", ["Big/a.md"], new Date());+ const plan = planBatches(vault, "Big", {+ maxBatchBytes: 10_000,+ maxBatchFiles: 100,+ resume: true,+ });+ expect(plan.totalFiles).toBe(2);+ expect(plan.resumedCompleted).toBe(0);+ } finally {+ delete process.env["OSB_INGEST_NO_CHECKPOINT"];+ }+ });+});diff --git a/tests/core/brain/ingest/checkpoint.test.ts b/tests/core/brain/ingest/checkpoint.test.tsnew file mode 100644index 00000000..984191df--- /dev/null+++ b/tests/core/brain/ingest/checkpoint.test.ts@@ -0,0 +1,147 @@+import { afterEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ checkpointPath,+ checkpointingEnabled,+ clearCheckpoint,+ computePlanId,+ readCheckpoint,+ recordCompleted,+} from "../../../../src/core/brain/ingest/checkpoint.ts";++function setupVault(): string {+ return mkdtempSync(join(tmpdir(), "o2b-ckpt-"));+}++const AT = new Date("2026-07-10T08:00:00Z");++afterEach(() => {+ delete process.env["OSB_INGEST_NO_CHECKPOINT"];+});++describe("computePlanId", () => {+ test("is stable regardless of discovered-path order", () => {+ const a = computePlanId("docs", ["docs/b.md", "docs/a.md"]);+ const b = computePlanId("docs", ["docs/a.md", "docs/b.md"]);+ expect(a).toBe(b);+ expect(a).toMatch(/^[0-9a-f]{16}$/);+ });++ test("differs when the source dir or the path set differs", () => {+ const base = computePlanId("docs", ["docs/a.md"]);+ expect(computePlanId("notes", ["docs/a.md"])).not.toBe(base);+ expect(computePlanId("docs", ["docs/a.md", "docs/b.md"])).not.toBe(base);+ });+});++describe("recordCompleted / readCheckpoint", () => {+ test("unions items across calls and reports them sorted", () => {+ const vault = setupVault();+ try {+ const planId = computePlanId("docs", ["docs/a.md", "docs/b.md", "docs/c.md"]);+ recordCompleted(vault, planId, "docs", ["docs/b.md"], AT);+ recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);+ const cp = readCheckpoint(vault, planId);+ expect(cp).not.toBeNull();+ expect(cp!.completed).toEqual(["docs/a.md", "docs/b.md"]);+ expect(cp!.plan_id).toBe(planId);+ expect(cp!.source_dir).toBe("docs");+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("re-recording the same set is a byte-identity no-op", () => {+ const vault = setupVault();+ try {+ const planId = computePlanId("docs", ["docs/a.md"]);+ expect(recordCompleted(vault, planId, "docs", ["docs/a.md"], AT)).toBe(true);+ const before = readFileSync(checkpointPath(vault, planId), "utf8");+ const later = new Date("2026-07-10T09:00:00Z");+ expect(recordCompleted(vault, planId, "docs", ["docs/a.md"], later)).toBe(false);+ const after = readFileSync(checkpointPath(vault, planId), "utf8");+ expect(after).toBe(before);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("a corrupt checkpoint throws rather than silently resetting", () => {+ const vault = setupVault();+ try {+ const planId = computePlanId("docs", ["docs/a.md"]);+ const path = checkpointPath(vault, planId);+ recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);+ writeFileSync(path, "{ not json", "utf8");+ expect(() => readCheckpoint(vault, planId)).toThrow(/corrupt/i);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("an unknown schema_version throws", () => {+ const vault = setupVault();+ try {+ const planId = computePlanId("docs", ["docs/a.md"]);+ const path = checkpointPath(vault, planId);+ recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);+ writeFileSync(path, JSON.stringify({ schema_version: 99, completed: [] }), "utf8");+ expect(() => readCheckpoint(vault, planId)).toThrow(/schema_version/);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("rejects a plan id that could escape the checkpoint dir", () => {+ const vault = setupVault();+ try {+ expect(() => readCheckpoint(vault, "../../etc/passwd")).toThrow(/plan id/i);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });+});++describe("clearCheckpoint", () => {+ test("removes the checkpoint file and reports whether it existed", () => {+ const vault = setupVault();+ try {+ const planId = computePlanId("docs", ["docs/a.md"]);+ recordCompleted(vault, planId, "docs", ["docs/a.md"], AT);+ expect(existsSync(checkpointPath(vault, planId))).toBe(true);+ expect(clearCheckpoint(vault, planId)).toBe(true);+ expect(existsSync(checkpointPath(vault, planId))).toBe(false);+ expect(clearCheckpoint(vault, planId)).toBe(false);+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });+});++describe("OSB_INGEST_NO_CHECKPOINT opt-out", () => {+ test("makes record/read inert", () => {+ const vault = setupVault();+ try {+ process.env["OSB_INGEST_NO_CHECKPOINT"] = "1";+ expect(checkpointingEnabled()).toBe(false);+ const planId = computePlanId("docs", ["docs/a.md"]);+ expect(recordCompleted(vault, planId, "docs", ["docs/a.md"], AT)).toBe(false);+ expect(existsSync(checkpointPath(vault, planId))).toBe(false);+ expect(readCheckpoint(vault, planId)).toBeNull();+ } finally {+ rmSync(vault, { recursive: true, force: true });+ }+ });++ test("treats empty/0/false as still-enabled", () => {+ process.env["OSB_INGEST_NO_CHECKPOINT"] = "0";+ expect(checkpointingEnabled()).toBe(true);+ process.env["OSB_INGEST_NO_CHECKPOINT"] = "false";+ expect(checkpointingEnabled()).toBe(true);+ process.env["OSB_INGEST_NO_CHECKPOINT"] = "";+ expect(checkpointingEnabled()).toBe(true);+ });+});diff --git a/tests/core/brain/ingest/ingest.test.ts b/tests/core/brain/ingest/ingest.test.tsindex 2b6f57e2..6c9595bc 100644--- a/tests/core/brain/ingest/ingest.test.ts+++ b/tests/core/brain/ingest/ingest.test.ts@@ -7,7 +7,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";@@ -19,6 +19,7 @@ import {upsertEntity,} from "../../../../src/core/brain/entities/registry.ts";import { ingestSource } from "../../../../src/core/brain/ingest/ingest.ts";+import { computePlanId, readCheckpoint } from "../../../../src/core/brain/ingest/checkpoint.ts";let vault: string;let configHome: string;@@ -102,4 +103,22 @@ describe("ingestSource", () => {const restaking = getEntity(vault, { category: "concept", query: "Restaking" });expect(restaking?.body).toContain("[[Articles/restaking-primer.md]]");});++ test("planId records the ingested vault-file source into the plan checkpoint (t_ba1fa5f6)", () => {+ // The checkpoint is only recorded for a real vault file, so materialize it.+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, "Articles", "restaking-primer.md"), "content", "utf8");+ const planId = computePlanId("Articles", ["Articles/restaking-primer.md"]);+ ingestSource(vault, INPUT, { agent: "claude", now: NOW, planId });+ const cp = readCheckpoint(vault, planId);+ expect(cp?.completed).toEqual(["Articles/restaking-primer.md"]);+ });++ test("without planId no checkpoint is written", () => {+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, "Articles", "restaking-primer.md"), "content", "utf8");+ const planId = computePlanId("Articles", ["Articles/restaking-primer.md"]);+ ingestSource(vault, INPUT, { agent: "claude", now: NOW });+ expect(readCheckpoint(vault, planId)).toBeNull();+ });});diff --git a/tests/core/brain/staleness.test.ts b/tests/core/brain/staleness.test.tsnew file mode 100644index 00000000..7d49f57a--- /dev/null+++ b/tests/core/brain/staleness.test.ts@@ -0,0 +1,84 @@+import { describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";++import { evaluateStaleness } from "../../../src/core/brain/staleness.ts";++function setup(): string {+ return mkdtempSync(join(tmpdir(), "o2b-staleness-"));+}++/** Write a file and stamp its mtime to a fixed epoch-second. */+function writeAt(path: string, atSec: number): void {+ writeFileSync(path, "x", "utf8");+ utimesSync(path, atSec, atSec);+}++describe("evaluateStaleness", () => {+ test("no outputs is never fresh (nothing materialized yet)", () => {+ const dir = setup();+ try {+ const input = join(dir, "in.md");+ writeAt(input, 1000);+ const res = evaluateStaleness([input], []);+ expect(res.fresh).toBe(false);+ expect(res.oldestOutputMs).toBeNull();+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("fresh when every output is at least as new as every input", () => {+ const dir = setup();+ try {+ const input = join(dir, "in.md");+ const output = join(dir, "out.md");+ writeAt(input, 1000);+ writeAt(output, 2000);+ expect(evaluateStaleness([input], [output]).fresh).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("stale when any input is newer than the oldest output", () => {+ const dir = setup();+ try {+ const input = join(dir, "in.md");+ const output = join(dir, "out.md");+ writeAt(output, 1000);+ writeAt(input, 2000);+ const res = evaluateStaleness([input], [output]);+ expect(res.fresh).toBe(false);+ expect(res.newestInputMs).toBe(2000 * 1000);+ expect(res.oldestOutputMs).toBe(1000 * 1000);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("no inputs with existing outputs is fresh (nothing to be stale against)", () => {+ const dir = setup();+ try {+ const output = join(dir, "out.md");+ writeAt(output, 1000);+ expect(evaluateStaleness([], [output]).fresh).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("unreadable paths are ignored, not treated as newest", () => {+ const dir = setup();+ try {+ const output = join(dir, "out.md");+ writeAt(output, 2000);+ // A missing input path contributes no mtime.+ const res = evaluateStaleness([join(dir, "gone.md")], [output]);+ expect(res.fresh).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/tests/e2e/agent-write-contract.integration.test.ts b/tests/e2e/agent-write-contract.integration.test.tsindex 3683ab48..99c513a5 100644--- a/tests/e2e/agent-write-contract.integration.test.ts+++ b/tests/e2e/agent-write-contract.integration.test.ts@@ -99,7 +99,7 @@ test("panel session: four lenses, synthesis, committed decision note", () => {test("backend registry renders a preference through the claude adapter", () => {const backend = resolveMemoryBackend(configPath);expect(backend.id).toBe("claude");- const parsed = backend.parseMemoryFile(+ const parsed = backend.parseMemoryEntries(["---","name: prefer_pipelines",@@ -110,7 +110,7 @@ test("backend registry renders a preference through the claude adapter", () => {"","Use pipeline() by default.",].join("\n"),- );+ )[0]!;if (parsed.kind !== "feedback") throw new Error("expected feedback parse");const rendered = backend.renderPreference({name: parsed.name,diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.tsindex bdb070c4..1a6adedf 100644--- a/tests/helpers/run-cli.ts+++ b/tests/helpers/run-cli.ts@@ -12,6 +12,8 @@ import { tmpdir } from "node:os";import { join, dirname, resolve } from "node:path";import { fileURLToPath } from "node:url";+import { main } from "../../src/cli/main.ts";+export interface RunResult {readonly stdout: string;readonly stderr: string;@@ -43,14 +45,29 @@ const RUNTIME_OVERRIDABLE_ENV = ["OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT",] as const;-export async function runCli(- args: ReadonlyArray<string>,- opts: { env?: Record<string, string>; stdin?: string; cwd?: string } = {},-): Promise<RunResult> {- const callerEnv = opts.env ?? {};- // Build the child env from process.env, then strip any runtime-resolution- // env that the caller did not explicitly pass. The caller's passed values- // — including empty strings — are honoured verbatim.+export interface RunCliOptions {+ readonly env?: Record<string, string>;+ readonly stdin?: string;+ readonly cwd?: string;+ /**+ * Force a fresh child process instead of the in-process fast path. The+ * in-process path imports `main()` once and calls it directly - two orders of+ * magnitude cheaper than spawning `bun run src/cli/main.ts` per call (that+ * re-parses and re-evaluates the whole CLI import graph every time). Set this+ * only when a test genuinely needs OS-level process isolation (real stdin, a+ * long-running server command, signal handling). Passing `stdin` implies it.+ */+ readonly subprocess?: boolean;+}++/**+ * Compute the child environment the caller's overrides produce, mirroring the+ * process-level resolution the CLI performs from `process.env`.+ */+function resolveEnv(callerEnv: Record<string, string>): {+ env: Record<string, string>;+ cleanupDir: string | null;+} {const env: Record<string, string> = { ...process.env } as Record<string, string>;for (const key of RUNTIME_OVERRIDABLE_ENV) {if (!(key in callerEnv)) delete env[key];@@ -61,6 +78,25 @@ export async function runCli(cleanupDir = mkdtempSync(join(tmpdir(), "o2b-test-"));env["OPEN_SECOND_BRAIN_CONFIG"] = join(cleanupDir, "isolated-config.yaml");}+ return { env, cleanupDir };+}++/** A `process.stdout.write`-shaped sink that appends decoded chunks to `sink`. */+function captureWrite(sink: (s: string) => void) {+ return (chunk: unknown, ...rest: unknown[]): boolean => {+ sink(typeof chunk === "string" ? chunk : Buffer.from(chunk as Uint8Array).toString("utf8"));+ const cb = rest[rest.length - 1];+ if (typeof cb === "function") (cb as () => void)();+ return true;+ };+}++/** Fresh-process invocation - the original behavior, kept for isolation cases. */+async function runCliSubprocess(+ args: ReadonlyArray<string>,+ opts: RunCliOptions,+): Promise<RunResult> {+ const { env, cleanupDir } = resolveEnv(opts.env ?? {});try {const proc = Bun.spawn(["bun", "run", CLI_ENTRY, ...args], {cwd: opts.cwd ?? ROOT,@@ -83,3 +119,62 @@ export async function runCli(if (cleanupDir !== null) rmSync(cleanupDir, { recursive: true, force: true });}}++/**+ * In-process invocation: apply the resolved env + cwd, capture stdout/stderr,+ * call `main()`, then restore everything. `main()` never calls `process.exit`+ * (that lives behind its `import.meta.main` guard) and returns an exit code, so+ * a direct call is a faithful black-box of the full parse + dispatch path. An+ * uncaught throw is mapped to code 1 with the message on stderr, matching how a+ * crashing child process would surface.+ */+async function runCliInProcess(+ args: ReadonlyArray<string>,+ opts: RunCliOptions,+): Promise<RunResult> {+ const { env, cleanupDir } = resolveEnv(opts.env ?? {});+ const savedEnv = process.env;+ const savedCwd = process.cwd();+ let stdout = "";+ let stderr = "";+ const realOut = process.stdout.write.bind(process.stdout);+ const realErr = process.stderr.write.bind(process.stderr);+ process.env = env;+ try {+ process.chdir(opts.cwd ?? ROOT);+ } catch {+ // A caller cwd that does not exist would also fail a subprocess spawn.+ }+ process.stdout.write = captureWrite((s) => (stdout += s)) as typeof process.stdout.write;+ process.stderr.write = captureWrite((s) => (stderr += s)) as typeof process.stderr.write;+ let returncode: number;+ try {+ returncode = await main(args);+ } catch (err) {+ stderr += `${(err as Error)?.stack ?? String(err)}\n`;+ returncode = 1;+ } finally {+ process.stdout.write = realOut;+ process.stderr.write = realErr;+ process.env = savedEnv;+ try {+ process.chdir(savedCwd);+ } catch {+ /* restore best-effort */+ }+ if (cleanupDir !== null) rmSync(cleanupDir, { recursive: true, force: true });+ }+ return { stdout, stderr, returncode };+}++export async function runCli(+ args: ReadonlyArray<string>,+ opts: RunCliOptions = {},+): Promise<RunResult> {+ // Real stdin or an explicit isolation request needs a child process; every+ // other command runs in-process for speed.+ if (opts.subprocess === true || opts.stdin !== undefined) {+ return runCliSubprocess(args, opts);+ }+ return runCliInProcess(args, opts);+}diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.tsindex 323babbd..94e4ab1b 100644--- a/tests/mcp/brain-tools-parity.test.ts+++ b/tests/mcp/brain-tools-parity.test.ts@@ -65,6 +65,7 @@ const FROZEN_BRAIN_TOOL_NAMES = ["brain_deep_synthesis","brain_delete_by_source","brain_derive_fact",+ "brain_distill_source","brain_doctor","brain_dream","brain_entity",diff --git a/tests/mcp/distill-tool.test.ts b/tests/mcp/distill-tool.test.tsnew file mode 100644index 00000000..599f84bf--- /dev/null+++ b/tests/mcp/distill-tool.test.ts@@ -0,0 +1,61 @@+/**+ * MCP integration test for `brain_distill_source` (t_2e2e959f). The agent+ * supplies atomic claims with optional block ids; OSB writes an idempotent+ * distillation page. Handler exercised directly with a minimal context.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import { DISTILL_TOOLS } from "../../src/mcp/brain/distill-tools.ts";+import { MCPError } from "../../src/mcp/protocol.ts";+import type { ServerContext } from "../../src/mcp/tools.ts";++let vault: string;+let configHome: string;+let ctx: ServerContext;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-distill-tool-vault-"));+ configHome = mkdtempSync(join(tmpdir(), "o2b-distill-tool-cfg-"));+ const configPath = join(configHome, "config.yaml");+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+ mkdirSync(join(vault, "Articles"), { recursive: true });+ writeFileSync(join(vault, "Articles", "src.md"), "# Src\n\nBody.\n", "utf8");+ ctx = { vault, configPath, repoRoot: null };+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+});++const handler = DISTILL_TOOLS[0]!.handler;++describe("brain_distill_source", () => {+ test("writes a distillation page and returns its path", async () => {+ const res = (await handler(ctx, {+ source_path: "Articles/src.md",+ claims: [{ text: "An atomic claim.", block: "^abc" }, { text: "Another claim." }],+ })) as { distillation_path: string; claim_count: number };+ expect(res.claim_count).toBe(2);+ const md = readFileSync(join(vault, res.distillation_path), "utf8");+ expect(md).toContain("kind: brain-distillation");+ expect(md).toContain("([[Articles/src.md#^abc]])");+ });++ test("a non-empty claims array is required", async () => {+ await expect(handler(ctx, { source_path: "Articles/src.md", claims: [] })).rejects.toThrow(+ MCPError,+ );+ });++ test("missing source_path is rejected", async () => {+ await expect(handler(ctx, { claims: [{ text: "x" }] })).rejects.toThrow(MCPError);+ });+});diff --git a/tests/mcp/ingest-tool.test.ts b/tests/mcp/ingest-tool.test.tsindex 7b123d36..793ac6ec 100644--- a/tests/mcp/ingest-tool.test.ts+++ b/tests/mcp/ingest-tool.test.ts@@ -9,6 +9,8 @@ import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";import { join } from "node:path";import { tmpdir } from "node:os";+import { mkdirSync, writeFileSync } from "node:fs";+import { bootstrapBrain } from "../../src/core/brain/init.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { listEntities } from "../../src/core/brain/entities/registry.ts";@@ -77,3 +79,38 @@ describe("brain_ingest_source", () => {).rejects.toThrow(MCPError);});});++describe("brain_ingest_batch_plan resume (t_ba1fa5f6)", () => {+ const batchPlan = INGEST_TOOLS.find((t) => t.name === "brain_ingest_batch_plan")!.handler;++ test("returns a plan_id and a resumed plan excludes ingested items", async () => {+ mkdirSync(join(vault, "Docs"), { recursive: true });+ writeFileSync(join(vault, "Docs", "a.md"), "alpha", "utf8");+ writeFileSync(join(vault, "Docs", "b.md"), "bravo", "utf8");++ const first = (await batchPlan(ctx, { source_dir: "Docs" })) as Record<string, unknown>;+ expect(first["plan_id"]).toMatch(/^[0-9a-f]{16}$/);+ expect(first["total_files"]).toBe(2);+ expect(first["resumed_completed"]).toBe(0);++ // Ingest one file through the source tool, carrying the plan id so the+ // checkpoint records it.+ await handler(ctx, {+ source_path: "Docs/a.md",+ summary: "Alpha.",+ entities: [{ category: "concept", name: "Alpha" }],+ plan_id: first["plan_id"],+ });++ const resumed = (await batchPlan(ctx, { source_dir: "Docs", resume: true })) as Record<+ string,+ unknown+ >;+ expect(resumed["plan_id"]).toBe(first["plan_id"]);+ expect(resumed["resumed_completed"]).toBe(1);+ const files = (resumed["batches"] as Array<{ files: Array<{ path: string }> }>).flatMap((b) =>+ b.files.map((f) => f.path),+ );+ expect(files).toEqual(["Docs/b.md"]);+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 6be23e64..bf4c76d6 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -291,6 +291,8 @@ describe("tool listing", () => {"brain_ingest_source",// Large-folder ingest planner (memory-signal-provenance-lifecycle A3)."brain_ingest_batch_plan",+ // Source distillation into atomic claims (ingestion-import-robustness t_2e2e959f).+ "brain_distill_source",// Source cleanup: search + delete by exact source file (C6, v1.x)."brain_search_by_source","brain_delete_by_source",@@ -587,7 +589,9 @@ describe("stdio loop", () => {// source file, memory-signal-provenance-lifecycle C6) = 95.// + brain_ingest_batch_plan (large-folder ingest planner,// memory-signal-provenance-lifecycle A3) = 96.- expect(list.result.tools.length).toBe(96);+ // + brain_distill_source (source distillation into atomic claims,+ // ingestion-import-robustness t_2e2e959f) = 97.+ expect(list.result.tools.length).toBe(97);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.tsindex a9d4a984..01829ea5 100644--- a/tests/mcp/removed-tools.test.ts+++ b/tests/mcp/removed-tools.test.ts@@ -157,5 +157,7 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn// source file, memory-signal-provenance-lifecycle C6) = 95.// + brain_ingest_batch_plan (large-folder ingest planner,// memory-signal-provenance-lifecycle A3) = 96.- expect(list.result.tools.length).toBe(96);+ // + brain_distill_source (source distillation into atomic claims,+ // ingestion-import-robustness t_2e2e959f) = 97.+ expect(list.result.tools.length).toBe(97);});