Skip to main content

Sourced from docs/orchestrator-storage.md in the firmware repo.

Nimbus Tiered Storage Architecture (SD-primary)

Canonical record of what data lives where in the Orchestrator "World" memory system, and why. Companion to orchestrator-world.md (the cognitive tiers) and the orchestrator live turn (the live turn). Read this before touching memory_subsystem, vector_memory, episodic, or the SD mount.

0. The design rule​

All bulk data (vectors, episodic history, media blobs, logs) lives on the SD card. Internal flash and RAM hold only small critical config and a bounded degraded cache. Two hardware constraints shape the rest: working sets belong in the 8 MB PSRAM, not the ~300 KB internal SRAM, and the device must keep working, with bounded storage, when no card is present.

The pre-redesign code violated this rule in three locatable ways:

  1. VDB working set in internal SRAM. g_vec holds std::vector<VecEntry> on the default heap. At maxVectors=2000 (256-dim int8) that is ~1.14 MB - guaranteed OOM on a device with tens of KB free internal heap.
  2. Episodic is a 500-message RAM ring whose whole blob is rewritten on every captureMessage - O(history) write amplification and a hard 500-message ceiling, the opposite of "all history on SD."
  3. Persistence defaults to LittleFS and only routes to SD if setDataFs(SD) runs. With no card, vectors grow unbounded on the ~few-MB LittleFS partition with no overflow guard - the one genuinely dangerous path (flash exhaustion).

1. The four tiers​

Rule of thumb:

  • NVS - tiny critical config that must survive an over-the-air firmware update and is human-set (model-read-only). Card-independent.
  • LittleFS (internal flash) - firmware + ephemeral per-turn scratch + a bounded degraded fallback cache when there is no SD.
  • PSRAM-working (8 MB) - in-RAM working sets and indices (volatile, rebuildable from SD/flash): the VDB search set, the episodic recent window.
  • SD (durable) - the system-of-record for everything bulk.
Data typeTierFormat / pathNo-SD fallback
VDB vectors - working setPSRAMentries_ in PSRAM heapreduced-cap set still in PSRAM (or internal if no PSRAM)
VDB vectors - durableSD/mem/vectors.bin (existing serialize blob)/data/orchvec.bin on LittleFS, hard-capped (≈400 vecs) + eviction
Pending memory writes (embedding outage)SD/mem/pending_embed.bin (at most 64 facts or 48 KB; text only)/data/pendemb.bin on LittleFS, behind the same free-space floor as the vectors
Episodic - full historySD/mem/episodic/YYYY-MM-DD.jsonl append-log + index.binin-RAM 500-ring + /data/episodic.bin whole-blob (as before)
Episodic - recent windowPSRAMrecent-N ring, hydrated from SD at bootthe ring is the whole history
Media / voice / artifactsSD/mem/blobs/<hash>.<ext> content-addressedephemeral only (/voice.pcm, /reply.mp3, /audio/tgvoice.ogg), deleted per-turn - no durable media
Telegram archive (every message and file in or out, full size)SD/mem/tg/<chat>/<day>/ raw JSON, media and index.jsonl (memory.md, section 4)not kept (SD only)
Scratchpad (goal tiers)LittleFS/data/scratchpad.bin (~4 KB; the orchmem NVS copy until v4.5.14)unchanged
Usage ledger (spend and budgets)LittleFS/data/usage_ledger.txt (the usgLedger NVS key until v4.5.14)unchanged
Provider park (out-of-credit and refused-key parks, their re-check times, the once-per-episode billing notice and its one short answer, and the daily spend warning, per provider)LittleFS/data/provpark.txt (a few lines; rewritten whole on every change)unchanged
Sub-agent journal (running helpers and the last 8 finished)LittleFS/data/agjournal.json (the agjournal NVS slots j0..j5 until v4.5.16; see the sub-agent journal)unchanged
Managed-agent ids (Anthropic environment and agent map)LittleFS/data/ant_env.txt, /data/ant_agents.txt (the antEnv and antAgents NVS keys until v4.5.16)unchanged
RoutinesLittleFS/data/loops.json (written atomically; a routine fires only after its next slot was saved)unchanged
Provider keys / routing / configNVSsolide::memory keysunchanged
Verify cacheNVSvfy_*unchanged
Provider model lists (the model store, rebuilt by every verify)LittleFS/data/models_<provider>.txt (see the NVS budget)same LittleFS
Logs / diagnosticsDurable error log (GET /api/errlog) on SD /log/nimbus.log (rotated 4x256 KB), plus the 1280 B RAM ring (GET /api/log) + serial. Beside it in /log: the boot counter (boot.n) and the crash dedupe record (crash.seen). Device EVENTS are also durable via the episodic system timeline (kind=log); events captured before the clock syncs wait in /mem/pending_ev.txt-flash fallback /log on LittleFS (2x24 KB) + RAM ring; held events in /data/pending_ev.txt

Two things do not move: NVS config/keys/verify are already at the right tier and are card-independent - the "critical info" the design rule keeps off SD. Rebuildable caches never live in NVS: the 20 KB partition is reserved for owner config and bounded values (the full rule and the HTTP 507 contract for a save that does not land are in the Config and NVS reference). Everything bulk targets SD with a bounded LittleFS/RAM degraded mode.

Durable log: what persists, and its best-effort limit​

The durable error log does not persist every line. Persistence is scoped by severity: warnings, errors, and tagged key events (memory, provider, relay, OTA, panel, NVS, storage, network, boot) are written to the log; routine info-level lines stay in the RAM ring and serial only. This bounds internal-flash write wear over the device's lifetime rather than writing every diagnostic line to flash.

A durable write is best-effort. Each log call takes the shared card lock with a short timed try-acquire; if a large memory persist is holding the card, the write is skipped so the log call never stalls the watchdog-guarded loop. A contention skip is never a silent loss: the RAM ring and serial still hold the line, a dropped-line count is recorded into the durable log itself at the next successful write, and the running totals (X-Log-Durable-Skipped, X-Log-Durable-Bytes) are returned as headers on GET /api/log (the bytes header is left out while a tool holds the card), in GET /api/errlog?list=1, and on the device health row. If you need every line during a heavy-churn incident, read the RAM ring (GET /api/log) continuously rather than relying on the durable log alone.

