Install
Install with PiG
pig install npm:pi-memoriaInstall with Pi
pi install npm:pi-memoriaPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"extensions": [
"./index.ts"
]
}README
Written by the package's publisher, shown as published in version 0.6.0 (README.md). PiG does not review it.
pi-memoria
Global memory for Pi: startup rules in SQLite, durable facts in SQLite FTS5, and cited search across every past conversation.
How it works • Installation • Hot memory • Tools • Configuration • Performance • Support
pi-memoria gives Pi one memory shared across every project: instructions that must apply from the first message go in a capped hot-memory table in memoria.sqlite, everything else lives in SQLite with FTS5, and past conversations stay searchable through ripgrep. Five tools, local storage only. No embeddings, no network calls, no background model work.
Requirements
- Node.js 22.19+ (uses
node:sqlite; earlier baselines 22.19/24.20 are historical, and the maintained offline suite uses 26.12.0). - A Node-based Pi host at
>=1.6.0 <2. The pinned development baseline is Pi 1.6.0, which the maintained offline suite uses. Standalone/Bun builds are not validated withnode:sqlite. - ripgrep (
rg), either on PATH or in Pi's managed<agent-dir>/bin/directory, for session search.
Installation
pi install npm:pi-memoria
This installs the current public npm release. The source version is recorded in package.json; unpublished checkout changes require a local install. This package works with no other package from this repository installed.
Activate with /reload in an idle session when intended, or a separately approved restart. To uninstall, run pi remove npm:pi-memoria; stored memory remains until you delete its directory.
Install from a local checkout
From the monorepo root:
npm --prefix packages/pi-memoria install --ignore-scripts --legacy-peer-deps --workspaces=false
pi install /absolute/path/to/pi-extensions/packages/pi-memoria
Keep the checkout in place: a local install references it directly. To try it without installing:
pi -e /absolute/path/to/pi-extensions/packages/pi-memoria/index.ts
How it works
| Store | What belongs there | How it is retrieved |
|---|---|---|
| SQLite hot table | Instructions that must apply before any retrieval cue appears | Injected before every user prompt and stored in memoria.sqlite |
| SQLite + FTS5 | Preferences, facts, decisions, names, conventions | memoria_search |
| Original Pi JSONL sessions | What was actually said, including old branches and pre-compaction messages | memoria_sessions, with file and line citations |
"Start every sentence with beep_boop" belongs in hot memory: even a session starting with "Hello" must obey it. "The user likes apples" belongs in SQLite with tags such as fruit and preferences: a fruit recommendation supplies the retrieval cue.
The model decides what to save and when to search; nothing is extracted automatically. Before saving, it searches for related memories, keeps unchanged facts, and edits existing ones when information changes. SQLite rejects repeated identical adds; differently worded paraphrases depend on the model's judgment.
Hot memory
Hot rules live in the hot_memories table in memoria.sqlite. The prompt receives only the rendered rules, never IDs, priorities, or a filesystem path:
- Start every sentence with beep_boop.
Priority is 0–100 (default 50) and controls eviction order only. The rendered block must fit in 5,000 UTF-16 code units; IDs, priorities, timestamps, and the wrapper do not consume that budget. Content is single-line; CR, LF, U+2028, and U+2029 are rejected.
Duplicate adds reuse the existing row and consume no capacity. When space is needed, strictly lower-priority rules are archived to long-term SQLite with tag hot-archive in the same transaction as the new write. If that cannot free enough room, the write fails and nothing changes.
memoria_search returns hot rules first and supports reading an h_ ID directly. Hot results carry no tags, so a tag filter returns long-term memories only.
If memoria.sqlite cannot be opened, hot rules are not injected. The prompt status reports that memory is unavailable instead of presenting an empty block.
Upgrading from MEMORY.md
The first run of this version imports a legacy MEMORY.md once, preserves its IDs and priorities, and then renames the file to backups/MEMORY-pre-sqlite-<timestamp>-<uuid>.md. The import and the hot-row insert share one transaction. A malformed file, a symbolic link, or a hot table without a migration marker fails closed and leaves the file untouched. Once imported, the file is never read again.
The schema moves to version 3 and an existing v1/v2 database is snapshotted first as backups/memoria-pre-v3-<timestamp>-<uuid>.sqlite. Older pi-memoria versions refuse a v3 database, so keep that snapshot until the upgrade is proven.
[!WARNING] Do not edit
memoria.sqlitedirectly. ManualMEMORY.mdedits stop working after the one-time import; use the memoria tools instead.
Recall
Keyword search uses the supplied terms with prefix matching and English stemming, not automatic terminology rewriting. Save personal shorthand as an ordinary fact containing both forms, for example The user's shorthand piem refers to the pi-extensions monorepo. Searching piem then retrieves that fact; use its meaning for a follow-up search when needed. Session search has no recency or project filter. For "remember when" questions, search sessions and cite the original entries; follow next_offset/next_text_offset, and check warnings and exhausted. A partial or failed search is never proof of absence.
Tools
| Tool | Purpose |
|---|---|
memoria_add | Save a fact to SQLite or a startup rule to hot memory |
memoria_edit | Change content, tags, priority, or hot text by ID |
memoria_delete | Remove a memory by ID |
memoria_search | Search hot and long-term SQLite memory with keywords, modes, and exact tags |
memoria_sessions | Search or read original Pi session entries with citations |
Tool replies are compact; oversized results spill to a private pi-memoria-result-* file.
Add a fact:
{"content":"The user likes apples.","tags":["fruit","preferences"]}
Add a hot rule:
{"store":"hot","content":"Start every sentence with beep_boop.","priority":90}
Search memories:
{"query":"kubernetes deploy","mode":"all","tags":["infrastructure"]}
Search sessions:
{"query":"deadline","role":"user","after":"2025-03-04","before":"2025-03-05"}
Read a session entry:
{"action":"read","path":"/absolute/path/to/session.jsonl","line":42}
- Add:
storeislong_term(default) orhot; long-term memory acceptstagsandsource. Identical content is reused withcreated: false; edits are the only way to change a fact. SQLite limits: 20,000 characters, 30 tags, 2,000-character source. Hot rules share a 5,000-character rendered budget and ignore tags/source. - Edit/delete: pass an
id(m_for long-term,h_for hot) and only the fields to change.expected_revisionor hotexpected_contentcatches concurrent writes. Deletion never archives hot rules or erases sessions. - Search:
memoria_searchsearches both hot and long-term SQLite memory. Hot results are listed first and expose their priority;tagsmatch exactly, case-sensitively, and exclude hot entries.modeisany(default),all,phrase, orliteral; a long-term miss falls back to a literal scan and reports the mode used. Read any memory with itsh_orm_ID; long content paginates viatext_offset. - Sessions: decoded JSON is searched, including hidden, ignored, and inactive-branch files. Results carry path/line citations. Symlinks are never followed during recursive search, so a link to an outside tree is not traversed or read; an in-root symlinked archive remains searchable through its canonical target path. Reads authorize only the canonical path, and a file that disappears mid-search is skipped with a warning.
exhausted: truemeans every accessible root was scanned without errors; warnings mean partial results, never absence.
Configuration
Environment variables and storage layout
| Variable | Effect |
|---|---|
PI_CODING_AGENT_DIR | Pi's agent directory; memoria defaults to its memoria/ child and looks for managed ripgrep in its bin/ child |
PI_MEMORIA_DIR | Override the single global memory directory |
PI_MEMORIA_SESSION_DIRS | JSON array of additional absolute session roots |
~/.pi/agent/memoria/
├── memoria.sqlite
├── memoria.sqlite-wal
├── memoria.sqlite-shm
└── backups/
Database startup recognizes truly empty stores and the exact shipped memoria v1/v2/v3 schemas, including legacy stores without an application identifier. A v1/v2 store is snapshotted before the v3 migration, and existing facts, archives, duplicates, and FTS indexes are preserved. Foreign, future, customized, or unsupported schemas are refused before chmod, journal-mode changes, or migration. Older package versions refuse a v3 store.
Database/companion files must be regular single-link files, and existing directory components cannot be symlinks. Unsafe -wal, -shm, -journal aliases and orphan companions are refused. A regular companion observed with zero links during SQLite last-close is rechecked by name, at most 32 times; it is never accepted as an unlinked file. Main-file unlink, nonregular entries and multiple links remain fatal. Ownership inspection uses a private mode-0700 temporary snapshot of the database/WAL/journal, because even SQLite READONLY can alter original SHM read marks. Snapshot files use 0600, copying uses a fixed-size buffer with bounded change retries, and cleanup runs on success/failure. Startup inspection is linear in stored bytes and needs temporary disk capacity; normal queries do not copy the store. Companion disappearance between stat/open or unlink of the same opened companion restarts the bounded snapshot inspection; identity changes and other open errors are not ignored. Concurrent supported startup still re-attests under its migration transaction. WAL-mode selection retries only the driver's numeric SQLITE_BUSY condition, rechecking path safety on every attempt within a five-second deadline; other errors fail immediately. These are focused startup checks, not an OS lease against uncoordinated path/schema mutations by another process.
Session search prefers Pi's managed <agent-dir>/bin/rg (rg.exe on Windows), then inherited PATH if the managed executable is missing (ENOENT). Permission errors or other operational failures are reported, not hidden by fallback. Resolution is retried on each search so a binary provisioned after extension loading is recognized. PI_CODING_AGENT_DIR uses the same absolute/tilde normalization as the memory configuration; PI_MEMORIA_DIR does not move the managed-bin location. Explicit executable overrides for custom callers/tests remain authoritative.
Memoria never downloads binaries or changes PATH. Normal interactive Pi startup can provision missing ripgrep on supported platforms. On an offline first start, after a failed download, or where Pi cannot provision it (such as Android/Termux), install system ripgrep or provision the managed binary separately. Android/Termux users can use pkg install ripgrep. Reading an original entry with action=read does not require ripgrep.
The default session root is <agent-dir>/sessions; roots Pi uses are remembered across projects, capped at the newest 100 entries. Configured roots are re-added after session-derived roots, so an explicitly configured archive is never the entry evicted by that bound; when old custom roots are evicted, the prompt status reports the count and points to PI_MEMORIA_SESSION_DIRS. Changing PI_MEMORIA_DIR selects a different store without migrating the old one, project cwd is never used to choose it, and no data is sent over the network. A malformed path override falls back to the host default paths and is reported in the prompt status instead of escaping the session handler.
Oversized tool results spill a private complete payload under the OS temporary directory. Spill directories are pruned to at most 100 entries and 24 hours, checked at most once per hour before a new spill; on a shared temporary directory, only directories owned by the current user are removed. Crash-left pi-memoria-inspection-* startup snapshots are pruned after one hour with the same ownership check.
Performance
Benchmark: 10,000 memories and 50,000 session entries (11.9 MB)
| Operation | Median | p95 |
|---|---|---|
| Selective SQLite FTS5 lookup | 0.093 ms | 0.119 ms |
| Exact-tag filtered FTS5 lookup (10,000 matching rows) | 6.308 ms | 7.365 ms |
| Literal SQLite full scan | 4.709 ms | 5.094 ms |
| Hot-file refresh with locking (historical) | 0.148 ms | 0.249 ms |
| Session match near the end of the corpus | 26.776 ms | 34.777 ms |
| Absent session term, complete scan | 4.325 ms | 5.172 ms |
npm run bench recreates this synthetic corpus in a temporary directory. These historical warm-cache medians were measured on Linux, Node 24.20, Ryzen 5 7500F, including rg startup; the hot row predates the SQLite hot table and is retained only as history. They are not current Node 26.12/Pi 1.6.0 acceptance evidence. Indexed lookups stay fast; scans grow with corpus size. Not a performance guarantee.
Development
From the monorepo root:
npm --prefix packages/pi-memoria install --ignore-scripts --legacy-peer-deps --workspaces=false
npm run link-host
npm --prefix packages/pi-memoria run verify
npm --prefix packages/pi-memoria run bench
No package lockfile is currently committed, so npm ci is not a fresh-checkout setup command. The shared host-link helper preserves working dependencies and only repairs missing/broken links.
There is no build step: Pi loads index.ts directly. src/database.ts owns persistence, src/hot-memory.ts owns the hot model and prompt renderer, src/hot-migration.ts owns the one-time import, and src/sessions.ts owns session search; index.ts wires them to lifecycle events and the tool schemas. Tests use temporary directories, real SQLite FTS5, real rg, concurrent writers, and Pi's extension loader. Test and benchmark files are checkout-only and excluded from the published tarball. See AGENTS.md for architecture and contribution rules.
Support and contact
If pi-memoria is useful to you, you can support its development on Ko-fi.
