State and storage状态与存储
Where facts live between calls, who may write them, and how concurrent writers stay safe.两次调用之间数据存在哪里、谁可以写,以及多个写入方如何互不破坏。
What it is and why it exists它是什么,为什么需要它
What是什么
State is everything that outlives one model call: the run state inside a request, the conversation across requests, durable knowledge and memory, and the cursors that mark how far a background job has read.状态是比一次模型调用活得更久的一切:单次请求内的运行状态、跨请求的对话、持久化的知识与记忆,以及标记后台任务读到哪里的游标。
Why为什么
A model call has no memory. Each kind of state has a different lifetime and owner, and mixing them causes the worst bugs. The reference build's single-writer stores failed when two scheduled jobs wrote at once, and one file was corrupted.模型调用本身没有记忆。每种状态的生命周期和所有者都不同,混在一起会导致最严重的问题。参考系统早期使用单写入方的存储,两个定时任务同时写入时出了故障,其中一个文件被损坏。
How it works工作原理
- Run state is a dict passed through the executor. Merge rules say which keys accumulate and which overwrite.运行状态是在执行器中传递的字典。合并规则规定哪些键累加、哪些键覆盖。
- Conversation state is rows keyed by user and thread.对话状态是以用户和会话为键的数据行。
- Durable state is tables whose name prefix shows the owner: kb for ingested, brain for learned, mem for per-user.持久状态是表,表名前缀标明归属:kb 是入库内容,brain 是学到的内容,mem 是每个用户的记忆。
- Background jobs keep a cursor so they resume where they stopped and never handle a log line twice.后台任务保存游标,中断后从上次的位置继续,同一行日志绝不处理两次。
Where it sits in the build order它在搭建顺序中的位置
Needs first前置模块
Nothing. You can start here.没有。可以从这里开始。
Unlocks解锁
- RAG and knowledge graphRAG 与知识图谱Chunks, vectors, and edges need tables that survive a nightly writer and concurrent readers.文本块、向量和边需要存在表里,并且要经得住夜间写入和并发读取。
- Harness engineeringHarness 工程Concurrent tool results have to merge into one conversation without overwriting each other. The merge rules exist before the loop that relies on them.并发的工具结果必须合并进同一个对话而不互相覆盖。合并规则要先于依赖它的循环而存在。
- Memory记忆Memory is durable state with concurrent writers: live chats and background jobs. It needs the tables and the connection settings from the state module.记忆是有并发写入方的持久状态:实时对话和后台任务都会写。它需要状态模块里的表和连接设置。
In the reference build在参考系统中
| Path路径 | Role作用 |
|---|---|
| apps/agent-server/graph.py | merge_state: the rules for run state.merge_state:运行状态的合并规则。 |
| apps/agent-server/pgstore.py | Connection handling and schema setup for Postgres.Postgres 的连接管理和建表。 |
| apps/agent-server/pgschema.sql | Schemas by owner: learned knowledge, file ledger, chunk indexes.按归属划分的 schema:学到的知识、文件台账、文本块索引。 |
| apps/agent-server/conversation_store.py | Threads and messages across requests.跨请求的会话和消息。 |
Process map流程图
Three lifetimes, three places三种生命周期,三个存放位置
- 1Run state运行状态Lives for one request. A dict. Dies when the answer is returned.只存在于一次请求内。是一个字典。回答返回后即消失。
- 2Conversation对话Lives for a thread. Rows with user, thread, role, content.存在于一个会话期间。数据行包含用户、会话、角色、内容。
- 3Ingested knowledge入库的知识kb tables. Written by the indexer. Rebuildable from the bank.kb 表。由索引程序写入。可以从知识库重建。
- 4Learned knowledge学到的知识brain tables. Written by the nightly loop. Can be dropped without touching kb.brain 表。由夜间任务写入。删除它不影响 kb。
- 5User memory用户记忆mem tables. Every row carries a partition.mem 表。每一行都带有分区标识。
- 6Cursors游标One number per job: how far into a log it has read.每个任务一个数字:它读到日志的哪个位置。
Build steps搭建步骤
Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。
- 1Name each kind of state and its owner给每种状态命名,并确定归属
- 2Open the database so concurrent access works以支持并发访问的方式打开数据库
- 3Create the schema, grouped by owner按归属分组建表
- 4Define merge rules for run state定义运行状态的合并规则
- 5Test concurrent writers before you depend on them在依赖并发写入之前先测试
- 6Give every background job a cursor给每个后台任务一个游标
- 7Check that learned state can be dropped alone确认学到的状态可以单独清除
- 8Move to Postgres when the workload asks for it当负载需要时迁移到 Postgres
01Name each kind of state and its owner给每种状态命名,并确定归属
Do this操作
- List what must outlive a request. For each item write: lifetime, the one job that writes it, who reads it.列出哪些数据必须活过一次请求。对每一项写下:生命周期、唯一负责写入的任务、谁来读。
- Group them under prefixes: kb, brain, mem, conv, job.按前缀分组:kb、brain、mem、conv、job。
- State and storage状态与存储 2: Open the database so concurrent access works以支持并发访问的方式打开数据库 (the list of jobs that will write at the same time会同时写入的任务清单)
- State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表 (prefixes and owners前缀和归属)
02Open the database so concurrent access works以支持并发访问的方式打开数据库
- the list of jobs that will write at the same time会同时写入的任务清单 ← State and storage状态与存储 1: Name each kind of state and its owner给每种状态命名,并确定归属
Do this操作
- Enable write-ahead logging so readers proceed while a writer writes.开启预写日志(WAL),这样写入时读取不受阻塞。
- Set a busy timeout so a second writer waits its turn.设置 busy timeout,让第二个写入方排队等待。
- Use one `connect()` function everywhere.全系统只用一个 `connect()` 函数。
def connect(path: Path) -> sqlite3.Connection:
"""WAL lets readers proceed while one writer writes. busy_timeout makes a second
writer wait its turn instead of failing with 'database is locked'."""
db = sqlite3.connect(str(path), timeout=30, check_same_thread=False)
db.execute("PRAGMA journal_mode=WAL")
db.execute("PRAGMA busy_timeout=30000")
db.execute("PRAGMA foreign_keys=ON")
return db- State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表 (a connection数据库连接)
- State and storage状态与存储 5: Test concurrent writers before you depend on them在依赖并发写入之前先测试 (WAL and busy timeoutWAL 和 busy timeout)
03Create the schema, grouped by owner按归属分组建表
- prefixes and owners前缀和归属 ← State and storage状态与存储 1: Name each kind of state and its owner给每种状态命名,并确定归属
- a connection数据库连接 ← State and storage状态与存储 2: Open the database so concurrent access works以支持并发访问的方式打开数据库
Do this操作
- Read the schema below. Find the prefix of each table.阅读下面的表结构,找出每张表的前缀。
- Note `chunk_id` is `<source>::<n>`. Retrieval and evals rely on that format.注意 `chunk_id` 的格式是 `<source>::<n>`。检索和评估都依赖这个格式。
- Make schema creation idempotent and call it on every start.让建表操作幂等,并在每次启动时调用。
SCHEMA = """
CREATE TABLE IF NOT EXISTS kb_chunks (
chunk_id TEXT PRIMARY KEY, -- "<source>::<n>"
collection TEXT NOT NULL, source TEXT NOT NULL, chunk_index INTEGER NOT NULL,
text TEXT NOT NULL, context TEXT, embedding TEXT, -- JSON list of floats
tier INTEGER NOT NULL DEFAULT 3, retired INTEGER NOT NULL DEFAULT 0, heldout INTEGER NOT NULL DEFAULT 0);
CREATE VIRTUAL TABLE IF NOT EXISTS kb_fts USING fts5(chunk_id UNINDEXED, collection UNINDEXED, body);
CREATE TABLE IF NOT EXISTS kb_edges (
from_key TEXT NOT NULL, to_chunk TEXT NOT NULL, relation TEXT NOT NULL, -- 'defines' | 'cites'
PRIMARY KEY (from_key, to_chunk, relation));
CREATE TABLE IF NOT EXISTS brain_claims (
claim_id INTEGER PRIMARY KEY, kind TEXT NOT NULL, text TEXT NOT NULL, source_ref TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'candidate', -- candidate | trusted | unsupported | retired
formed_at TEXT NOT NULL, UNIQUE (kind, text));
CREATE TABLE IF NOT EXISTS brain_evidence (
claim_id INTEGER NOT NULL REFERENCES brain_claims(claim_id), origin TEXT NOT NULL, day TEXT NOT NULL,
PRIMARY KEY (claim_id, origin, day));
CREATE TABLE IF NOT EXISTS mem_facts (
partition TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, updated_at REAL NOT NULL,
PRIMARY KEY (partition, key));
CREATE TABLE IF NOT EXISTS conv_turns (
turn_id INTEGER PRIMARY KEY, partition TEXT NOT NULL, thread TEXT NOT NULL,
role TEXT NOT NULL, content TEXT NOT NULL, ts REAL NOT NULL);
CREATE TABLE IF NOT EXISTS job_cursors (job TEXT PRIMARY KEY, position INTEGER NOT NULL);
"""
def ensure_schema(db: sqlite3.Connection) -> None:
db.executescript(SCHEMA) # idempotent: safe to run on every start
db.commit()python3 -m labs.m04_state.demo1 schema, applied twice : brain_claims, brain_evidence, conv_turns, job_cursors, kb_chunks, kb_edges, kb_fts, mem_facts- State and storage状态与存储 5: Test concurrent writers before you depend on them在依赖并发写入之前先测试 (a table to write to可写入的表)
- State and storage状态与存储 6: Give every background job a cursor给每个后台任务一个游标 (the job_cursors tablejob_cursors 表)
- State and storage状态与存储 7: Check that learned state can be dropped alone确认学到的状态可以单独清除 (prefixes that mark ownership标明归属的前缀)
- RAG and knowledge graphRAG 与知识图谱 2: Embed and load, driven by the ledger由台账驱动,向量化并入库 (kb_chunks and kb_fts tableskb_chunks 和 kb_fts 表)
- RAG and knowledge graphRAG 与知识图谱 7: Build graph edges at index time在索引阶段建立图的边 (the kb_edges tablekb_edges 表)
- Memory记忆 2: Store facts and build the briefing保存事实并生成摘要 (the mem_facts tablemem_facts 表)
- Evaluation评估 3: Seal the test material before anything learns在任何学习发生之前封存测试材料 (the heldout column on chunks文本块上的 heldout 列)
- Self-evolving agents自进化智能体 3: Record evidence so repetition cannot pose as support记录证据,不让重复冒充支持 (brain_claims and brain_evidencebrain_claims 和 brain_evidence 表)
- Operations and deployment运维与部署 6: Back up what cannot be reproduced, and test the restore备份无法重新生成的东西,并测试恢复 (the tables to count要统计行数的表)
04Define merge rules for run state定义运行状态的合并规则
Do this操作
- Keys ending in `_append` extend a list.以 `_append` 结尾的键向列表追加。
- Counter keys add.计数类的键做加法。
- Every other key overwrites. That is a decision: last writer wins.其余的键直接覆盖。这是有意的决定:后写的生效。
EXTEND_KEYS = {"messages_append", "tools_used_append", "findings_append"} # concurrent nodes each add items
SUM_KEYS = {"prompt_tokens", "completion_tokens", "model_calls"} # concurrent nodes each add a number
def merge_state(state: dict, update: dict) -> None:
"""Apply one node's update to shared run state without losing a sibling's update."""
for key, value in update.items():
if key in EXTEND_KEYS:
state.setdefault(key[: -len("_append")], []).extend(value)
elif key in SUM_KEYS:
state[key] = state.get(key, 0) + value
else:
state[key] = value # last writer wins, on purpose2 two nodes merged : ['q', 'A', 'B'] model_calls = 2 last_node = tool:b- Harness engineeringHarness 工程 2: Write the wave executor编写波次执行器 (merge_state()merge_state())
- Multi-agent patterns多智能体模式 3: Fan out, fan in, synthesize扇出、扇入、汇总 (an append key for findings用于结论的追加键)
05Test concurrent writers before you depend on them在依赖并发写入之前先测试
- WAL and busy timeoutWAL 和 busy timeout ← State and storage状态与存储 2: Open the database so concurrent access works以支持并发访问的方式打开数据库
- a table to write to可写入的表 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
Do this操作
- Start three threads, each with its own connection, each inserting 200 rows.启动三个线程,各用自己的连接,各插入 200 行。
- Count the rows.统计行数。
3 three writers at once : 600 rows, none lost- State and storage状态与存储 8: Move to Postgres when the workload asks for it当负载需要时迁移到 Postgres (the test that tells you the move worked用来确认迁移成功的测试)
- Memory记忆 3: Write the record pipeline, after the answer编写记录流程,放在回答之后 (proof that a background writer is safe后台写入安全的证据)
06Give every background job a cursor给每个后台任务一个游标
- the job_cursors tablejob_cursors 表 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
Do this操作
- Store one byte offset per job name.为每个任务名保存一个字节偏移量。
- Read from the offset to the last complete line. Advance the offset in the same call.从偏移量读到最后一个完整的行,并在同一次调用中推进偏移量。
- If the file is now smaller than the stored offset, it was rotated: start again from 0. Without this check the job skips every line written after rotation. Lab 15 shows it.如果文件现在比保存的偏移量还小,说明它被轮转过:从 0 重新开始。没有这项检查,任务会跳过轮转之后写入的每一行。lab 15 演示了这一点。
- Write logs as JSON lines, one record per line.日志使用 JSON Lines 格式,每行一条记录。
def read_new_lines(db: sqlite3.Connection, job: str, log_path: Path) -> list:
"""Return log lines this job has not seen, then advance its cursor. A job that
crashes and restarts resumes where it stopped and never handles a line twice."""
row = db.execute("SELECT position FROM job_cursors WHERE job=?", (job,)).fetchone()
pos = row[0] if row else 0
if not log_path.exists():
return []
if log_path.stat().st_size < pos: # the file was rotated (copied, then truncated): start over
pos = 0
with log_path.open("rb") as f:
f.seek(pos)
data = f.read()
end = pos + data.rfind(b"\n") + 1 if b"\n" in data else pos # only whole lines
lines = [json.loads(x) for x in data[: end - pos].decode().splitlines() if x.strip()]
db.execute("INSERT INTO job_cursors VALUES (?,?) ON CONFLICT(job) DO UPDATE SET position=excluded.position",
(job, end))
db.commit()
return lines4 cursor : 3 lines, then 1 new, then 0- Harness engineeringHarness 工程 7: Assemble run(): guard, retry, log, record组装 run():护栏、重试、日志、记录 (append_log() for JSON-lines logs用于 JSON Lines 日志的 append_log())
- Self-evolving agents自进化智能体 1: Check the four preconditions检查四项前提条件 (read_new_lines()read_new_lines())
- Operations and deployment运维与部署 7: Rotate logs and keep signal apart from noise轮转日志,并把信号与噪音分开 (cursors that must survive rotation需要在轮转后依然有效的游标)
07Check that learned state can be dropped alone确认学到的状态可以单独清除
- prefixes that mark ownership标明归属的前缀 ← State and storage状态与存储 3: Create the schema, grouped by owner按归属分组建表
Do this操作
- Drop every table with the brain prefix.删除所有以 brain 为前缀的表。
- Confirm the kb tables are untouched.确认 kb 表没有受影响。
5 dropped brain_* tables: 3 of 3 kb_* tables still there- Self-evolving agents自进化智能体 1: Check the four preconditions检查四项前提条件 (the tested way to undo learning经过验证的撤销学习的方法)
- Self-evolving agents自进化智能体 9: Keep rollback one command away让回滚只需一条命令 (dropping learned tables删除学到的表)
08Move to Postgres when the workload asks for it当负载需要时迁移到 Postgres
- the test that tells you the move worked用来确认迁移成功的测试 ← State and storage状态与存储 5: Test concurrent writers before you depend on them在依赖并发写入之前先测试
Do this操作
- Start Postgres with the pgvector extension. On your machine use the container command below. The lab starts a private throwaway cluster instead.启动带 pgvector 扩展的 Postgres。在你自己的机器上用下面的容器命令。lab 则会启动一个用完即删的私有集群。
- Map each table prefix to a Postgres schema of the same name: kb, brain, mem.把每个表前缀映射为同名的 Postgres schema:kb、brain、mem。
- Keep the same column names so calling code keeps its SQL.保持列名不变,这样调用代码的 SQL 不用改。
- Run the concurrent-writer test against Postgres. Each writer uses its own connection.在 Postgres 上运行并发写入测试。每个写入方使用自己的连接。
def concurrent_writers(dsn: str, writers=("chat", "nightly-job", "eval-job"), rows: int = 200) -> int:
"""The state-module writer test, against Postgres. Each writer has its own connection."""
errors = []
def write(name):
try:
with psycopg.connect(dsn) as c:
for i in range(rows):
c.execute("INSERT INTO mem.turns (partition, thread, role, content) VALUES (%s,'t1','user',%s)",
(name, f"{name}-{i}"))
c.commit()
except Exception as e: # a lock error would land here
errors.append(f"{name}: {e}")
ts = [threading.Thread(target=write, args=(n,)) for n in writers]
[t.start() for t in ts]
[t.join() for t in ts]
if errors:
raise RuntimeError("; ".join(errors))
with psycopg.connect(dsn) as c:
return c.execute("SELECT count(*) FROM mem.turns").fetchone()[0]docker run -d --name agentdb -e POSTGRES_PASSWORD=change-me -p 127.0.0.1:5432:5432 pgvector/pgvector:pg17
psql -h 127.0.0.1 -U postgres -c "CREATE EXTENSION IF NOT EXISTS vector;"
psql -h 127.0.0.1 -U postgres -c "CREATE SCHEMA kb; CREATE SCHEMA brain; CREATE SCHEMA mem;"
# "delete everything the agent taught itself" becomes: DROP SCHEMA brain CASCADE;The container command was not run by the labs. The lab ran the same schema and writer test on a local Postgres 16 server.lab 没有运行这条容器命令。lab 在本地的 Postgres 16 上运行了同样的 schema 和写入测试。
PG_RUN_AS=<ordinary user, only when running as root> python3 -m labs.m05_rag.pg1 cluster up, pgvector 0.6.0 | schemas, applied twice: brain, kb, mem
2 three writers at once : 600 rows, no lock errors- RAG and knowledge graphRAG 与知识图谱 10: Production form: Postgres with pgvector生产形态:Postgres 加 pgvector (a Postgres database with the vector extension带向量扩展的 Postgres 数据库)
How it works with the other parts它如何与其他部分协作
- Harness engineeringHarness 工程The wave executor calls merge_state after every wave.波次执行器在每一波结束后调用 merge_state。
- RAG and knowledge graphRAG 与知识图谱Chunks, vectors, and graph edges live in the kb tables.文本块、向量和图的边存放在 kb 表里。
- Memory记忆Facts and conversation turns live in mem and conv tables, always with a partition.事实和对话轮次存放在 mem 和 conv 表里,始终带有分区。
- Self-evolving agents自进化智能体Claims and their evidence live in brain tables. Log readers use cursors.论断及其证据存放在 brain 表里。读日志的任务使用游标。
What went wrong in the real build真实搭建中踩过的坑
Two jobs wrote one single-writer file两个任务同时写一个单写入方文件
- What happened发生了什么
- The daily cycle and the learner collided at the same minute two nights running. One night the database was corrupted.日常任务和学习任务连续两晚在同一分钟撞在一起。其中一晚数据库被损坏。
- Fix修复
- A store with real concurrency control, and an explicit lock for jobs that must not overlap.换用真正支持并发控制的存储,并对不能重叠的任务显式加锁。
- Lesson教训
- Find out how your store handles a second writer before you have one.在出现第二个写入方之前,先弄清你的存储会如何处理它。
A findings file that was 97 percent duplicates一个 97% 都是重复内容的发现记录文件
- What happened发生了什么
- A job re-recorded the same 26 findings about 11,000 times, once every hour.一个任务每小时把同样的 26 条发现重新记录一遍,累计约 11,000 次。
- Fix修复
- A cursor per job, and a uniqueness rule on what is recorded.每个任务一个游标,并对记录内容加唯一性约束。
- Lesson教训
- A job without a cursor counts its own repetition as evidence.没有游标的任务,会把自己的重复劳动当成证据。
The same idea on other platforms同样的思路在其他平台上
| Platform平台 | How this module maps本模块如何对应 |
|---|---|
| Databricks | Delta tables for durable state. Lakebase for Postgres-style transactional state such as threads and checkpoints. Run state lives in your agent code.持久状态用 Delta 表。会话和检查点这类事务型状态用 Lakebase(Postgres 风格)。运行状态在你的智能体代码里。 |
| IBM watsonx | Orchestrate manages thread state for its agents. Durable domain state goes in watsonx.data or a database you connect.Orchestrate 为其智能体管理会话状态。持久的业务状态放在 watsonx.data 或你接入的数据库里。 |
| Codex | Session history is managed by the tool and can be resumed. Durable project state is files in the repo.会话历史由工具管理,可以恢复。持久的项目状态是仓库里的文件。 |
| Cursor | Chat history is managed by the editor. Durable state is files, plus whatever your MCP servers store.聊天历史由编辑器管理。持久状态是文件,以及你的 MCP 服务自己存的数据。 |
| Claude Code / Agent SDK | Sessions can be resumed and the SDK exposes session ids. Durable state is files and your own stores.会话可以恢复,SDK 提供会话 ID。持久状态是文件和你自己的存储。 |
| Another machine | SQLite with WAL is enough for one machine. Postgres in a container gives the same layout with stronger guarantees.单机用开启 WAL 的 SQLite 就够了。容器里的 Postgres 结构相同,保障更强。 |
Step-by-step guides per platform各平台的分步指南
Explain it back讲给自己听
Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。
Name three kinds of state and their lifetimes.说出三种状态及其生命周期。
Why are merge rules part of storage and not part of the harness?为什么合并规则属于存储,而不属于 Harness?
Why build the cursor now when no job reads logs yet?现在还没有任务读日志,为什么要先做游标?
How do you delete everything the agent taught itself, and nothing else?如何只删除智能体自己学到的内容,而不影响其他?
Terms术语
| WALWAL(预写日志) | Write-ahead logging. Changes go to a log first, so readers are not blocked by a writer.修改先写入日志,因此读取不会被写入阻塞。 |
| Cursor游标 | A saved position in a log, one per job.日志中保存下来的位置,每个任务一个。 |
| Partition分区 | The value, usually a user id, that scopes every memory read and write.限定每次记忆读写范围的值,通常是用户 ID。 |
From the live build来自实时构建
Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。
- Conversation learner ignores eval threads; report treats findings from unchanged threads as no new traffic
- Memory store on Postgres, second attempt (qualified upsert columns); recall skips the current thread, memory briefing cannot fail a request
- Memory store on Postgres (mem schema), recall skips the current thread, memory briefing cannot fail a request
- Conversation recall: mem.turns index, recall_conversations tool, recall gate in the daily cycle
- Audit fixes: self-gap dedupe, SQLite stores in the nightly backup; agent quiz
- Tests: isolate conversations.db and the retrieval trace
- Baseline 2026-09-30: code and scripts after the Postgres cutover, pinned MCP servers, nightly pg_dump
- the quarantined learned-knowledge store (BRAIN-ARCHITECTURE.md §3.1). Deliberately modelled on memory_store.py, right down to the conventions: contextmanager connection, schema-if-not-exists, 0600 permissions, PRAGMA journal_mode=TRUNCATE, and idempotent additive migrations via ...
- learn from what people actually said. python3 nightly/conversation_learn.py # report, write nothing python3 nightly/conversation_learn.py --apply # record python3 nightly/conversation_learn.py --all # ignore the cursor WHY THIS EXISTS =============== This system had three ways ...
- the agent can look up what was said before (2026-10-01). Thin wrapper over conversation_index.search(). Registered after nightly/recall_eval.py passed its gate (see evals/memory/history.jsonl).
- searchable index of past conversations (2026-10-01). The audit scored memory 2 of 5: conversations.db keeps every exchange for 90 days and nothing can search it, so "what did we decide about X last week" has no answer.
- copy memory.db into Postgres schema mem (2026-10-01). Idempotent. agent:self observations are collapsed to the newest row per distinct finding (10,998 rows were 26 findings re-logged hourly). venv/bin/python3 ../ops/migrate_memory_pg.py # migrate + verify
- collects every tool into the two things agent_loop.py needs: the OpenAI-style schema list to hand Ollama (so the model knows what it can call), and a name -> async-callable map to actually execute a call.
- nightly dump of the knowledge store (2026-09-30). WHAT: pg_dump --format=custom of the whole build-host database (brain.* learned atoms, kb.* file ledger, kb_finance / kb_k12 chunk vectors).
- regression tests for the learned-knowledge store. Run: python3 test_brain_store.py These are not exhaustive unit tests; they are guards on the SIX properties that make brain_store.py safe to run unattended.