Metadata-Version: 2.4
Name: seren-corpus-callosum
Version: 5.10.0
Summary: Read-only N-store memory federation for Seren. The callosum - fans Loci, SerenMemory, and any number more into one RRF-merged recall surface.
Author: Chad Roesler
License: AGPL-3.0-or-later
Project-URL: Homepage, https://github.com/ChadRoesler/SerenCorpusCallosum
Project-URL: Repository, https://github.com/ChadRoesler/SerenCorpusCallosum
Project-URL: Bug Tracker, https://github.com/ChadRoesler/SerenCorpusCallosum/issues
Keywords: llm,memory,federation,rrf,reciprocal-rank-fusion,seren,callosum
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: fastapi>=0.115.0
Requires-Dist: uvicorn[standard]>=0.32.0
Requires-Dist: pydantic>=2.9.0
Requires-Dist: pyyaml>=6.0.2
Requires-Dist: httpx>=0.27.0
Requires-Dist: seren-meninges<7,>=6.0.0
Requires-Dist: seren-sinew<6,>=5.3.0
Provides-Extra: mcp
Requires-Dist: mcp<2,>=1.0; extra == "mcp"
Provides-Extra: corp
Requires-Dist: truststore>=0.9; extra == "corp"
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: httpx2>=2.3; extra == "dev"
Provides-Extra: updates
Provides-Extra: peers
Requires-Dist: seren-memory>=5.0; extra == "peers"
Requires-Dist: seren-loci>=5.0; extra == "peers"
Dynamic: license-file

# SerenCorpusCallosum