No task the watchdog watches waits for the card lock. The 8 s task watchdog watches two tasks: the main loop and the web server's task (every web request, the cloud tunnel's included, runs on it). A turn holds the card lock for the whole of each tool call, which can include a long card scan. So every piece of card work the loop does (the SD health probe, the held timeline rows, the battery history row, a timeline event such as an SD edge) tries for the lock for at most 20 ms and, when a tool holds it, skips that pass or parks the event for a later one. A web request tries for at most 150 ms (GET /api/state, 20 ms) and, when the lock stays busy, GET /api/state answers at once with the last card figures it read and "cardBusy": true, while the other card routes answer 503 with Retry-After: 5 and {"error":"busy"}. A download read from the card (the durable log, a stored file, an archive item, an archived day as a ZIP) is a card stream instead: it tries the lock for 20 ms at every step, from opening the file to each read, and while a tool holds the card it sends nothing and tries again at the server's next poll (every half second), so it waits out the hold and completes. Its waits add up to at most 60 s (10 s through the cloud tunnel, inside the tunnel's own read limit); past that, a download that has sent nothing answers 503 with Retry-After, and one already under way is cut, so it shows as failed, never as a short file that looks whole. The web page treats every 503 with Retry-After as busy: it keeps what it showed, says "The SD card is busy right now. Retrying in a few seconds." above the section ("The device is busy right now." when working memory is short), and loads it again after the Retry-After. A download or preview retries a busy answer up to twice, saying "Waiting for the SD card". A tool call that holds the lock for 3 s or more is named in the durable log (memory: tool <name> held the card lock for <ms> ms), and a loop pass of 2 s or more is logged too (loop: one pass took <ms> ms ...). Earlier firmware waited for the lock: a tool call that held it past 8 s stopped the loop (fixed in v4.5.16), and on v4.6.0 a GET /api/state that arrived while a photo look-up held it stopped the web task, and the watchdog restarted the device.

No task holds the card lock across a network request. A tool that waits on the network (image.look, image.generate, web.search, reply.telegram, reply.speak, device.control with its speech action, and the tools of a connected tool server, mcp.*) runs outside the tool dispatcher's card lock and takes the lock only around its own card reads and writes; a memory tool's embedding gives the lock up for its request and takes it back after. The LAN /mcp endpoint, whose request runs on the web task, refuses those tools with an error. A web request's own network wait is bounded too: the host must already be in the device's name cache (an uncached name starts a lookup and the request answers busy), at most 250 ms for the device's network slot and 5 s for the whole exchange, and every exchange one request starts draws on the same 5.25 s allowance: a LAN /mcp memory.update that finds the fact by its description embeds twice, and the second embedding runs only if at least 2 s are left (else it answers busy, and the update stores the new fact as new and keeps the old one, as it does whenever that embedding fails). The test build's WEBGUARD? console verb reads the counters that prove it on a bench unit.

No line is lost before storage mounts. The first lines of a boot (the boot record, the HAL and network lines, an [sd] mount FAILED diagnosis) are emitted about a second before any filesystem is mounted. They wait in a bounded early backlog (24 lines or 4 KB) and are written, in order, when storage attaches: the SD card right after its mount (in both modes), or LittleFS right after memory::begin() mounts it when there is no card. If the backlog overflowed, one marker line gives the exact count. A unit with nowhere to write (Notifier mode with no card) frees the backlog at the end of start-up. The card lock exists from the top of setup() in both modes, so the early attach never opens a second writer on the card. A tier change is logged only when it really happens mid-run (SD lost: ... / SD available: ...), never on a normal boot.

One open file. The active log file is held open; each line is one write plus a flush (an fsync, so a line written right before a crash is on the card). The file is reopened only on rotation, a tier change, a remount or a write error. If it cannot be opened, the log degrades to the RAM ring and retries at most every 10 seconds, and the first line after recovery is followed by a marker with the number of lines missed. (Opening a file per line made every log line an internal-RAM allocation that aborts on failure, so the log could turn a low-memory moment into a crash.) The handle is closed before anything unmounts or reformats the card, and during a factory erase.

The forensic window. Routine copies of the per-request relay lines, the per-exchange transport: heaptrace line and the per-round headloop line stay in the RAM ring and on serial. The durable log keeps the abnormal ones (no response, a 5xx, a capped round, internal memory under 12 KB free or an 8 KB largest block) and one folded relay summary every 15 minutes. These lines once filled 83-98% of every rotated SD file, so whatever led up to a crash aged out within hours.

Boot record and crash report​

The first durable line of every boot is its boot record:

boot: n=17 fw=v4.5.14 build=v4.5.14-3-gabc1234 reason=usb(0x15) wake=none mode=orch t=0 prev=none

n is the boot number (kept in /log/boot.n, stamped into the line when storage attaches; serial shows n=?). reason names every ESP-IDF reset reason with the chip's raw reset code beside it (one table in nimbus/sys/reset_reason.h; unknown only for value 0 or an out-of-range value, always with the number). t is the wall clock the chip kept across the reset (software, panic and watchdog resets keep it), else 0. prev is where the previous run stopped, from a 48-byte record in RTC memory that every boot stage, turn start and turn round updates (and the main loop every 5 seconds): for example prev=n16/367161s/turn-r2/h1180 (boot 16, 367161 s up, round 2 of a turn, lowest internal free heap 1180 B), or prev=1s/storage for a boot that passed the SD mount and died in the memory load. It survives software, panic, watchdog and USB resets and deep sleep, so it explains a brownout-like or early-boot death that leaves no core dump; a power cycle clears it (prev=none).

Every panic and watchdog reset writes a core dump to the 64 KB coredump flash partition. The next boot reads it once, right after storage attaches, and writes:

