Compaction already fires 8 times per session, which means context is being *discarded* rather than *retained* — the knowledge produced (root causes, decisions, gotchas) evaporates when the window rolls. Meanwhile the corpus is already project-partitioned on disk:
-`~/.pi/agent/sessions/--Users-rockliang-workplace-Poimen--/*.jsonl` — `cwd` in the session header gives the project key
-`Poimen/agent-rust/tasks/artifacts/<TaskId>/` — coder/reviewer JSONL per attempt
Intended outcome: a durable, queryable project memory built by reading that history chunk-by-chunk and keeping only what answers standing questions — surfaced as an Obsidian vault a human reads and a pgvector index an agent queries.
The mechanism is GRU-Mem (arXiv 2602.10560). Its two gates map directly onto the problem: the **update gate** refuses to write evidence-free chunks into memory (the 43% of toolResults), and the **exit gate** stops the scan once evidence is sufficient. The paper reports up to 400% speedup and *better* accuracy than ungated recurrent memory, because unchecked memory growth actively degrades later updates.
| Ollama context cap | **32768** (`OLLAMA_CONTEXT_LENGTH`) | `k8s/apps/llm-serving/ornith.yaml` |
| Controller model | `qwen2.5:3b-instruct` | is Qwen2.5-3B-Instruct — **the paper's exact 3B backbone** |
| Gateway auth | `apikey:` header, **not**`Authorization: Bearer` | Kong key-auth compares whole header value |
The 32K cap is the binding constraint and it fits: paper uses 5000-token chunks, 8192 max prompt, 2048 max response.
**Side fix:**`~/.pi/agent/models.json` declares `contextWindow: 131072` for ornith. Wrong — Ollama caps at 32768, so long prompts truncate silently. Correct to 32768.
## The tier model
Memory is **levelled**, and every event in the log carries its level. The paper has one flat memory; a project knowledge base needs three.
| Level | What it is | Produced by | Bounded |
|---|---|---|---|
| **L0** | evidence chunk — the verbatim source span the update gate accepted | update gate opening at L1 | no, but sparse (~17 of 412 chunks) |
| **L1** | per-query memory — GRU-Mem's `M_t` for one standing question | gated loop over L0 chunk stream | 1024 tokens |
| **L2** | project synthesis — memory across the L1 memories of one project | gated loop over L1 memories | 1024 tokens |
**The tiering is not new machinery.** L2 is the same controller, same prompt, same two gates — run with the L1 memories as its chunk stream and a project-level question. The recurrence is the algorithm applied to its own output, so `mem-core` implements one loop and the level is a parameter. Two consequences worth having on purpose:
- **Exit gate flips by level.** Off at L1 (see below), reasonably *on* at L2, where the input is a handful of memories rather than hundreds of chunks and "enough evidence" is actually decidable.
- **Levels form a provenance graph, not a pile.** Each L1 node records the L0 nodes that produced it; each L2 node records its L1 parents. That graph *is* the Obsidian link structure and the `parent_id` edges in Postgres — one relationship expressed in both projections.
**Authority invariant unchanged:** API is stateless demultiplexer. JSONL log is authoritative; vault and pgvector projections are droppable. API caches read-only state (embeddings, L2 synthesis); ingest writes only to log.
**Authority model — the load-bearing decision.** The JSONL log is the only source of truth. The vault and the vector index are projections that must be droppable and rebuildable byte-identically from the log. This is poimen's own §1 principle ("nothing derived is authoritative; if it cannot be dropped and rebuilt, it has hidden inputs and that is a bug") applied here, and it buys three things: re-embedding after a model change is a rebuild not a migration, Obsidian edits cannot corrupt the record, and the post-training corpus is the log itself.
## Standing queries
The paper's memory agent is `φθ(Q, C_t, M_{t-1})` — **it requires a question**. The update gate is defined as "does this chunk contain useful information *about the problem*". Without `Q` the gate has no referent, and `r_update` becomes undefinable, which forecloses post-training.
So each project declares durable questions in YAML. One query = one L1 memory = one Obsidian note.
question:What architectural decisions were made, with reasoning and rejected alternatives?
- id:infra-root-causes
question:What infrastructure bugs were found, what was the root cause, how was it isolated?
- id:open-questions
question:What questions were raised and left unresolved?
synthesis:# the L2 pass
question:What is the current state of this project, and what should someone know before working on it?
exit_gate:true
```
**Exit gate defaults off at L1.** Paper §3.3 makes this call itself: for "what are *all* the X" questions you cannot know evidence is sufficient without reading everything, so they provide a w/o-EG inference mode. L1 extraction is exactly that shape. Keep the gate *recorded* (its signal is needed for RL) but do not act on it. Enable at L2 and for interactive retrieval, where the paper measures 4× speedup.
## Separate weights — yes, specifically a LoRA adapter
Confirming the instinct, with the reason that actually matters here:
- **Base:** Qwen2.5-3B-Instruct, already resident as `qwen2.5:3b-instruct`
1.**VRAM.** One GPU, `OLLAMA_MAX_LOADED_MODELS=2`, currently holding `ornith:35b` + `qwen2.5:3b`. A separate full memory model evicts something, and eviction here is a weights reload measured in tens of seconds — we already watched `ornith` cold-start blow a 60s gateway timeout. A LoRA rides on the resident base for near-zero extra VRAM.
2.**Iteration.** Post-training emits a ~50 MB adapter, not a 6 GB model. Swap without redeploying.
3.**Reversibility.** A gate-behaviour regression reverts by pointing at the previous adapter.
**Infra consequence to accept up front:** Ollama cannot hot-swap LoRA adapters. Serving one means either moving the memory model to a **vLLM** InferenceService with `--enable-lora` (the `reasoning` predictor is already vLLM v0.11.0, so the pattern exists), or merging into a GGUF for Ollama and losing swappability. P1–P4 run prompted-only on the stock model, so this is deferred, not dodged.
## Repository layout
Rust workspace at `Poimen/memory`:
```
Cargo.toml workspace
crates/
mem-core/ domain types; Level enum; gate-response parser; the gated loop
mem-chunk/ RecordSource trait; chunking policy; flush triggers (see below)
memory-tasks/ the task board — INDEX.md + one file per task, tracked
queries/ standing query YAML, one file per project
vault/ Obsidian output (own git repo or gitignored)
log/ JSONL event log — authoritative, tracked
```
Crates: `sqlx` (postgres, runtime-tokio-rustls) + `pgvector` (sqlx feature), `tokenizers` for chunk sizing against the real Qwen2 tokenizer, `futures`, `serde`/`serde_json`, `clap`, `reqwest`.
Reuse rather than reinvent: `mem-llm`'s request shape and the `apikey` header convention are proven in `agent-rust/loop.sh`; response parsing mirrors its `extract_text()`.
### `mem-chunk` — its own crate, stream-shaped from day one
Chunking is split out because it is the seam where new input kinds arrive. Sources today are files with an EOF; telemetry, a live session tail, or a broker will not have one. Designing the boundary as a stream now means a future source implements a trait rather than forcing the loop to be rewritten — and it costs nothing, since the rest of the stack is already tokio (`sqlx` runtime-tokio, `reqwest`).
Batch sources become streams for free via `futures::stream::iter`, so `mem-ingest` gets no more complex today.
**The one thing that genuinely differs for streams is the flush trigger.** A file chunker emits a partial chunk at EOF; a stream has no EOF, so a partially-filled chunk would sit forever. `FlushTrigger` is therefore `Tokens(n)` today and gains `OrIdle(Duration)` when a stream source lands — carrying it in the policy now means the later change is one enum variant, not a signature change through the loop.
Worth noting for whenever that happens: the **exit gate changes meaning on an unbounded source**. At L1 over a finite transcript it is switched off because "read everything" is well defined (paper §3.3). Over a live stream there is no everything, so the gate stops being an optimisation and becomes the only termination condition — which is an argument for keeping it trained even while it is switched off.
## Storage schemas
### JSONL event log — authoritative
`log/<project>/<query-id>/<run-id>.jsonl`. **Every record carries `level`.**
The L2 pass writes the same record types with `"level":"L2"`, `"input_level":"L1"`, and `parents` holding L1 shas. `evidence` records appear only when the update gate opened, so update-rate is directly measurable and memory at any `t` is replayable.
### pgvector — projection
One table across all levels, because retrieval wants to search them together and filter:
One table across L0/L1/L2 (not three) — retrieval searches all levels together and filters by `level`. `memory_edge` is the provenance graph: L1 rows point back at the L0 chunks that produced them, L2 rows point back at L1 parents. `sha256 UNIQUE` is content identity (dedup key, hash excludes run id/timestamp — M0.2) and is what `memory_edge` actually references, not the surrogate `id`.
Retrieval: HNSW recall filtered by level, then `bge-reranker-base` via `/v1/rerank` for precision — that endpoint scored 0.98 vs 0.00009 on a discrimination probe, so it earns its place. Default query searches L1+L2 and walks `memory_edge` down to L0 for citations.
Infra — new CNPG cluster with the extension managed declaratively (CNPG 1.30 supports this, so **no manual `psql`**, consistent with the GitOps hard rule). Follows `k8s/infra/databases/temporal-db.yaml` exactly:
_drafts/<name>/SKILL.md <- machine-written, never auto-loaded
<name>/SKILL.md <- human-promoted, loadable
```
```markdown
---
project:poimen
level:L1
query_id:infra-root-causes
updated:2026-08-17
chunks_seen:412
chunks_used:17
---
# Infra root causes — poimen
<final memory text>
## Provenance
- [[pi-2026-07-21-019f857d]] chunk 66 — Kong body buffer
```
L0 defaults to inline citations rather than notes — 17 per query is manageable but grows unbounded across projects. The flag exists for when the graph view is worth the file count.
## Skills — the procedural projection
**A skill is a projection, not a level.** L0/L1/L2 are all *descriptive* — what happened. A skill is *procedural* — what to do next time. That is a change of modality, not a further compression, so the gated loop does not produce it: the update gate's question ("does this chunk contain evidence for Q") has no meaning when the output is an instruction.
The format is free. `SKILL.md` is YAML frontmatter plus markdown, which is exactly an Obsidian note — verified against `~/.claude/skills/seo-geo-claude-skills/research/keyword-research/SKILL.md`, whose frontmatter carries `name`, `description`, `when_to_use`, `argument-hint`. So `vault/skills/<name>/SKILL.md` is simultaneously a vault note and a loadable skill, with no conversion step:
```sh
pi --skill vault/skills/ # or set skillsPath in ~/.pi/config.json
`mem skill draft --from poimen/infra-root-causes` reads an L1 or L2 note and writes a draft. Emission should follow the existing authoring rubric rather than inventing one — the installed `grafana-core:skill-authoring` skill encodes Anthropic's Agent Skills guidance and a four-dimension rubric (conciseness, actionability, workflow clarity, progressive disclosure). Description quality is the whole game: a skill whose `description` does not match how the user actually phrases the request never fires.
**Drafts are never auto-loaded, and promotion is manual.** This is the one place the system can close a loop on itself, and the failure is subtle:
> a memory-derived skill is auto-loaded → it appears in future session transcripts → those transcripts are ingested as evidence → the memory that produced the skill is reinforced by its own output
No external verifier breaks that cycle. It is the same hazard poimen §16 names when it gates "automatic workflow mutation without human approval" by default, and it is why `_drafts/` is a separate directory rather than a frontmatter flag — a directory cannot be accidentally globbed into `--skill`.
Two mechanical guards:
1.**Promotion is a human move** out of `_drafts/`, reviewable as a diff.
2.**Provenance marks derived text.** Every emitted skill carries `generated_from: <L2 sha>` in frontmatter, and `mem-ingest` tags chunks matching a known emitted artifact as `derived: true` and excludes them from evidence. Without this the corpus slowly becomes its own training data.
## Phases
**P1 — Read-only spine.**`mem-ingest` implements `RecordSource` for pi sessions and Claude transcripts; `mem-chunk` chunks to 5000 tokens on message boundaries; `mem ingest --dry-run` prints the chunk plan with no model calls. Both sources are batch, but they go through the stream interface so the seam is exercised from the first commit rather than retrofitted.
**P2 — Gated loop at L1, prompted only.**`mem-llm` + gate-response parser (paper Figure 10a prompt, adapted for standing queries). Writes the JSONL log with L0 evidence and L1 memory records. Exit gate recorded, not acted on. This is the paper's "w/o RL" baseline, which Figure 9 shows already works.
**P3 — Projections.** Obsidian projector and pgvector repo, both rebuildable via `mem rebuild --from-log`. Infra commit for `memory-db`.
**P4 — L2 synthesis and retrieval.**`mem synthesize` runs the same loop over L1 memories with the exit gate on. `mem query` — embed, HNSW recall by level, rerank, return with provenance walked through `memory_edge`.
**P5 — Skill drafting.**`mem skill draft --from <note>` emits `vault/skills/_drafts/<name>/SKILL.md` with `generated_from` provenance; `mem-ingest` grows the `derived: true` exclusion filter. Promotion stays manual. Cheap to build and it is the phase that makes the memory *do* something rather than only be read.
**P6 — Post-training (separate, Python).** Boundary is the JSONL. `mem label` uses the 32B `reasoning` model as an offline evidence labeler to produce per-chunk `U_t` ground truth (the paper had synthetic NIAH labels; we do not, and this is the honest cheapest substitute). Then verl trains a LoRA with the paper's rewards: `r_update` ±1, `r_exit` {0, −0.5 late, −0.75 early}, strict `r_format`, `α=0.9` mixing trajectory- and turn-level advantage. Requires the vLLM decision above.
## Task breakdown
Board lives in **`memory-tasks/`** at the repo root. Format follows `agent-rust/tasks/`: one file per task, self-contained, each with `Acceptance` / `Verify` (harness, numbered assertions, command) / `False pass` / `Traps`, a `Status` field as source of truth, and `memory-tasks/INDEX.md` mirroring it. Ids are `M<phase>.<n>` and frozen once written — phase order is declared in `INDEX.md`, never derived from the id.
```
memory-tasks/
INDEX.md board + phase order + progress mirror
M0.1-cargo-workspace.md
M0.2-domain-types.md
...
M5.6-m5-gate.md
```
Note `agent-rust/.gitignore` excludes `tasks`, which silently untracks the whole board there. Naming this `memory-tasks/` sidesteps that pattern — and it should be **tracked**, since the task files carry the acceptance criteria.
**M0 — Read-only spine** (no model calls anywhere in this phase)
| id | task | size | deps |
|---|---|---|---|
| M0.1 | Cargo workspace + six crate skeletons, CI builds clean | S | — |
Total 43 tasks, 7 gates. M0 and M2.2 have no model dependency and can start immediately; M5.4 is homelab work independent of everything else in M5 and can run in parallel. M3.5 depends on M2 (pgvector store exists) and M1 (ingest loop exists); can run in parallel with M4 and M5.
cargo run -p mem-cli -- verify --derived-filter --project poimen
# asserts: no L0 evidence node text matches an emitted skill artifact
```
The decisive P2 metric is **update-rate**, the one number distinguishing a working gate from an expensive summarizer. toolResults are 43% of records and mostly evidence-free, so a correct gate rejects the large majority of chunks.
**P3.5 API gate:** Ingest and query work over HTTP with correct idempotency, auth, and rate limiting. CLI and agents both submit to same endpoint; no duplication or ordering issues.
## Distributed API Layer (Homelab Frontend)
**Gateway:**`api.riotpiao.com` routes agent and system memory requests through Kong.
**Architecture assumption:** Memory services run in CNPG cluster; API layer is HTTP facade exposing read/write workflows to distributed agents. Authority remains JSONL—API is a request demultiplexer, not a cache or alternative source of truth.
### REST API Endpoints
```
POST /memory/ingest <- async, idempotent by sha256
GET /memory/query <- semantic search + rerank
GET /memory/projects <- list projects with L2 synthesis
GET /memory/projects/{id}/status <- ingest/synthesis status
GET /memory/projects/{id}/notes <- L1/L2 notes (Obsidian export)
GET /memory/skills <- loadable skills (excludes _drafts)
GET /memory/skills/{name} <- one skill frontmatter + body
**Ingestion:**`mem-ingest` CLI submits batches to `POST /memory/ingest` via `ingest_id` (sha256 of batch text). Duplicate `ingest_id` returns same `job_id` without re-enqueuing — jobs are idempotent by content hash, not request. Server stores the mapping; HTTP 409 means already ingested (user caller resubmits without retry).
**Query federation:** Agents query single endpoint; server fans requests to appropriate project (selected by metadata or query text). Results walk `memory_edge` down to L0 *server-side*, so client gets complete citation graph in one round-trip.
**Skills as cargo:**`GET /memory/skills` returns YAML frontmatter in JSON so agent UIs can inspect `description` and `when_to_use` without fetching the file. Body is optional (fetch separately if needed to load).
**Status & observability:**
-`GET /memory/projects/{id}/status` → `{"last_ingest": "...", "chunks_total": N, "chunks_used": M, "synthesis_ran": "...", "next_synthesis_at": "..."}`
- **3B gate quality unmeasured on this corpus.** The paper evaluates on QA benchmarks with clean evidence labels; agent transcripts are messier. Mitigation: P2's update-rate is a cheap early read, and the 32B `reasoning` model can spot-audit a sample before committing to P5.
- **L2 inherits L1's errors with no path back to source.** Synthesis over memories cannot recover evidence the L1 gate wrongly discarded. `memory_edge` makes the omission *visible* (an L1 note with suspiciously few parents) but not recoverable without a re-run.
- **Self-reinforcement through skills.** The only cycle in the system: emitted skill → future session context → ingested as evidence → reinforces the memory that emitted it. Guarded by manual promotion plus the `derived: true` ingest filter, and both must hold. Audit it by checking that no L0 evidence node's text matches an emitted artifact.
- **No ground-truth evidence labels.** `r_update` needs them. Distant supervision from the 32B labeler inherits its bias; hold out a hand-labelled set to measure agreement before trusting it.
- **Vault/log divergence.** Hand edits are overwritten on rebuild. Either make the vault read-only or add an `## Notes` region the projector preserves. Decide before anyone starts editing.
- **Ollama has no LoRA path.** P5 forces the vLLM decision. Do not discover this at P5.
- **API latency at scale.** Query federation fans requests to multiple projects; slowest project wins. Mitigation: query timeout 5s, client-side fallback to local JSONL search, async synthesis keeps L2 warm (cache hit 95%+).
- **Ingest race on concurrent writes.** Two agents submit overlapping session chunks to same project simultaneously. Mitigation: `ingest_id` based on content hash prevents duplicate evidence in log; gated loop is single-threaded per project, queues serialize. Allowed cost: cold-start ingest delay ~5m for backlog.