**The callosum.** A read-only fan that federates *N* memory stores into one ranked recall surface. Left brain ([SerenLoci](https://github.com/ChadRoesler/SerenLoci) - structured facts) plus right brain ([SerenMemory](https://github.com/ChadRoesler/SerenMemory) - episodic memory) plus however many more you hook in - merged into a single ordered list you can hand to a model.

It owns no store of its own. It remembers nothing. It only fans, floors, and merges what the hemispheres hand back. That read-only-by-construction shape is the whole point: the callosum is glue, not a place data lives.

---

## Why Reciprocal Rank Fusion (and not "just sort by score")

Every store in this family can change its embedder independently - both SerenMemory and SerenLoci ship embedder-migration. The moment two stores run different embedders, their raw distances and scores live in **different, incomparable number spaces**. Sorting a merged list by those scores is comparing apples to a slightly different apple every time someone migrates a model.

So the callosum never reads magnitudes. It reads only each store's **rank ordering** - position 1, 2, 3 within its own results - and merges with Reciprocal Rank Fusion:

```
score(hit) = weight_of_store / (k + rank_in_store)      # k = 60
```

That's **embedder-agnostic by construction**: rescale any store's scores however you like, the *order* is untouched, so the merge is untouched. There's a test that proves exactly this (`test_embedder_change_does_not_perturb_order`) - multiply one store's magnitudes by an arbitrary factor and the fused ranking comes out byte-identical.

Two per-store knobs decide how much a store is trusted (the federation has fifteen more; `GET /stores` lists the ones `POST /configure` honours as `supported_knobs`):

- **`weight`** (per store) - the one cross-store trust lever. Trust facts more than episodes? Give Loci a higher weight.
- **`floor`** (per store) - a relevance floor applied *before* fusion, so "rank 1 of a bag of garbage" can't sneak to the top. Default 0 (trust the store's own ordering); raise toward ~0.3 if a store is noisy.

---

## Implementation architecture

### Federation engine

The `Federation` class owns the fan-out. On a search request it:

1. **Fans out** - dispatches the query to every active store in parallel, each via its adapter, with a per-store timeout.
2. **Floors** - discards hits whose `base_relevance` is below the store's configured floor *before* ranking.
3. **Ranks** - sorts each store's survivors by native score descending, assigns rank order.
4. **Fuses** - applies RRF across all stores: `Σ weight / (k + rank_in_store)`.
5. **Ranks by rank and weight only.** The authority margin that used to sit here (a clearly-confident store's top hit promoted to lead) was removed on 7 Nov 2026: measured in Probe's harness across 1,152 knob combinations on five corpora, it never changed a packet, because 1/(1+d) squeezes MiniLM's useful range into 0.45 to 0.59 and no store ever looks confident. A config or `/configure` body that still names `authority_margin` is warned about and the key ignored (`/configure` answers with it under `ignored`).
6. **Truncates** - returns the top `n_results`; or, with `budget_tokens` (the request's, else `federation.budget_tokens`), **packs a page**: every row that fits in that many estimated tokens, in fused order, `min_per_store` seating each store on the page, an oversize row skipped rather than ending the page, and the edges and hop hits below packed into what is left. The response reports `budget_tokens` and the packet's estimated `tokens`.

A slow or down store degrades the result but never takes the call down with it - and the response says so: `stores_searched` is the stores that answered (an empty answer counts), `failed` names each store that was fanned and did not answer with why (timeout, refused, an HTTP error), and `skipped` is a store that was never bound (a config error). A timeout and "knows nothing" are different facts.

7. **Satellite edges** - a SerenMemory core hit carries `metadata.surroundings` (satellite count, what it superseded); its newest satellites and the superseded core are appended after the packet as marked edges (`source: satellite-edge` / `supersedes-edge`, `edge_of` = the core, score 0.0), budget `satellite_budget` shared round-robin across the packet's cores, before the topic edges. On a page (a search with `budget_tokens`) they are given room instead of a count: up to `satellite_share` of the page (a quarter), which grows with the page, none at or under `satellite_share_from` tokens (250) and all of it from `satellite_share_full` (750), for the top `satellite_top` cores (5), `satellites_per_core` each (5), `satellite_order` `recent` or `match`. Measured at four page sizes on two sets: no size scored under the old count, and on a 1,000-token page the questions answered by an episode went from 0.62 to 0.81 on one set and from 0.50 to 0.83 on the other. The over-fetch each store is asked for is clamped to what its contract accepts (Memory: 50).
8. **The episode is the row** (Memory store option `episode_rows`, 30 Oct 2026). When Memory lifted a core in on the strength of an episode (`matched_via`), the row the reader gets is the episode's text, the 40 tokens that matched, and the core by id (`metadata.row: episode`, `core_id`, `core_tokens`; the hit's id stays the core's, so `get_memory` and the graders still find it). The core's 200-token retelling is asked for, not read first: on a persona store a 1,000-token page held four or five fat cores with the matching episode buried in metadata, 8 of 33 hard misses on one real store's set. Off by default until Probe's harness has scored it beside the old shape; `options: {episode_rows: true}` on the Memory store turns it on, and `row_cost` then counts the episode alone.

### Adapter layer

Each store type has a corresponding adapter class. Adapters translate the store's native response shape into a uniform `StoreHit`:

| Adapter | Store type | What it does |
|---------|-----------|-------------|
| `SerenMemoryAdapter` | `seren_memory` | Calls `POST /search` on the memory service, maps `content`/`score`/`metadata` into hits |
| `SerenLociAdapter` | `seren_loci` | Calls `POST /search` on the loci service, maps `content`/`score`/`metadata` from the fact's `value` and `why` |

One adapter covers every store that speaks the same protocol - adding a SerenMemory-speaking store is a config entry, not a code change.

### Overlay system

Stores come from two sources merged at startup:

- **Base stores** - declared in the hand-authored yaml config. Config-owned; the Bridge UI won't delete them (it points you back at the file instead).
- **Managed stores** - added via the Bridge viewer's **+ Add store** form, persisted in a separate `runtime-stores.json` **overlay** file. Removable from the UI with the **✕** button.

Base always wins a name collision, so the overlay can never quietly shadow something you hand-wrote. The overlay path defaults to a sibling of the config file; override with `SEREN_SCC_RUNTIME_STORES` env var.

### Learned state across a restart

The Callosum learns two things from its own traffic: each store's habit (how close its best hit usually comes, which `habit_floor` and the "unusually close" ruler read) and the names tally (which names are on nearly everything, and so say nothing). Both start empty, and need about 20 questions per store and 200 rows before they do anything, so they are kept across a restart.

By default they are kept in `learned-state.json` beside the config file, the way the runtime overlay sits beside it. To put them elsewhere, or keep nothing, set `state_path` at the top level of the yaml (or `SEREN_SCC_STATE_PATH`, which wins):

```yaml
state_path: /var/lib/seren/callosum-learned.json   # somewhere else
# state_path: off                                  # keep nothing ("" works too)
```

With no config file (a config built in code, tests), nothing is kept.

The file is one small JSON snapshot, written atomically, at most every two minutes and only when something new was learned, and again on shutdown. It is read back at start; a missing, unreadable or older-shaped file is a cold start, never a crash. A store's habit comes back only if the store still has the same `url`.

**A habit follows its store's embedder.** Distances are in the units of the embedder that made them, so a habit learned under one embedder is wrong for another. Each store is asked which embedder it runs (`GET /` on the store: Memory's `embedding_model`, Loci's `embedder`) at start and every two minutes, whether or not anything is kept, and the name is saved with the habit. A store that names a different embedder than its habit was learned under has that habit forgotten and learned again from the next questions. A store that cannot be reached, or names no embedder, changes nothing.

`GET /stores` reports all of it under `learned`: the path, whether it was loaded and when, when it was last saved, and per store its `embedder` and `habit_reset_at`.

### Edges system (optional)

When `edges_enabled: true`, the federation appends topic-association edges after fusion. For each hit in the fused list, the edges system looks up topically related entries from *other* stores and appends them as additional results (up to `edge_budget`). This surfaces cross-store connections - a Loci fact about a project's coding convention might pull in a Memory entry about a related discussion.

Edges are purely additive: they never replace or re-rank the fused list, only extend it. A disabled edges config or a store that doesn't support topic queries degrades gracefully.

---

## Dynamic runtime configuration

Federation parameters can be tuned at runtime without a restart via `POST /configure`:

```http
POST /configure
{
  "k": 30,
  "fusion_mode": "rrf_pct",
  "min_per_store": 3,
  "edges_enabled": false,
  "edge_budget": 0,
  "n_results": 25,
  "budget_tokens": 1000,
  "fetch_multiplier": 4,
  "per_store_timeout_s": 10.0,
  "stores": [
    {"name": "facts", "weight": 2.0, "floor": 0.1}
  ]
}
```

All fields are optional - only supplied fields are changed. The live Federation is rebuilt immediately so the next `/search` picks up the new values. Per-store overrides mutate `weight`/`floor` on matching stores; an unknown store name returns 404, an invalid `fusion_mode` returns 422.

---

## The Sky

The viewer's **Sky** tab puts both hemispheres in one picture. Loci's city is
on the ground: a tower per project, a floor per fact, and skyways where one
fact rests on another. Memory's nebula is its night sky: every core and
satellite, placed by what it means. `GET /sky` (read-only) fetches the two maps
through the stores this callosum already fans, with their own bearers: Loci's
`GET /city` and Memory's `GET /long/map`, the first enabled store of each kind.
A store that can't be reached leaves its half empty and `failed` says why.

The city stands the shared towers first (`*`, then `seren`). One more project
can be set apart beside them, in a warm hue of its own: name it with
`home_project` at the top level of the yaml (or `SEREN_SCC_HOME_PROJECT`).
Blank, the default, sets none apart. `GET /sky` carries it as `home_project`.

The Sky also does what the callosum does. Ask a question and it runs the same
`/search` as the Search tab: the facts that answer light up in the city, the
memories that answer flare in the sky, and light runs between every fact and
every memory in the answer. Short- and near-term hits aren't in the sky, and
the answer says how many there were. Its 3D library (three.js r159, MIT) is
vendored in `viewer/vendor/` and served under `/viewer/` like the page.

---

## Tests

| Test file | What it covers |
|-----------|----------------|
| `tests/test_app.py` | 5 tests - HTTP search route, health/root, bearer auth, unknown-store survival, config loading from defaults/env |
| `tests/test_federation.py` | 9 tests - fan across stores, dead/slow store graceful degradation, per-store floor, weight-based ranking, unknown-store skip, empty config |
| `tests/test_fusion.py` | 28 tests - RRF fusion, embedder-agnostic ranking, percentile/rrf_pct modes, per-store quota/min_per_store |
| `tests/test_edges.py` | 7 tests - topic-association edges appended after fusion, edge budget cap, disabled mode, Loci skipped (no topics), failure degrades gracefully |
| `tests/test_adapters.py` | 6 tests - SerenMemory + SerenLoci adapter response mapping, search-path override, dispatch by type, empty/missing hits safe |
| `tests/test_stores.py` | 10 tests - stores endpoint, bridge viewer, add/delete managed stores, unknown-type rejection, duplicate rejection, blank-field rejection, base-store delete refused, missing 404 |
| `tests/test_overlay.py` | 5 tests - runtime overlay load/add/remove, corrupt overlay degrades to empty, env override |
| `tests/test_mcp_mount.py` | 2 tests - MCP mount requires federation, succeeds and exposes session manager |
| `tests/test_mcp_tools.py` | 4 tests - MCP search tool returns full provenance, surfaces skipped stores, default n_results |
| `tests/test_honest_fan.py` | 13 tests - the over-fetch clamped to what a store accepts; stores_searched = answered and `failed` with why (route and MCP tool); the health record survives /configure and store changes; a new timeout reaches the transport; satellite and superseded-core edges |
| `tests/test_exposure_is_wired.py` | 3 tests - a host beyond loopback with no bearer refuses to start |
| `tests/test_configure.py` | 9 tests - federation-level knobs (k, fusion_mode, edges, n_results, fetch, timeout), per-store weight/floor overrides, unknown store → 404, invalid fusion_mode → 422, empty body, partial updates keep untouched fields, bearer auth enforced |

```bash
pytest tests/
```

---

## The family

| Service | Role | Port |
|---------|------|------|
| [SerenMemory](https://github.com/ChadRoesler/SerenMemory) | right brain - episodic, consolidated memory | 7420 |
| [SerenMargin](https://github.com/ChadRoesler/SerenMargin) | private notes-to-self (opt-in) | 7421 |
| [SerenLoci](https://github.com/ChadRoesler/SerenLoci) | left brain - keyed, deterministic facts | 7422 |
| **SerenCorpusCallosum** | **the fan over all of them** | **7423** |

## License

AGPL-3.0-or-later.