crash: fp=1a2b3c4d new=1 this-reset=1 task=tg_poll pc=0x4201abcd cause=28(LoadProhibited) vaddr=0x00000000 size=23456/65536 elf=0badf00d1 fw-match=1
crash-bt: depth=12 corrupt=0 0x4201abcd,0x4201b0c4,...
crash-why: Stack canary watchpoint triggered (tg_poll)
  • fp is the dump's own stored checksum, so the same dump reads the same fingerprint on every boot. /log/crash.seen records the last one reported: a dump already reported is mentioned once per boot as a single crash: line with new=0.
  • this-reset=1 when this boot's reset was the crash; fw-match=0 after an update, because the dump belongs to the previous release (decode it with that release's ELF).
  • crash-why is the panic message the dump recorded. ESP-IDF records one only for abort() (the stack-overflow check aborts too) and the task watchdog. A CPU exception, the end-of-stack watchpoint and the interrupt watchdog record none, so the reason is then built from the exception cause, for example crash-why: StoreProhibited in loopTask: a write to an invalid address (0x00000000); no panic message in the dump. Every crash states a reason.
  • The report never contains stack bytes or the exception registers: a stack in transit can hold a provider key or the bot token.
  • The dump is never erased by the reader, so a bench can still pull it over USB; the next crash overwrites it, and a factory reset erases it.
  • The same summary is in GET /api/state (boot.crash, null when there is no dump) and on the episodic ev:boot row, so the assistant can say why it restarted. A crash whose own dump was not saved (it did not fit the 64 KB partition, or the write failed) never borrows the stored, earlier dump's cause: its row says crash=unsaved "no crash report was saved for this restart; ...".
  • After a crash boot the owner gets one plain-words Telegram message that says what went wrong (a software error, part of it stopped responding, it ran out of memory, or one of its jobs ran out of memory) and names the request that was cut short (/crash/turn.json on LittleFS, written at turn start and cleared when the turn ends; the round reached rides the RTC record above). The file is skipped when internal memory is below the forensic floors, because a file open is itself an allocation that aborts on failure; the RTC record still names the request then.
  • When: at once when the crash cut an owner request (a message, photo, voice message, file or console request - the owner is waiting on that reply). A crash that cut a background turn (a routine, such as the nightly memory pass) is held and sent once, at the owner's next turn; a crash with nothing in progress still goes out at boot. Never more than one notice per boot (nimbus/orch/restart_notice.h).

