pi-memoria 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,672 @@
1
+ # memoria
2
+
3
+ Agent-first long-term memory for [pi](https://github.com/badlogic/pi-mono).
4
+
5
+ memoria gives a coding agent a memory it can actually rely on: a plain-markdown
6
+ library on disk, a prose briefing that is loaded into every session, and
7
+ automatic recall that searches the whole library on every prompt — in well under
8
+ a millisecond.
9
+
10
+ - **Nothing is lost behind an API.** Every memory is a markdown file you can
11
+ read, edit, grep, diff and version.
12
+ - **Past conversations are searchable too.** When the library has nothing, the
13
+ agent can search the raw transcripts of earlier sessions before saying it does
14
+ not remember.
15
+ - **Recall is automatic.** Relevant notes are injected before the model answers,
16
+ so it does not have to remember to ask.
17
+ - **Broad topics, never fact files.** `likes-apples.md` is a defect; facts
18
+ accumulate in `food-preferences.md`.
19
+ - **Names are handles.** Aliases make every nickname, full name or former name
20
+ resolve to the same note, and notes can be re-filed later without breaking
21
+ references.
22
+ - **Zero runtime dependencies.** No database, no server, no embedding service, no
23
+ build step. Retrieval is a BM25 index kept in memory.
24
+
25
+ ```
26
+ ┌──────────────────────────────────────────────────────────────┐
27
+ │ layer 1 MEMORY.md always in the system prompt │
28
+ │ layer 2 auto-recall best matches injected per prompt │
29
+ │ layer 3 memoria_recall the agent can search deeper │
30
+ │ layer 4 plain markdown read/grep the files directly │
31
+ └──────────────────────────────────────────────────────────────┘
32
+ ```
33
+
34
+ Measured on the bundled corpus: **recall@5 = 100%, recall@1 = 92.5%** over 40
35
+ questions (paraphrases, typos, aliases, CJK, identifiers, superseded notes) with
36
+ an average query time of **0.16 ms** (`npm run eval`).
37
+
38
+ ## Contents
39
+
40
+ - [Install](#install)
41
+ - [Quick start](#quick-start)
42
+ - [How it works](#how-it-works)
43
+ - [The memory library](#the-memory-library)
44
+ - [Tools](#tools)
45
+ - [Commands](#commands)
46
+ - [Configuration](#configuration)
47
+ - [Scopes: personal, project, read-only](#scopes-personal-project-read-only)
48
+ - [Synonyms](#synonyms)
49
+ - [Model reranking](#model-reranking)
50
+ - [Automatic session learning](#automatic-session-learning)
51
+ - [Session recall](#session-recall-past-conversations)
52
+ - [Backup and migration](#backup-and-migration)
53
+ - [Performance](#performance)
54
+ - [Privacy and durability](#privacy-and-durability)
55
+ - [Troubleshooting](#troubleshooting)
56
+ - [Development](#development)
57
+ - [Design notes and limits](#design-notes-and-limits)
58
+ - [License](#license)
59
+
60
+ ## Install
61
+
62
+ ### Copy it into the extensions directory (simplest)
63
+
64
+ ```bash
65
+ mkdir -p ~/.pi/agent/extensions/memoria
66
+ cp index.ts package.json ~/.pi/agent/extensions/memoria/
67
+ cp -r src skills ~/.pi/agent/extensions/memoria/
68
+ ```
69
+
70
+ Pi discovers `extensions/memoria/index.ts` on the next start (or after
71
+ `/reload`). Three notes:
72
+
73
+ - **Do not copy `node_modules/`.** Pi supplies `typebox` and the
74
+ `@earendil-works/pi-*` packages to extensions, so the copy works with no
75
+ dependencies installed.
76
+ - `package.json` is optional for this route; it carries the `pi.extensions` and
77
+ `pi.skills` manifest and the peer-dependency metadata used by the package
78
+ route.
79
+ - The bundled skill is discovered automatically when memoria is installed as a
80
+ **package** (`pi install …`). For the copy route, copy it separately if you
81
+ want it: `mkdir -p ~/.pi/agent/skills && cp -r skills/memoria ~/.pi/agent/skills/`.
82
+
83
+ ### Install as a pi package
84
+
85
+ ```bash
86
+ pi install git:github.com/rcsaquino/pi-memoria@v0.1.1
87
+ pi install npm:pi-memoria # if published to npm
88
+ pi install ./path/to/pi-memoria # or from a local checkout
89
+ pi list
90
+ pi remove git:github.com/rcsaquino/pi-memoria@v0.1.1
91
+ ```
92
+
93
+ `pi install` records the package in `~/.pi/agent/settings.json` (or
94
+ `.pi/settings.json` with `-l`, which loads only after project trust) and clones
95
+ the repository to `~/.pi/agent/git/<host>/<owner>/<repo>`. It runs
96
+ `npm install --omit=dev` in the clone; this package declares the pi-provided
97
+ modules as *optional* peers so npm does not fetch a second, ~450 MB copy of pi.
98
+ The installed package is around 700 KB with no `node_modules`.
99
+
100
+ The package also ships a skill (`skills/memoria/SKILL.md`) that teaches an agent
101
+ how to maintain the library — where a fact belongs, how to consolidate notes, and
102
+ what never to do.
103
+
104
+ ### Try it without installing
105
+
106
+ ```bash
107
+ pi --extension /path/to/memoria/index.ts
108
+ # from a checkout:
109
+ pi -e ./index.ts
110
+ ```
111
+
112
+ ## Quick start
113
+
114
+ Nothing to configure. In a session:
115
+
116
+ ```
117
+ You: Remember that I take my coffee with oat milk and I'm lactose intolerant.
118
+ Agent: [memoria_write { topic: "Dietary preferences", category: "preferences" }]
119
+
120
+ ... days later, in a different project ...
121
+
122
+ You: Order me a flat white.
123
+ Agent: [auto-recall surfaces "Dietary preferences — drinks oat milk; lactose intolerant"]
124
+ ```
125
+
126
+ Other things you can say or run:
127
+
128
+ ```bash
129
+ /memoria status # where the store is and how healthy it is
130
+ /memoria store remember to renew the Datadog contract in August
131
+ /memoria search datadog contract
132
+ /memoria topics # review notes: facts, size, usage, merge candidates
133
+ /memoria doctor # consistency problems and housekeeping hints
134
+ /memoria learn # extract durable facts from this session
135
+ ```
136
+
137
+ ## How it works
138
+
139
+ 1. **`MEMORY.md`** lives in the store root and is injected into the system
140
+ prompt on every model call, capped at `hotLimit` (5000 characters). It is a
141
+ short **prose** briefing — who the user is, how they work, hard constraints,
142
+ the state of active work — not a log: no headings, no bullets, no
143
+ annotations. Being stable, it does not invalidate the prompt cache.
144
+ 2. **Auto-recall** searches the library on every user prompt and injects the
145
+ best matches as a `memoria_recall` message, with ids, paths and excerpts. The
146
+ previous turn is folded in at a lower weight (`autoRecallPriorWeight`) so a
147
+ long earlier message cannot out-vote the current question.
148
+ 3. **`memoria_recall`** lets the agent search deeper, with filters for category,
149
+ tags, priority, recency, scope and score, plus an optional scoring breakdown.
150
+ 4. **Plain markdown**: `library/INDEX.md` and per-category indexes provide a
151
+ generated table of contents, and `read`/`grep`/`cat` work on the files.
152
+ 5. **Past conversations**: if the library has nothing, the transcripts pi saved
153
+ for earlier sessions are searched as a last resort, with file-and-line
154
+ citations so anything found can be verified in context.
155
+
156
+ Ranking combines BM25 over weighted fields (title, tags, aliases, links,
157
+ summary, category, body) with boosts for exact phrases, priority, recency, query
158
+ coverage, time windows ("last week"), related notes, and a demotion for notes
159
+ that a newer note declares superseded. Matching is resilient: identifiers and
160
+ paths match literally, plurals and verb forms match through a conservative
161
+ stemmer, `kuber` finds `kubernetes`, one or two typos still hit, and CJK text is
162
+ matched with unigrams and bigrams.
163
+
164
+ ## The memory library
165
+
166
+ ```
167
+ <agent dir>/memoria/
168
+ ├── MEMORY.md always-injected prose briefing
169
+ ├── config.json optional store configuration
170
+ ├── synonyms.json optional query-side synonym table
171
+ ├── library/
172
+ │ ├── INDEX.md generated table of contents
173
+ │ ├── people/<topic>.md one note per broad topic
174
+ │ ├── projects/<topic>.md
175
+ │ ├── preferences/<topic>.md
176
+ │ ├── decisions/<topic>.md
177
+ │ ├── workflows/<topic>.md
178
+ │ ├── knowledge/<topic>.md
179
+ │ └── inbox/<topic>.md quick captures, triaged later
180
+ ├── .index/ derived: index.json|index.bin, usage.json
181
+ └── .trash/ soft-deleted notes
182
+ ```
183
+
184
+ `<agent dir>` is `~/.pi/agent` by default, or `$PI_CODING_AGENT_DIR` when pi's
185
+ agent directory is customized. Because the store is user-level, memories follow
186
+ you across projects: remember something in one repository and recall it in
187
+ another.
188
+
189
+ Pi's own conversation transcripts live next to the store at
190
+ `<agent dir>/sessions/` (plus `sessions-archive/` if you keep one). They are read
191
+ by [session recall](#session-recall-past-conversations) and never modified.
192
+
193
+ ### Broad topics, never facts
194
+
195
+ | User says | Stored as | Not as |
196
+ |---|---|---|
197
+ | "I like apples" | `library/preferences/food-preferences.md` → `- **Fruit** — Likes apples.` | `likes-apples.md` |
198
+ | "I like pears" | appended to the same `food-preferences.md` | `likes-pears.md` |
199
+ | "Alice prefers oat milk" | `library/people/alice.md` | `alice-prefers-oat-milk.md` |
200
+ | "my dad is Bob" | `library/people/bob.md` → `- **Bob** — John's father, retired.` | `dad.md`, `johns-father.md` |
201
+
202
+ Rules enforced by the store, not merely requested from the model:
203
+
204
+ - The file name is always `slugify(topic)`. Topics that read like a single fact
205
+ (`likes apples`, `I like apples`) or like a **relationship** (`John's father`,
206
+ `dad`, `Alice's manager`) are rejected and the fact is filed under the category
207
+ name instead (`people.md`), with an explanatory note returned to the agent.
208
+ A relationship goes in the fact text; the note is named after the subject.
209
+ - Writing to an existing topic **appends** under a `## Facts` section, skipping
210
+ duplicates. There is no one-file-per-fact path.
211
+ - A note may grow to `topicMaxChars` (default 8000) before new facts spill into
212
+ `topic-2.md`.
213
+ - `memoria_write` accepts `mode: "new"` to force a sibling file and
214
+ `mode: "replace"` to overwrite a note deliberately.
215
+ - `memoria doctor` flags any file named after a fact or a relationship.
216
+
217
+ ### Names change: aliases first, renames second
218
+
219
+ A person is not their name, and the first name you learn is rarely the one you
220
+ keep. Notes therefore carry **aliases** in frontmatter, indexed at tag weight:
221
+
222
+ ```markdown
223
+ ---
224
+ topic: Bob
225
+ aliases: ["Robert", "Bobby", "John's father"]
226
+ ---
227
+ ```
228
+
229
+ Any of `Bob`, `Robert`, `Bobby`, `John's father` — and the file name — recalls
230
+ the note, so retrieval never depends on which name won the file name.
231
+
232
+ When the better name *is* known, `memoria_move` re-files the note:
233
+
234
+ - Target free → the file is **renamed**; the note keeps its `id`, so ids read
235
+ earlier in the session stay valid.
236
+ - Target exists → facts are **merged** in (duplicates skipped, nothing
237
+ overwritten) and the old file goes to `.trash/`. `merge: false` reports the
238
+ conflict instead.
239
+ - The previous topic, title and file name are added to the target's aliases, so
240
+ old references keep working.
241
+
242
+ Renaming is deliberately an explicit agent action rather than a side effect of
243
+ writing: renaming during an unrelated write is how you end up with `bob-2.md`
244
+ and a path the agent read earlier in the session that no longer exists.
245
+
246
+ ### Related notes and superseded notes
247
+
248
+ ```markdown
249
+ ---
250
+ related: ["mem_1758_ab12"] # pulled into recall with the source note
251
+ supersedes: ["Deploy process"] # this note replaces that one
252
+ ---
253
+ ```
254
+
255
+ - `related` notes are appended to recall results (`related` marker) and shown by
256
+ `memoria_read`, so following a reference works from either end.
257
+ - A note that another note declares `supersedes` stays searchable but is
258
+ **demoted and flagged** (`SUPERSEDED BY: …`). That is the recommended way to
259
+ change a decision: write the new note with `supersedes` instead of deleting
260
+ history.
261
+ - `memoria doctor` reports dangling links and fact pairs that look contradictory
262
+ (same wording, opposite polarity).
263
+
264
+ ### Note format
265
+
266
+ Notes are markdown with optional YAML frontmatter. Frontmatter is written
267
+ automatically on the first `memoria_write`; hand-written notes without it are
268
+ still indexed (the title comes from the first `#` heading, the category from the
269
+ folder).
270
+
271
+ ```markdown
272
+ ---
273
+ id: mem_1758712445123_a1b2c3
274
+ title: Dietary preferences # broad topic = note title
275
+ topic: Dietary preferences # drives the file name: dietary-preferences.md
276
+ category: preferences
277
+ tags: [alice, dietary, food]
278
+ aliases: ["Dairy", "Food preferences"]
279
+ related: []
280
+ supersedes: []
281
+ created: 2025-09-24T09:14:05.123Z
282
+ updated: 2025-09-24T09:14:05.123Z
283
+ last_used: 1758712445123 # refreshed lazily on recall
284
+ source: agent
285
+ confidence: high
286
+ priority: normal
287
+ summary: Oat milk in coffee; lactose intolerant.
288
+ ---
289
+
290
+ # Dietary preferences
291
+
292
+ ## Facts
293
+
294
+ - **Drinks** — Drinks oat milk in flat whites; avoids dairy.
295
+ - **Fruit** — Likes apples and pears; dislikes durian.
296
+ ```
297
+
298
+ Fields: `topic` (broad grouping, drives the file name), `priority`
299
+ (`low|normal|high|critical`, boosts ranking), `confidence`, `tags`, `aliases`
300
+ (all indexed), `related`, `supersedes`, `summary` (used in listings and recall),
301
+ `last_used` (maintained by the store), and `category` (kept in sync with the
302
+ folder). Unknown keys are preserved verbatim through updates.
303
+
304
+ ## Tools
305
+
306
+ | Tool | Purpose |
307
+ |---|---|
308
+ | `memoria_recall` | Search long-term memory. Filters by category, tags, priority, recency, scope; options for `include_body`, `min_score`, `explain`, `rerank`, `drop_superseded`, prefix/fuzzy control. |
309
+ | `memoria_write` | Add a fact to a broad **topic note** (`topic`, `content`, optional `label`, category, tags, aliases, related, supersedes, summary, priority). Creates the note on first use and appends afterwards. |
310
+ | `memoria_read` | Read a full note by id, path or alias, with its aliases, related notes and superseding notes. |
311
+ | `memoria_move` | Re-file a note under a better broad topic (`from`, `topic`, optional `category`, `merge`, `keep_alias`). Renames when the target is free, merges when it is not. |
312
+ | `memoria_sessions` | Search the transcripts of earlier conversations (`action: "search"`, plus `since_days`, `project`, `include_tools`, `user_only`) and read the surrounding dialogue (`action: "read"`, `path`, `line`, `window`) before quoting it. |
313
+ | `memoria_hot` | Read/add/remove/replace/compact `MEMORY.md`, the always-in-context briefing. |
314
+ | `memoria_list` | Browse categories, titles, ids, tags, aliases and summaries. |
315
+ | `memoria_forget` | Move a note to `.trash/` (recoverable). |
316
+ | `memoria_export` | Dump the store to JSONL, inline or to a file. |
317
+ | `memoria_import` | Restore from JSONL (`mode: merge|replace|skip`, `dry_run`). |
318
+
319
+ The agent's system prompt teaches it when to use them, so you normally do not
320
+ have to ask.
321
+
322
+ ## Commands
323
+
324
+ ```
325
+ /memoria Store status, index stats, MEMORY.md budget
326
+ /memoria search <query> Ranked results with snippets (--primary/--project/--all)
327
+ /memoria store <text> Quick capture into library/inbox
328
+ /memoria read <id|path> Print a full note
329
+ /memoria move <ref> <topic> Re-file a note under a better broad topic
330
+ /memoria hot Show MEMORY.md
331
+ /memoria topics Review notes: facts, size, usage, merge candidates
332
+ /memoria diff [days] Memories created or updated recently (default 7 days)
333
+ /memoria sessions <query> Search earlier conversations (--days=N --project=X --tools --user)
334
+ /memoria sessions --read <path> <line> [--window=N] Show the surrounding dialogue
335
+ /memoria doctor Consistency problems and housekeeping hints
336
+ /memoria export [file] Dump the store to JSONL (default ./memoria-export-<date>.jsonl)
337
+ /memoria export --hot [file] Write MEMORY.md alone as an "about me" document
338
+ /memoria import <file> Restore from JSONL (--merge|--replace|--skip, --dry-run)
339
+ /memoria learn Extract durable memories from the current session
340
+ /memoria reindex Rebuild the search index from disk
341
+ /memoria index Regenerate library/INDEX.md files
342
+ /memoria paths Print store paths
343
+ /memoria forget <id> Move a note to .trash
344
+ ```
345
+
346
+ ## Configuration
347
+
348
+ Create `config.json` in the store root (`~/.pi/agent/memoria/config.json`) to
349
+ override any default. Everything is optional; unknown or malformed values fall
350
+ back to the default rather than failing.
351
+
352
+ ```json
353
+ {
354
+ "autoRecall": true,
355
+ "autoRecallLimit": 6,
356
+ "topicMaxWords": 6,
357
+ "exclude": ["library/scratch"],
358
+ "projectRoot": ".pi/memoria-project",
359
+ "autoLearn": "on-settle",
360
+ "synonyms": { "k8s": ["kubernetes"] }
361
+ }
362
+ ```
363
+
364
+ | Key | Default | Meaning |
365
+ |---|---:|---|
366
+ | `rootDir` | `"$AGENT_DIR/memoria"` | Primary store. Supports `$AGENT_DIR`, `~/`, absolute and cwd-relative paths. |
367
+ | `projectRoot` | `""` | Optional writable per-project store; empty disables it. |
368
+ | `extraRoots` | `[]` | Additional **read-only** stores to search. |
369
+ | `hotLimit` | `5000` | Hard cap for `MEMORY.md`, in characters. |
370
+ | `snippetChars` | `280` | Body excerpt length per hit. |
371
+ | `autoRecall` | `true` | Search the library on every user prompt. |
372
+ | `autoRecallLimit` | `6` | Maximum notes injected per prompt. |
373
+ | `autoRecallMinScore` | `1.4` | Score floor for auto-recall. |
374
+ | `autoRecallMaxChars` | `2400` | Character budget for the injected recall block. |
375
+ | `autoRecallLastTurns` | `1` | Previous turns folded into the recall query. |
376
+ | `autoRecallPriorWeight` | `0.4` | Weight of those previous turns versus the current prompt. |
377
+ | `bodyCacheBytes` | `8388608` | In-memory body cache budget. |
378
+ | `scanIntervalMs` | `2000` | Minimum interval between filesystem freshness scans. |
379
+ | `watcherSettleMs` | `300` | Idle delay after a file event before refreshing (coalesces bursts). |
380
+ | `exclude` | `[]` | Path fragments never indexed. |
381
+ | `defaultCategory` | `"inbox"` | Folder for notes without a category. |
382
+ | `topicMaxWords` | `6` | Longest topic name before falling back to the category. |
383
+ | `topicMaxChars` | `8000` | Largest note before facts spill into a sibling file. |
384
+ | `usageTracking` | `true` | Track hits/writes/last-used in `.index/usage.json`. |
385
+ | `lastUsedWriteIntervalMs` | `21600000` | Refresh a note's `last_used` at most this often (6 h). |
386
+ | `staleAfterDays` | `365` | `doctor` reports notes unused for longer. |
387
+ | `promoteAfterWrites` | `3` | Suggest `memoria_hot` after this many writes with priority ≥ high. |
388
+ | `dedupeThreshold` | `0.62` | Overlap above which two notes are reported as merge candidates. |
389
+ | `relatedHits` | `3` | Related notes pulled into one result. |
390
+ | `relatedBoost` | `0.35` | Score factor for those related notes. |
391
+ | `synonyms` | `{}` | Inline synonym table (merged over `synonyms.json`). |
392
+ | `synonymWeight` | `0.6` | Weight of synonym-expanded query terms. |
393
+ | `timeHints` | `true` | Parse "last week"/"yesterday" in queries into a recency window. |
394
+ | `searchCacheSize` | `32` | LRU entries for repeated identical searches (0 disables). |
395
+ | `rerank` | `false` | Let the session model reorder recall candidates. |
396
+ | `rerankModel` | `""` | Model id (`provider/model`); empty uses the session model. |
397
+ | `rerankTopK` | `12` | Candidates shown to the reranker. |
398
+ | `rerankTimeoutMs` | `2500` | Reranker budget before falling back to lexical order. |
399
+ | `autoLearn` | `"off"` | `off`, `on-settle` (after the agent goes idle) or `on-shutdown`. |
400
+ | `autoLearnMinTurns` | `8` | Minimum user turns before automatic extraction. |
401
+ | `autoLearnMinChars` | `2000` | Minimum transcript size before automatic extraction. |
402
+ | `autoLearnCooldownMs` | `21600000` | Minimum gap between automatic extractions. |
403
+ | `learnChunkChars` | `12000` | Characters per extraction chunk (long sessions are chunked). |
404
+ | `indexFormat` | `"auto"` | `auto` (binary above 20k notes), `json` or `binary`. |
405
+ | `sessionSearch` | `true` | Search saved session transcripts at all. |
406
+ | `sessionRoots` | `[]` | Extra transcript roots (searched before `<agent dir>/sessions`). |
407
+ | `sessionFallback` | `true` | Search transcripts automatically when the library returns nothing. |
408
+ | `sessionScanMs` | `1500` | Wall-clock budget for an explicit transcript search (the automatic fallback uses at most 400 ms). |
409
+ | `sessionExcerptChars` | `400` | Context characters per transcript hit. |
410
+ | `sessionCacheBytes` | `33554432` | In-memory budget for parsed transcripts. |
411
+ | `sessionIncludeTools` | `false` | Include tool calls/results and compaction summaries by default. |
412
+
413
+ ## Scopes: personal, project, read-only
414
+
415
+ - **`primary`** (default) — the user-level store at `<agent dir>/memoria`.
416
+ Memories follow you across projects.
417
+ - **`project`** — set `projectRoot` to keep project-specific memories in the
418
+ repository (`"projectRoot": ".pi/memoria-project"`). It is writable: pass
419
+ `scope: "project"` to write there, while reads default to `all`.
420
+ - **`all`** — primary + project + extra roots, read paths merged.
421
+ - **`extraRoots`** — additional stores that are always **read-only**, for a
422
+ shared team library or an imported archive.
423
+ - **`global`** — legacy alias for `primary`.
424
+
425
+ Cross-store results are rank-normalized: a small store's best hit is lifted to
426
+ the global best (up to 4×) instead of being drowned by a large one, and a note
427
+ that exists in two stores is returned once.
428
+
429
+ ## Synonyms
430
+
431
+ Domain shorthand rarely appears in the notes you wrote earlier. Drop a
432
+ `synonyms.json` in the store root (or inline the table in `config.json`) and
433
+ expansion happens at query time, both directions, with no re-indexing:
434
+
435
+ ```json
436
+ {
437
+ "k8s": ["kubernetes"],
438
+ "postgres": ["postgresql", "pg"],
439
+ "auth": ["authentication", "login"],
440
+ "oncall": ["on-call", "pager"]
441
+ }
442
+ ```
443
+
444
+ ## Model reranking
445
+
446
+ BM25 is exact but literal: it does not know which of five plausible notes you
447
+ mean. With `"rerank": true`, the top candidates (`rerankTopK`) are shown to the
448
+ session model, which returns them in relevance order, within
449
+ `rerankTimeoutMs`. Reranking is strictly best-effort: on timeout, error, missing
450
+ auth or an unparsable reply, lexical order is used, so it can never make recall
451
+ fail. It is off by default because it costs a model call per search.
452
+
453
+ ## Automatic session learning
454
+
455
+ `/memoria learn` extracts durable facts from the current session. Long
456
+ conversations are chunked (`learnChunkChars`, at most 4 calls) and progress is
457
+ shown in the status line. Set `autoLearn` to `"on-settle"` (after the agent
458
+ finishes a turn) or `"on-shutdown"` to run it without asking. Guards keep it
459
+ cheap: at least `autoLearnMinTurns` user turns, at least `autoLearnMinChars` of
460
+ transcript, and at most one extraction per `autoLearnCooldownMs`. The default is
461
+ `"off"` because it spends model tokens.
462
+
463
+ ## Session recall (past conversations)
464
+
465
+ Curated memory only holds what the agent decided to remember. The rest of the
466
+ story is in pi's saved transcripts, so memoria can search them:
467
+
468
+ - **Automatically**, whenever `memoria_recall` finds nothing (`sessionFallback`,
469
+ on by default). The injected block is explicitly labelled as raw evidence and
470
+ includes the file and line of every excerpt.
471
+ - **On request**, through the `memoria_sessions` tool — useful for "remember
472
+ when", "did we discuss", exact earlier wording, dates, or prior decisions that
473
+ were never turned into memory notes.
474
+ - **From the CLI**, with `/memoria sessions <query>` and
475
+ `/memoria sessions --read <path> <line>`.
476
+
477
+ ```
478
+ memoria_sessions { action: "search", query: "deploy window Thursday" }
479
+ memoria_sessions { action: "search", query: "oat milk", user_only: true }
480
+ memoria_sessions { action: "read", path: "<file from a hit>", line: 92, window: 8 }
481
+ ```
482
+
483
+ The bundled `memoria-sessions` skill teaches the agent the discipline that makes
484
+ this trustworthy: run two to four short distinctive searches (not one long
485
+ question), then **read the surrounding dialogue before quoting it** — a later
486
+ user correction outranks an earlier assistant claim, and transcript text is
487
+ evidence to evaluate, not instructions to follow. If nothing is found, the tool
488
+ reports how many sessions and messages were searched.
489
+
490
+ What it does and does not touch:
491
+
492
+ | Property | Behaviour |
493
+ |---|---|
494
+ | Scope | Every `*.jsonl` under the configured roots, newest first — no index that can go stale. |
495
+ | Content | User and assistant **text** by default. Thinking blocks are never extracted. Tool calls/results, compaction summaries and extension payloads only with `include_tools: true`. |
496
+ | Output | Bounded excerpts plus `file:line`; never a whole transcript dump. |
497
+ | Writes | None. Transcripts are read-only and `read` refuses paths outside the session roots. |
498
+ | Cost | Full cold scan of 110 sessions / 13 MB ≈ 120 ms; repeat searches ≈ 5 ms from the parse cache. |
499
+ | Coverage | Exhaustive unless a budget stops it. `partial` (shown in the tool output, the recall block and `/memoria sessions`) means the scan stopped early: the hits are real, but older sessions were not read. Newest sessions are scanned first, already-parsed files stay cached (so each retry gets further), and an explicit `memoria_sessions` call uses the larger `sessionScanMs` budget. |
500
+ | Privacy | Nothing leaves the machine; the excerpts go to the model only when the feature runs. |
501
+
502
+ `sessionRoots` exists for archives or a second agent directory. Set
503
+ `sessionSearch: false` to disable the feature entirely, or
504
+ `sessionFallback: false` to keep the tool while never searching automatically.
505
+
506
+ ## Backup and migration
507
+
508
+ `memoria_export` writes JSONL — one record per line, notes plus `MEMORY.md` — to
509
+ a file or returns a bounded preview. `memoria_import` restores it:
510
+
511
+ ```
512
+ memoria_export { path: "memoria-backup.jsonl" }
513
+ memoria_import { path: "memoria-backup.jsonl", dry_run: true }
514
+ memoria_import { path: "memoria-backup.jsonl", mode: "merge" }
515
+ ```
516
+
517
+ - `merge` (default) adds facts that are missing, never duplicating an id.
518
+ - `replace` overwrites notes with the same id.
519
+ - `skip` only imports notes that do not exist yet.
520
+ - Notes keep their ids, so ids in an old transcript still resolve.
521
+ - Paths are validated: an import cannot write outside `library/`, and a path
522
+ already taken by a different note gets a numbered sibling instead of an
523
+ overwrite.
524
+
525
+ The same files remain readable as plain markdown if you stop using memoria, and
526
+ the whole store is safe to commit to a private repository (`.index/` is derived
527
+ and can be deleted).
528
+
529
+ ## Performance
530
+
531
+ `node tests/bench.ts 1000 5000` measures a worst-case corpus (50-word
532
+ vocabulary, 60-word documents, so every posting list is long);
533
+ `node tests/bench.ts 1000 5000 --real` uses a realistic high-vocabulary corpus
534
+ (~44k distinct terms at 5k notes).
535
+
536
+ | Corpus | Notes | Index size | Cold load | Reload | Search | Prefix | Fuzzy |
537
+ |---|---:|---:|---:|---:|---:|---:|---:|
538
+ | worst case | 1,000 | 1.3 MB | 219 ms | 23 ms | 0.35 ms | 0.22 ms | 0.32 ms |
539
+ | worst case | 5,000 | 6.8 MB | 1.10 s | 109 ms | 0.89 ms | 0.66 ms | 0.94 ms |
540
+ | realistic | 5,000 | 8.5 MB | 1.34 s | 134 ms | 1.20 ms | 0.64 ms | 1.02 ms |
541
+ | realistic | 20,000 | 34.5 MB | 5.4 s | 543 ms | 5.88 ms | 2.63 ms | 4.30 ms |
542
+
543
+ Auto-recall runs on every prompt, which is why the search path is
544
+ allocation-light: a dense scratch-buffer BM25 loop, posting lists in memory, and
545
+ snippets read only for the final hits. Recency scans are throttled
546
+ (`scanIntervalMs`) and coalesced from filesystem events (`watcherSettleMs`), so
547
+ a burst of edits costs one refresh.
548
+
549
+ ## Privacy and durability
550
+
551
+ - **Local only.** Nothing is sent anywhere except by the optional reranker and
552
+ session learning, which use the model you already configured and only when
553
+ enabled.
554
+ - **Files, not a database.** Memoria never owns your data: notes are markdown
555
+ with frontmatter, deletes are soft (moved to `.trash/`), and the index is
556
+ derived and can be rebuilt with `/memoria reindex`.
557
+ - **Crash-safe moves.** Category moves and renames are journaled, so an
558
+ interrupted move is completed on the next start instead of leaving two copies.
559
+ - **Atomic writes.** Every write goes through a temp file and rename; there is no
560
+ window where a note is half-written.
561
+ - **Secrets:** memoria does not scan for credentials, and the learn prompt tells
562
+ the model not to store them. If you keep secrets in the store anyway, remember
563
+ that recall may surface them in model context — treat the store like your shell
564
+ history.
565
+
566
+ ## Troubleshooting
567
+
568
+ | Symptom | Fix |
569
+ |---|---|
570
+ | Notes exist but recall finds nothing | `/memoria reindex`; check `/memoria paths` for the store location; remember scopes (`--all` searches every root). |
571
+ | A note is filed under `people.md` instead of the person's name | The topic was rejected as fact-shaped or relational. Write with the person's name as `topic` and put the relationship in the content. |
572
+ | The same subject ended up in two notes | `/memoria topics` lists merge candidates with the exact `memoria_move` command; `memoria doctor` reports them too. |
573
+ | `MEMORY.md` is over budget | `memoria_hot { action: "compact" }` drops the least important trailing paragraphs and returns them so you can file them into notes. |
574
+ | A decision changed | Write the new note with `supersedes: ["<old id, path or title>"]`; the old note stays searchable but is demoted and flagged. |
575
+ | Search misses domain shorthand | Add `synonyms.json` (see [Synonyms](#synonyms)). |
576
+ | Model reranking is slow | Lower `rerankTopK`, or leave `rerank` off — lexical search is already sub-millisecond. |
577
+ | Want to see what changed lately | `/memoria diff 3` for the last three days, `/memoria topics` for usage, and a session-start notification summarises changes since your previous session. |
578
+ | An agent edited files and the index is stale | Filesystem events and a throttled scan pick changes up automatically; `/memoria doctor` shows the state. |
579
+ | The user references something from before | The agent should search transcripts (`memoria_sessions`, or `/memoria sessions <query>`) rather than claim it does not remember; `/memoria paths` lists the session roots. |
580
+ | Session search finds nothing | Try different wording, a name or a date, or `include_tools: true`; check `sessionRoots` covers the transcript location, and note that a budget-limited scan reports `partial`. |
581
+
582
+ ## Development
583
+
584
+ ```bash
585
+ npm install # dev-only: pi host packages + typescript
586
+ npm test # 144 tests, node:test, no build step
587
+ npm run typecheck # tsc --noEmit
588
+ npm run eval # recall@1/@5/MRR over the fixture corpus
589
+ npm run bench # latency at 1k and 5k notes
590
+ npm run bench:real # realistic high-vocabulary corpus
591
+ pi -e ./index.ts # run the extension from the checkout
592
+ ```
593
+
594
+ The extension runs on Node's native type-stripping (`node >= 22.19`), which
595
+ means no build step but also no `enum`, `namespace`, constructor parameter
596
+ properties or `import x = require()` in the sources. Type-only imports must use
597
+ `import type`, and relative imports include the `.ts` extension.
598
+
599
+ Architecture, invariants and the release checklist live in
600
+ [`AGENTS.md`](AGENTS.md). The short version:
601
+
602
+ ```
603
+ index.ts lifecycle hooks, system-prompt section, auto-recall, auto-learn
604
+ src/types.ts shared types (no runtime imports)
605
+ src/util.ts atomic writes, mutex, debounce, ids, paths
606
+ src/frontmatter.ts dependency-free YAML-subset parser/serializer
607
+ src/tokenize.ts identifiers, camel/snake/kebab, CJK, stemmer, trigrams
608
+ src/config.ts defaults, coercion, path resolution
609
+ src/store.ts filesystem: parse, write, merge, move, MEMORY.md, indexes
610
+ src/index-engine.ts inverted index, persistence (JSON/binary), link resolution
611
+ src/search.ts BM25, boosts, snippets, explain, related/superseded handling
612
+ src/similarity.ts duplicate-topic and contradiction detection
613
+ src/usage.ts hits/writes/last-used tracking
614
+ src/timeexpr.ts "last week" → recency windows
615
+ src/synonyms.ts query-side synonym tables
616
+ src/transfer.ts JSONL export/import
617
+ src/learn.ts session extraction (chunked)
618
+ src/recall.ts prompt/message rendering
619
+ src/rerank.ts optional model reranking
620
+ src/runtime.ts roots, locks, caching, health, export/import, scopes
621
+ src/tools.ts tool definitions and renderers
622
+ src/commands.ts /memoria subcommands
623
+ ```
624
+
625
+ ### Publishing your own copy
626
+
627
+ 1. Push the repository to GitHub (public or private).
628
+ 2. Keep `index.ts` at the package root and the `pi` manifest in `package.json`.
629
+ 3. Leave the host modules as `peerDependencies` **and** mark them
630
+ `"optional": true` in `peerDependenciesMeta`, keeping them in
631
+ `devDependencies` for local tests only. Without that, npm installs a ~450 MB
632
+ duplicate of pi into the package.
633
+ 4. Tag releases (`git tag v0.1.1 && git push --tags`) and install by tag:
634
+ `pi install git:github.com/<you>/pi-memoria@v0.1.1`.
635
+ 5. `npm pack --dry-run` should list only `index.ts`, `src/**`, `skills/**`,
636
+ `README.md`, `LICENSE` and `package.json`.
637
+
638
+ ## Design notes and limits
639
+
640
+ - **Topic notes are the unit of storage.** This is deliberately opinionated: a
641
+ file per fact fragments knowledge and makes retrieval worse. The cost is that
642
+ the agent must pick a broad topic; when it picks badly, the store falls back to
643
+ the category rather than creating a bad file name, and `memoria_move` fixes it
644
+ later.
645
+ - **Lexical, not semantic.** BM25 with a conservative stemmer, prefix and fuzzy
646
+ matching is fast, deterministic and dependency-free, but it will not connect
647
+ "my manager" to "Alice" without an alias or a synonym table. Embeddings would
648
+ improve that; they are not worth the dependency for a store this fast.
649
+ - **Cross-topic duplication is reported, not merged automatically.** The store
650
+ flags two notes as duplicates only when their *names* also point at the same
651
+ subject (equal slugs, or one name being a prefix/suffix of the other — e.g.
652
+ `Alice` and `Alice Smith`, or a legacy `Johns father` note whose name appears
653
+ as an alias). Content overlap alone is not enough: one person's note naturally
654
+ describes the people around them, and merging John Doe with his father would be
655
+ worse than missing a duplicate. Folding notes stays an explicit
656
+ `memoria_move`, suggested on write and listed by `/memoria topics`.
657
+ - **Usage is derived data.** `.index/usage.json` drives staleness and promotion
658
+ hints; deleting `.index/` only loses those hints.
659
+ - **Journal recovery covers moves, not arbitrary edits.** A crash between an
660
+ atomic write and a trash move is repaired; a crash mid-edit of a single file
661
+ leaves the previous content intact (writes are atomic).
662
+ - **Model reranking instead of embeddings.** An embedding index would improve
663
+ semantic matching, but pi exposes chat completions rather than an embedding
664
+ API, and a vector store is a dependency this project does not want. The
665
+ optional reranker gets the same effect (an LLM judging the top candidates) and
666
+ degrades to lexical order on any failure. Time-scoped questions are handled by
667
+ parsing the window out of the query rather than by time-decayed IDF: the note's
668
+ own timestamp is the signal that matters.
669
+
670
+ ## License
671
+
672
+ MIT © 2026 rcsaquino. See [LICENSE](LICENSE).