Device events captured before the clock syncs (a power-on boot has no time until SNTP answers) wait in a 16-row / 4 KB file on the data store instead of RAM, so an offline boot or an early crash loop no longer loses its boot row: the first sync on any later boot writes them, labelled with the boot that captured them ("from boot n=12, clock never synced", or "from an earlier boot" when that boot's number was not recorded). The file is rewritten through a temporary copy and a rename, so a restart in the middle of a write keeps every row already held, and the rows the syncing boot added itself are told apart by their place at the end of the file, never by their boot number.

2. VDB - working set in PSRAM, durable on SD​

The engine is in-house, not a ported vector database: VectorMemory (lib/core) is a flat (brute-force) cosine store over int8-quantized vectors at a set-once dimensionality (256 by default; the embed gate may lock a provider-native width). "Flat" means every recall scans every candidate - fine for the low thousands of small vectors a desk device holds, and it needs no index to keep in sync. Recall is relevance x recency x importance with query-time TTL filtering, near-duplicate collapse, and MMR-on-ties. The whole store is browsable and capped; there is no ANN library and no on-device embedder (vectors arrive already embedded through the provider /embeddings seam).

VectorMemory is portable/Arduino-free and allocator-agnostic, so its allocations are routed from the device seam, not by editing the portable class.

  • Working set → PSRAM. Place the engine and its hot storage in PSRAM via heap_caps_malloc(MALLOC_CAP_SPIRAM) (the pattern the PSRAM-mbedTLS allocator already proves - see the nimbus-psram-tls note). Gate on esp_psram_is_initialized() at boot; if PSRAM is absent, fall back to the reduced-cap internal path (§4). Capacity: 256-dim int8 ≈ 570 B/vector in RAM ⇒ ~6000 vectors fit in the PSRAM budget after TLS/JSON headroom (device cap set well below kMaxVectorsMax). Dims stay locked by the set-once embed gate.
  • Durable → SD. Keep the byte-clean serialize/deserialize blob; change only the path (/mem/vectors.bin) and the write discipline: a dirty flag set by mutating ops only (not read-only recalls), debounced, written .tmp→rename for crash-atomicity. This kills the "rewrite the whole blob after every tools/call" amplification.
  • Migration is already half-built: loadBlob reads SD-first, LittleFS- fallback, so the first SD-backed persist carries existing LittleFS memories onto the card.

2a. Archive - the TTL-expired cold store​

Re-embedding text is the expensive operation the device most wants to avoid, so a memory that reaches its time-to-live is not deleted - it is moved to an archive, embedding and all, where it can be searched or restored later without paying to embed it again. This exists only on the SD card. With no card the live engine drops entries at TTL exactly as before; an archive is a bonus of having storage, never something the card-less device pays for.

  • Same engine, separate store. VectorArchive (lib/core) is the same in-house int8 flat-cosine PSRAM store as the live VDB, persisted to its own SD blob /mem/archive.bin (byte-clean serialize/deserialize, .tmp→rename, written only when a dirty flag says it changed). It is a distinct engine, not a flag on VectorMemory, so archived entries are invisible to normal recall by construction - they are simply not in the live set.
  • Expiry moves, not deletes. VectorMemory::pruneExpired takes an optional archive sink. The device attaches it only when a card is present, so the nightly maintenance pass that used to delete an expired entry now moves it into the archive instead. On SD loss mid-run the sink detaches (back to drop-at-TTL); on recovery it re-attaches.
  • Capped, FIFO. The archive is bounded (default 2000 entries); when full the oldest-archived entry is evicted first. Pinned/creator memories never expire, so nothing pinned is ever in the archive.
  • Tools, gated on the card. memory.archive (search | restore | list) is registered only when the archive is bound (i.e. a card was present at boot), and every action re-checks the card is still there (a mid-run pull refuses cleanly). restore brings an entry back into the live store, quota-respecting: it resets the TTL clock, lifts importance above the prune floor, honors max_vectors and the pin budget, and - if the live store is at its cap - refuses without losing the archived entry. All of it stays inside the caller's namespace boundary: a member only searches or restores its own archived memories.

3. Episodic - SD append-log + index, PSRAM recent window​

Decision: append-only JSONL day-streams + a compact binary offset index - not a SQLite dependency. Append is O(1) (seek-end, write one line); the index makes date/session/kind queries cheap; a truncated last line is tolerable (same philosophy as the tolerant vector deserialize); and it matches the documented design intent (an append-only JSONL day-stream). SQLite stays deferrable behind the same EpisodicStore interface. This resolves the long-standing F10 "SQLite-on-SD unbuilt" item without the lib.

/mem/episodic/
2026-07-04.jsonl # append-only, one EpisodicMessage per line
index.bin # (tsHours, sessionId-hash, kind, day, byteOffset) fixed-width
sessions.jsonl # append-only EpisodicSession rows
  • Append path: captureMessage writes one JSON line to today's file + one fixed-width index record. No whole-file rewrite → the 500-cap that protected the rewrite is lifted.
  • Recent window (PSRAM): an InMemoryEpisodicStore recent-N ring, hydrated at boot by tailing the newest day-streams; serves context assembly + memory.* reads without SD I/O. It stops being the system-of-record and becomes a cache.
  • Query path: the existing MsgQuery (session/kind/time-window/textContains/ limit) is served index-first (skip day-files outside the window; reject on session/kind before opening the JSONL; textContains scores the survivors by the shared word rule, see "Text search" in §3a). A window fully inside the recent ring answers from RAM with zero SD I/O. Same semantics the in-memory store is host-tested against ⇒ tests transfer.

3a. Deep history - the boot index, the backfill, and the cold query​

The boot scan is deliberately budget-bounded (kHydrateMaxRows 4000 / kHydrateMaxBytes 256 KB): an unbounded scan of a busy month's history took long enough to trip the boot watchdog, leaving a device that could no longer start. The byte budget is the one that binds - real rows average about 600 B on the card (trace rows run near 1 KB), so the boot scan indexes roughly 400 rows. Two rules keep that partial index honest:

  • The boot index is a contiguous suffix of history. The scan walks the newest day first and stops after the first file it could read only in part, or when less than kHydrateMinTail (4 KB) of the budget is left. It never indexes an isolated older row below a hole, so the index floor, the cold cursor and "newest first" ordering all describe the rows the index really holds.
  • The index converges to the whole card after boot. backfillStep() indexes what the boot scan left out, newest region first, one backward window at a time (8 KB and at most 32 rows per slice; a window grows only for a single long record, up to 128 KB). The main loop drives it (memory::episodicBackfillTick): at most one slice per 250 ms, only while no turn is in flight, only when the TLS work slot is free (acquireWork(0)), and only if the card lock is free within 20 ms. No task of its own, no TLS, no NVS and no new on-card format: the index is still rebuilt from the day-streams on every boot. The SD log records memory: episodic index complete (N rows, M added in K slices, ...) when it is done. The index is capped at kIndexMaxRows (20,000 rows of 72 B on the device, 1.44 MB of PSRAM); past the cap, or with a record too long to read whole, the index stays marked incomplete and says so. A file that keeps failing to read pauses the backfill, which retries every 5 minutes from where it stopped; the index stays marked incomplete meanwhile.
  • The index grows in steps, never by doubling (v5.1.2, after a bench restart: past 16,384 rows the doubling asked for one 2.4 MB block while the old 1.2 MB one was held, under a turn's PSRAM and 20 KB of internal ballast, and the uncaught std::bad_alloc restarted the device). Every growth adds at most kIndexGrowRows (2,048 rows, about 147 KB). At the cap the backfill asks for at most the cap plus the free-slot target ((20,000 + 1,024) x 72 B = 1,513,728 B), and a live append past it asks for its size plus one step (22,048 rows, 1,587,456 B, at 20,000 rows; more as live appends grow the index past the cap over a long uptime, as in v5.1.1). The backfill asks for its slice's room before it reads, decodes or moves anything; a refused reserve leaves the index as it was ("no progress this step"), and after kBackfillMaxReadErrors (8) refusals in a row the backfill stops in its existing stalled state (incomplete for this boot; the log line memory: episodic index incomplete (N rows; memory for its growth was refused 8 times in a row) ...; the next boot tries again). Each backfill step also tops the index up to at least kIndexFreeSlots (1,024) free slots, and so does a live append; a refused top-up changes nothing and is tried again only after 256 more live appends. The top-up fires only once the free slots fall under half that target, so a new device's first 2,048 messages reallocate the index a few dozen times, not once each. The step is min(2,048, the index's size) rows, so a small index never asks for more than v5.1.1's doubling did, and the free-slot target is min(1,024, the size); the backfill only skips its reserve when its slice and those free slots are both already there, and keeps them at the cap too, so it never ends with the index full. A live append whose top-up has failed and whose own step is refused still throws, as in v5.1.1: the device restarts and the boot scan rebuilds the index from the card, where every row already is.
  • Abort sites that remain (a refused block still throws out of the store; for the v5.2.0 audit): the live append's step growth (above); the boot scan's vectors and the move of up to kHydrateMaxRows rows into the index; the recent ring's copies (live, held and backfill) and the held rows; each index record's two strings; the backfill's temporaries (its rows, ring copies and window); the cold and after reads' windows; the retention sweep's hash buffer. A JSON document whose pool is refused while decoding a row reads as a torn line and the row is skipped, and the store's JSON allocator asks for a new block even to shrink one (ArduinoJson does not check that call). Outside this store: the conversation cache's rows, the vector memory's entries, the result store, the transcript, the jobs ledger and the web chat.

indexComplete() is the store's honest answer to "does the index hold every row on the card". It is false while the backfill runs (or after it stopped short), and everything that consumes the index reads it: retention defers the blob sweep (§4), the memory.episodic count says "older history on the card is not in this count", GET /api/mem/episodic returns indexComplete, and /api/state returns epiIndexComplete.

While the index is incomplete, the older rows are on the card but not in the index, and the cold query reaches them:

  • Text search (nimbus/orch/lexical.h) - the text filter splits the query into words (whitespace and punctuation), drops common words ("the", "my", "what", ...) and one-letter words, trims one plural or verb suffix ("boats" -> "boat"), and matches case-insensitively by substring (a word under 4 bytes must start a word, so "ai" never matches "said"). A row matches when any counted word occurs. With two or more counted words the page is ranked: rows holding more of the different words come first (ties: newest first), the store examines every row in the call's window (the RAM ring, the read-budgeted index, or the cold budget) and keeps the best limit (capped at 200), and EpiQueryInfo::matched reports how many rows matched so a short page is never presented as everything. The scan stops early once the page is full of rows holding every word (nothing can beat them), so paging with the cursor never skips a full match; a partial match that ranked below the cut in its window is counted but not returned. One counted word keeps the old contract exactly: newest-first, stop at limit, page with no row lost. A query of only common words matches nothing and reads nothing. The old rule required every word, so a three-word query found nothing when the stored row held only one of them. Memory: the parsed query is ~220 bytes on the caller's stack, a ranked page adds one score byte per kept row (at most 200 bytes of heap), and matching scans each row in place with no per-row allocation (the old matcher lowercased a full copy of every row).
  • Cold query (MsgQuery::coldScan, opt-in) - when the indexed range comes up short, walk the day-streams below each file's own index floor, newest record first, reading backward in bounded windows. The unindexed region is per file: the boot scan reads each day-stream's tail, so the newest file can hold thousands of rows above the global floor day. Two budgets keep a single call safe on the querying task - at most a few files and ~128 KB per call - and the pass pages: it reports the exact cursor to resume from.
  • Cursor (MsgQuery::before) - a row id for the indexed range, a "<day>:<offset>" byte cursor for the cold range. The store emits the next token; no caller (and no model) computes one. The indexed range is itself budgeted, so even a query that never leaves the index pages: rows still in the RAM ring are matched from memory, older rows come off the card in blocks (one read covers a run of neighbouring rows of one day-stream that the in-RAM filters keep, up to the 8 KB window; a lone match reads only itself), at most 120 reads and 128 KB per call.
  • Honest floor (EpiQueryInfo) - every answer carries how far back it looked, whether older history remains, and the resume token. A call that stopped early (budget or a full page) reports the day it reached, not the index floor. "No results" from a bounded read is reported as exactly that, never as "it never happened".

Surfaces: memory.episodic cold-scans by default and takes before; its result ends with a "searched back to <date>; older history exists … before=<token>" line when there is more. GET /api/mem/episodic gains cold / before params and returns searchedTo / olderExists / nextBefore (and matched, the rows the text filter matched in the range searched) and indexComplete; GET /api/mem/stats exposes epiTruncated + epiFloor, plus epiIndexComplete, epiBootIndexed (rows the boot scan indexed) and epiBackfillRows (rows indexed after boot). The [HOW YOU RUN] prompt tells the model the log reaches months back and to search it before claiming not to remember. Hot per-turn windows never set coldScan, so they stay zero-read.

⚠ The window is a heap allocation on the querying task. The web task holds ~8 KB of stack next to ~60 KB of free internal SRAM, so the window size is a crash boundary, not a performance knob - an early 128 KB window took the device off the LAN mid-query. Kept small (8 KB, escalating only for an over-long record); the budget is what bounds the work, not a big buffer.

4. Media / blobs - SD /mem/blobs, referenced by episodic blobPath​

Content-addressed sidecars: on capture (Telegram voice note, mic record, inbound image/doc), hash the bytes → /mem/blobs/<hash>.<ext>, then captureMessage(kind=Audio/Image/File, blobPath=…). The episodic row is the index; the file is the payload; identical bytes dedup for free. Ephemeral in-flight files (/voice.pcm, /reply.mp3, /audio/tgvoice.ogg) stay transient LittleFS scratch (privacy-deleted per turn); the durable copy is the SD sidecar (erase the card to purge).

Retention. Every ~6 h the main loop runs memory::pruneRetention(30) (nimbus/orch/retention.h holds the portable rules, host-tested):

  • Day-streams older than 30 days are removed. They are chosen by file name, not from the index, so a day the index never saw still ages out.
  • Blob sidecars no row references are removed by a reference-count sweep, but only when the index is complete. With rows on the card that the index has not reached yet, "referenced by no indexed row" would include blobs those rows still point at (this deleted a field device's attachments after a restart). The sweep is then skipped, the report says blobGcSkipped, and the log reads blob GC deferred: index incomplete; a later pass sweeps once the backfill is done.
  • Never during a turn, never waiting on the card lock. While orchestrator::turnInFlight(), or when the card lock stays busy for 50 ms (a web query or a memory tool holds it), the pass touches nothing and is deferred; it stays due and runs on the first loop pass after that ends (RetentionSchedule), logged once as retention deferred.
  • The Telegram archive is exempt. Nothing under /mem/tg/ is ever deleted by retention (isRetentionExempt, the one predicate every retention delete passes).
  • Internal heap. Every container the pass builds (the day list, the reference set, the orphan list, the report) uses the PSRAM working allocator, and directories are read with readdir (no file opened per entry), so a pass over thousands of rows or blobs does not hold hundreds of small internal-heap blocks.

Test builds can ask for a pass out of schedule with POST /api/test/epiprune; it goes through the same schedule and gate.

4b. Effect ring - SD /mem/fx (each chat's recent effects)​

What the device actually did in each chat lately (nimbus/orch/effect_ring.h, lane RB-FX, host-tested in test/test_effect_ring). The truth check reads it, so a true "I logged it at 13:02" is not taken for a false claim, and the old engine's recent-actions view is rendered from it. Every turn effect lands here through the engine's Hooks::onEffect: a head tool call whose kind changes something (with its result) and each outcome the turn's apply recorded (with the per-turn effects record's summary of it). Lookups do not.

  • One file per chat, /mem/fx/<key>.ring, outside the file index. The key is the Telegram chat id itself, or k plus the hex of any other chat id of up to 23 bytes.
  • One line per effect: f1, the time (UTC seconds, 0 when the clock was not set), the tool, a one-line receipt of at most 160 B and a crc32, tab-separated. Receipts are cleaned at append (no control characters, valid UTF-8, clipped on a character boundary).
  • RAM keeps the newest 50 per chat (in PSRAM, at most 8 chats resident). Every effect is one append of one line. At 100 lines the file is rewritten from RAM (a temp file, then a rename).
  • A torn last line is dropped when the file is read, and the next line is never glued onto it. A temp left by a cut or refused rewrite is removed beside a whole file, or becomes the file when it is the only copy.
  • No card: the ring runs from RAM and says so (Backing::RamOnly). A refused memory allocation is a designed answer (AppendResult::NoMemory), never a restart.

5. Migration and no-SD degraded mode​

Boot/mount: solide::storage::begin() → on success setDataFs(SD), g_haveSd=true. LittleFS always mounts (config + migration source + degraded store). esp_psram_is_initialized() decides PSRAM vs reduced-cap internal.

Migration (one-time, on first successful SD mount): vectors migrate via the existing SD-first/LittleFS-fallback loadBlob; episodic replays the old /data/episodic.bin blob into day-stream appends, then drops a .migrated marker (no double-migrate).

Degraded mode (g_haveSd==false) - the system still works, bounded:

SubsystemDegraded behavior
VDBworking set in PSRAM (or internal); durable to LittleFS hard-capped ≈400 vecs + score eviction. Closes the unbounded-flash bug.
Episodicno-card-AT-BOOT: in-RAM 500-ring + LittleFS whole-blob. A MID-RUN demote keeps the append-log: new rows stay queryable in the RAM ring and are held, then written to the card in arrival order once it answers (see 5a).
Mediarefused, not degraded (since v3.7.0): an inbound photo or document is not downloaded: sent on its own it gets a plain reply asking the sender to describe it in words, and inside a message or an album the turn names it as not kept ("no memory card in the device"). Media on internal flash would compete with the firmware's own OTA slots for a 3.5 MB partition, and one phone photo can be a sixth of it. Voice notes still transcribe (the audio is transient); only the durable copy is skipped.
Files (artifact store)unavailable: artifact.save fails with a legible reason and the listing reports present:false.
Tenants (roles + quotas)fully functional - the table lives on internal flash, not the card, so losing a card never drops everyone's role.
Privacy boundariesfully enforced - namespace and session filters live in the portable query layer, not the SD path, so degraded mode cannot open up what full mode keeps apart (asserted by tests/hil/test_l20_degradation.py).
Journal / logslast-N RAM ring + small rotating LittleFS file.
Config / keys / verifyfully functional (NVS).
Scratchpad, usage ledgerfully functional (LittleFS /data, card-independent).

Verification signal (per AGENTS.md's bar): a no-card boot logs memory: storage tier=flash /data (no SD) sd_mounted=0 ..., the dashboard shows the banner "No SD card - memory is limited to N entries on internal storage, with no durable media or history. Insert a FAT32 SD card for full storage.", the STATUS console line reports sd=absent (and /api/mem/stats reports sdPresent:false), and a RENDER?-assertable indicator lets HIL prove the degraded path. SD is re-probed live (/api/sdprobe / timer / menu) so inserting a card upgrades the tier + runs migration without a restart.

⚠ The boot scan is BOUNDED, and must stay that way (F31). hydrate() runs inside setup(), before the device can serve anything, on a path the watchdog watches. It used to read every day-stream whole and parse every row; a device that had merely accumulated ~15 K rows could no longer start, and no amount of power-cycling helped - retention prune runs after boot, so it could not recover the device either. The scan now walks the newest day first and stops at a row budget, a total-byte budget, and a per-FILE window read as the file's tail (a single oversized file defeats a per-scan-only budget). Older rows stay on the card and remain reachable by a dated query; they are simply not indexed at boot, which hydrateTruncated() reports, and the backfill (§3a) indexes them after boot from the main loop. Any future work here keeps that property: a device must be able to start regardless of how much it has written.

LittleFS overflow guard: the degraded VDB persist checks free space (totalBytes-usedBytes) before each write; below a floor it stops accepting new vectors and logs memory: vectors flash full (free=..KB need=..KB) - persist paused. memory::flashFull() and /api/mem/stats report the paused state.

5a. When the card stops answering mid-run​

A card that was mounted at boot can stop answering later: a pull or a cold joint, and, until v4.6.0, internal memory running short (the storm suite's low-memory leg, 22 and 23 Oct 2026). The device keeps working and loses nothing:

  • Card transfers never allocate. FATFS keeps its buffers in PSRAM on this build and the S3 SDMMC host can only DMA internal memory, so the IDF driver used to allocate a 512 B internal DMA buffer for every card transfer and failed with not enough mem when internal memory was short. One sector-sized DMA buffer is now reserved at boot, before the card mounts, and every such transfer goes through it (src/sys/sd_dma_bounce.cpp, link-time wrappers around sdmmc_read_sectors/sdmmc_write_sectors).
  • Demote and promote. Two failed card writes or probes demote the tier (no restart); the probe tries the card every 4 s while it is lost and two answers promote it back.
  • Held writes. History rows the card refused stay queryable in the RAM ring and are held, oldest first; after the promote they are written in arrival order, a few with each new row and the rest in bounded steps on the Telegram task between turns. Vectors whose persist failed are written again once per recovery. Two things still lose held rows: a restart before the card answers, and an outage long enough to hold more than 512 rows (the oldest go first, counted in the log line that reports the flush).
  • Remount. A card still lost once internal memory has recovered (4 KB DMA block, 16 KB internal free) is remounted, at most once a minute, on the Telegram task, never on the main loop. A remount under low memory is never tried: it can leave the card unmounted.
  • The owner hears once. An outage that outlasts 20 s sends one notice (Telegram owner chat and the web chat); a card that keeps dropping is told about at most once every 6 h. The device screen and the web page show the live state the whole time.

Bench legs: tests/hil/test_l70_sd_low_memory.py holds internal memory down with the console ballast and loads the network, then checks that the card neither runs out of memory nor demotes; a second leg fails every card write (FAULT sd_io) and checks one owner notice, a remount, the promote, and the held rows on the card after a restart.

5b. Implementation status​

In place (host-tested; confirmed on device via /api/log and /api/mem/stats):

  • PSRAM working set (§2): psram_alloc seam + device hook install; on-device [psram] VDB working set -> PSRAM, internal heap 148 KB free (was ~45 KB).
  • SD-primary paths (/mem/*) + LittleFS /data degraded fallback + SD-first/LittleFS migration read; atomic .tmp→rename writes.
  • Degraded cap (400) + LittleFS overflow guard; dirty-flag persist (mutating tools only).
  • Tier status: memory::haveSd()/flashFull(), /api/mem/stats fields + dashboard degraded banner, STATUS sd=/psram=/minheap=/vec=, live /api/sdprobe re-mount.
  • Blob content-addressing utility (§4); a width-invariant bug was found, fixed, and regression-tested.

In place, verified with a mounted card:

  • Episodic append-log day-streams + offset index (§3): AppendLogEpisodicStore (lib/core/.../episodic_log.h + orch_episodic_log.cpp) behind the EpisodicStore interface - JSONL day-streams (/mem/episodic/YYYY-MM-DD.jsonl), an in-RAM offset index rebuilt at boot from the streams (one system-of-record; no separate index.bin to desync under power loss), a PSRAM recent-window fast path, and uncapped history (the 500-ring cap is lifted on SD). O(1) appends, index-first queries that never open an out-of-window day file, tolerant torn-line decode. Host-tested (test_orch_episodic_log, 12 cases: O(1)-append proof via a write-counting fake FS, ring+index query parity vs the in-memory store, out-of-window skip, zero-read fast path, >500 history, hydrate/migration, torn-line tolerance, id-counter resume, retention prune, civil-date).
  • 30-day retention prune (§4): AppendLogEpisodicStore::prune drops old day-streams by name and, on a complete index, reference-count-scans away unreferenced blob sidecars; wired to memory::pruneRetention() behind the turn gate.
  • Durable media sidecars, WIRED + ON-DEVICE VERIFIED (§4): memory::captureMediaFile STREAMS a LittleFS file → content-addressed /mem/blobs/<hash>.<ext> in a 512 B buffer (a streaming BlobHasher, so the ~480 KB mic PCM never loads whole into RAM), dedup + .part→rename atomic, then an episodic Audio row referencing it. Wired at three capture sites: the inbound Telegram voice note (/audio/tgvoice.ogg, persisted before the LittleFS privacy-delete), an inbound Telegram photo or document, and the on-device mic turn (/voice.pcm). An inbound Telegram item's row is stamped with the time it was sent, not when it arrived, and tagged sent:<epoch>, so a late or redelivered photo never reads as new. An owner, routine or reply row also carries at:<epoch>, the second the device stored it (once its clock is set), which the conversation history uses to tell the owner's local day. A spoken reply is recorded as a text row, not a media sidecar. With no card this is a no-op. The resulting row appears in /api/mem/episodic as {"kind":"audio","blob":"/mem/blobs/<hash>.<ext>"}. Privacy note: raw inbound voice-note audio is retained on the card by design; erase the card to purge it.
  • Retention tick: main.cpp loop calls pruneRetention(30) every ~6 h through a RetentionSchedule (no-op without an SD append-log or before the clock advances past the window; a pass deferred by a turn runs when the turn ends), and episodicBackfillTick() on every pass.
  • Device seam: ArduinoEpiFs (fs::FS backing for the portable EpiFs); memory_subsystem::begin() routes episodic through the append-log when g_haveSd, with one-time whole-blob→day-stream migration; the card-less path is byte-identical to before (append-log constructed only on SD). esp32s3 + test builds link.

On-device verification (2026-07-04, firmware [env:test] flashed, card mounted):

  • Boot with the new firmware: [sd] mounted: 14911 MB, store=SD /mem, cap=2000.
  • Migration proven: boot log memory: migrated 37 episodic rows -> SD append-log (the legacy whole-blob's 37 rows replayed into the SD day-streams).
  • Query proven: GET /api/mem/episodic returns all 37 rows, newest-first, content- identical - the append-log serves reads via readRange over the real card.
  • Persistence across a restart proven (F10 crux): after a REBOOT, the second boot shows [sd] mounted + memory: ready with NO "migrated" line and episodicMsgs=37
    • hydrate() read the day-streams back (hydrate()>0 → migration skipped, no double- migrate), and a post-restart query still returns all 37 rows. Durability confirmed.

The sub-agent journal​

The journal (/data/agjournal.json, lib/core/src/orch_journal.cpp) holds what a restart must not lose about helpers (sub-agents):

  • Running helpers, at most 6: the id the device polls (backend:remoteId), the chat, the project and the model. After a restart the device polls each one again instead of starting it twice. A helper on a synchronous provider (Mistral, Z.ai, Cumulo, a custom endpoint) ran inside the device, so its result lived in memory: after a restart its owner hears "the result of [name] was lost when the device restarted", not "expired".
  • The last 8 finished helpers: tag, name, project, the file the result was saved to, and when it finished. A finished entry is stored before the running record is marked delivered, so a restart between the two never delivers a result twice. After a restart these are listed in the assistant's turn context ("Finished before the device last restarted"), so it does not run the same work again on the strength of its own note that it was waiting for results.
  • A new boot's job tags start after every tag the journal still holds.

The file is rewritten whole and atomically on each change. A write that does not land (flash full, or not mounted) keeps the helper running from memory; the owner hears "On it, but storage is full, so this helper will not survive a restart." in place of the plain acknowledgement (at most once every ten minutes), and the assistant's job list says the same. Until v4.5.16 the running records lived in the agjournal NVS namespace, where a full settings store refused them silently; the first boot of v4.6 reads them once, writes the file, and erases the NVS records on a boot whose image was already valid. If an earlier release ran after the file was created (a rollback, then an update back), a running record it left in NVS is added to the file, never dropped: that job may still be running and billing. The file remembers which NVS records it already took, so the stale NVS copy of a job that has since finished never brings it back. The hosted instance keeps the same file under its volume (<mem>/journal/agjournal.json).

5c. SD quota and supported-card truth​

The artifact store must not be able to fill the card the bulk tiers also live on, so it carries a quota, recomputed from the REAL card size at every mount:

  • Quota = card capacity - a 512 MB reserve (FileStore::quotaForCard, pure + host-tested). The reserve is headroom the firmware, logs, media, and sound packs need. A 16 GB card gets a ~15.5 GB store quota; a 1 GB card gets 512 MB.
  • Cards below 1 GB are UNSUPPORTED (FileStore::sdCardSupported): once the reserve is taken there is too little left to be a useful store, so the card mounts with a zero quota and an explicit unsupported state, and saves refuse legibly rather than the store silently offering a tiny space.
  • A flaky mount that reports cardSizeMB()==0 keeps the safe 512 MB default quota (never a zero quota from a transient read).

The payload carries four distinct truths so a client never reconciles two payloads to tell the store quota from the raw card free space. GET /api/files/list:

present card: {present:true, unsupported:false, count, bytes(=used),
quota(=card-512MB), cardTotal, cardFree, freeBytes(=quota-used), files:[...]}
absent card: {present:false, files:[]}
tiny card: {present:false, unsupported:true, files:[]}

/api/state.files mirrors present/unsupported/count/bytes/quota/cardFree, and the files.list tool returns count/bytes/quota/cardFree/freeBytes for the model.

5d. A full file store​

The store has no entry-count cap: the index scales with the card (owner ruling R6, no SD file cap), and an upgrade keeps every existing row whatever the old limit said. The only space limit is the byte quota from §5c, so a save refuses only when the card-scaled quota is genuinely reached (FileStore::fullRefusal tells that apart from a refused request such as a bad name or one file over its size limit, and from a card below the supported size). Listings and searches stay bounded per call however large the index grows: GET /api/files/list and the files.list tool page with limit/offset (default page 1000, ceiling 2000; the payload's count is the whole-store total, shown the page, and listCount/nextOffset/more page the store rows themselves - the Files panel's "Show more" fetches nextOffset while more is true, and the read-only Telegram archive rows appended to the payload never inflate those counters), and files.search scans at most the newest 512 readable text documents per call and says when older ones were not scanned.

When the byte quota is the blocker, the save path first reclaims the oldest regenerable copies - chat-attachment copies only (the Telegram archive keeps the original, and Telegram can re-serve it by file id) - oldest first, until the new file fits. Anything outside the chat-attachment folders is someone's own file - the owner's uploads and reports, another principal's artifact - and is never an eviction candidate, even when a newer entry in the store holds the same content. A reclaim that cannot cover the need evicts nothing: the save refuses rather than losing copies for nothing. When a save lands only because copies were reclaimed, the owner hears it once per episode, in plain words, as a second device notice alongside the full-store one.

A full store is told to the owner once per episode, never per item:

  • The episode starts with the first save the owner did not watch fail: an inbound Telegram photo or file, an assistant save (artifact.save, files.append, files.pdf, image.generate, a helper's saved report, a file captured from a provider's sandbox) or an approved URL download (files.fetch). A web upload is not one: the page shows its own refusal.
  • One device notice goes to the owner's chat (the web chat on a device with no Telegram owner), before that photo's reply: "the file store is full, so new photos and files are not saved to it. To make room, open the device web page, delete files you don't need in the Memory tab's Files section, then send them again."
  • The head reads it as a fact. Each photo or file the full store refused carries a bracketed line in its turn (not saved, the owner already has the message, do not explain it or ask which files to delete); a refused assistant save carries the same in its tool result. The photo itself still lands in the chat's history (its blob and media row are separate from the store), so the head says it in a few words and answers the photo.
  • The episode ends when files are removed and the store has room again. A save that lands in between does not end it. The state is RAM only (no settings key), so a restart mid-episode tells the owner once more.

The rule keys on the store's own full refusal, never on a count, so it holds when the quota changes. (The old 256-entry cap is gone: FileStore::maxEntries defaults to uncapped, and load() keeps every valid row, so a device at the old cap upgrades in place and loses nothing.)

6. Implementation phases (value × testability)​

Phase A - host-testable now, no hardware. Append-log episodic store behind the EpisodicStore interface (in-memory FS shim for tests; query parity with the in-memory store); degraded VDB cap + LittleFS overflow guard; blob content-address

  • reference-count prune; dirty-flag/debounced persist. All at 100% on native.

Phase B - device seams, no card required. PSRAM routing for g_vec + episodic recent window (boot PSRAM assert; STATUS reports the PSRAM size as psram=<bytes>); sd=absent status field + degraded banner + live SD re-probe. Verifiable on a board with no card via STATUS/RENDER?.

Phase C - SD-dependent (gated on the card being detected). /mem/* paths wired through setDataFs; LittleFS→SD migration converter; durable media sidecars; retention/archival maintenance.

7. E2E test plan​

Host (pio test -e native, kept at 100%) - all portable logic:

  • VDB: serialize↔deserialize bit-exact; truncated-blob tolerance; lowest-score eviction (permanent/creator exempt); top-k + threshold recall + access-boost; degraded cap when no SD; flash-overflow refusal.
  • Episodic: append-log makes O(1) appends (write-counting fake FS, no whole-file rewrite); query parity with the in-memory store; index skips out-of-window days; recent-window fast path (zero FS reads); uncapped history (>500 queryable); id counter resumes past loaded history.
  • Blobs: content-address dedup; reference-count prune.
  • Migration: LittleFS blob → day-streams (+.migrated, no double-migrate); vectors SD-first/LittleFS-fallback.
  • Tiering/config: scratchpad file round-trip (moved out of NVS in v4.5.14); mem-config clamps.

On-device HIL (tests/hil, --allow-hardware, gated markers) - device behavior; SD rows stay skipped until cardType != 0:

  • Without a card (Phase B): PSRAM backs the VDB (heapMin stays off the OOM floor as vectors grow); no-SD degraded banner + sd=absent + clamped cap; LittleFS-overflow pause; persist-across-restart in degraded mode.
  • Gated on the card (Phase C): SD mount + /mem/* created; migration on first mount; episodic full history on SD (cap lifted); durable media sidecar (voice note persists + episodic Audio row references it); recall into the live turn (must run off the main loop, not the watchdog-killed console TURN); persist-across-restart from SD; SD hot-plug upgrade.

Collection stays clean with no device; state-mutating rows restore in finally; manual media/hotplug rows fail LOUD if unconfirmed. A HIL row counts only when green on hardware.