Skip to main content

Sourced from docs/memory.md in the firmware repo.

Memory: RAM Pools, Turn Budget, and Compaction

How Nimbus fits a memory-hungry agent into a microcontroller. Read this before changing a heap floor, a buffer size or a context budget. It covers the two RAM pools and which one is scarce, what a live turn costs in internal SRAM and how that stays bounded, and how long conversations fold into a compact summary instead of growing without limit. It reads from the hardware up to the conversation.

Related: orchestrator-storage.md (what lives on SD, PSRAM, NVS, and flash), turn-anatomy.md (what the model sees), provider-wire.md (the wire mechanics per provider).

The memory tiers at a glance - information flows left to right from the shortest-lived tier to the most durable, and each tier is backed by the storage that fits its lifetime (details: §1–§3 below and orchestrator-storage.md):

1. The two pools (read this before touching heap floors)​

The Solide S3 board is an ESP32-S3-DevKitC-1 N16R8. It has two very different memory pools, and conflating them has repeatedly caused work to be throttled or deferred while most of the device's RAM sat idle. Know which pool you mean.

PoolSizeSpeedDMAWhat reports itCharacter
Internal SRAM~266 KB heap (of 512 KB total; the rest is static/ROM)FastYesESP.getFreeHeap(), heap_caps_*(…, MALLOC_CAP_INTERNAL)Scarce: the real constraint
PSRAM (external, octal)8 MB~2–4× slowerLimitedESP.getFreePsram(), heap_caps_*(…, MALLOC_CAP_SPIRAM)Abundant: normally ~98% free

ESP.getFreeHeap() measures internal SRAM only. A reading of 16 KB free means the scarce pool is low, not that the device is out of memory: PSRAM typically has ~8 MB free at the same moment.

What MUST live in internal SRAM (do not try to move these)​

  • FreeRTOS task stacks - every xTaskCreate* stack is internal by default. A task that touches flash (NVS / LittleFS / esp_partition reads) or runs in an ISR cannot use a PSRAM stack. TLS itself does not force an internal stack: the prebuilt Arduino core already enables ext-mem stacks (CONFIG_FREERTOS_TASK_CREATE_ALLOW_EXT_MEM) and the mbedTLS record buffers already live in PSRAM, so tg_poll's stack is internal because it reads NVS/config, not because it runs the handshake. The gate is flash access, not TLS.
  • The orchestrator's boot work - setup() runs the whole orchestratorBegin() chain (the persisted-store loads, the skills/tool registrations, the engine wiring) on a one-shot 12 KB orchboot task and joins it before anything else proceeds. It is the deepest call chain of the boot, and the Arduino loopTask's 8 KB stack had ~88 B of headroom left after it on the last release - the next lane's ~100 B of registration depth tipped the canary (the release-v451x boot crash). Nothing runs in parallel: the task is joined before loop() starts, the same one-shot shape provider_verify uses. The task reports its own stack watermark before it ends, and the boot ladder checks both stacks against a 1 KB floor (boot stack: loopTask min free ... floor 1024 B - ok and boot stack: orchboot min free ... of 12288 B, floor 1024 B - ok, or a BOOT FAULT line that also sets mem.bootStackFault), so stack erosion fails a bench leg loudly instead of a release-gate boot. The chain never runs inline on loopTask (that was the 88 B crash path): when the task cannot start (it needs its stack plus room for the Telegram task the chain creates next), setup() retries for up to 30 s, logs orchboot: BOOT FAULT ..., and falls back. An update still on trial rolls back to the previous image at once. Otherwise the device restarts, counted in RTC memory; after two restarts in a row, or on a boot that followed a crash (a restart would hide the crash notice), it boots on without the assistant: Wi-Fi, updates, the web page and the screen keep running, the screen says "The assistant could not start", the web chat gets one row once the network is up, and /api/state reports mem.orchBootDegraded. Never a restart loop, never a wait in place.
  • DMA buffers - Wi-Fi, I²S, SPI (display/SD), LED RMT. These request MALLOC_CAP_DMA explicitly and bypass the PSRAM spill entirely.
  • lwIP pbufs + the TLS record working set - the ~24 KB "danger zone." A network call needs this much contiguous-ish internal to not fail; it is the real internal red line.

What IS routed to PSRAM already (don't duplicate)​

Installed in main.cpp at boot:

  • mbedTLS allocator → PSRAM (mbedtls_platform_set_calloc_free): the big RX/TX content buffers (~16 KB each) + session/cert parse land in PSRAM. The ~40 K contiguous handshake that used to fail at ~50 K internal now lands in PSRAM.
  • General malloc/new/String/JSON churn ≥ the spill threshold → PSRAM (heap_caps_malloc_extmem_enable(N); currently N = 128 B). Allocations < N stay internal to keep hot paths fast; ≥ N go to PSRAM. Lowering N frees more internal at a small PSRAM-speed cost - this alone took internal free from 16 KB → ~48 KB and made Telegram turns run (they had been deferring at the 34 KB floor).
  • Every small block too, while a turn runs. The turn drops the spill threshold to 0 for its length and puts 128 B back after (PsramFirstScope in nimbus/harness/turn_memory.h, the switch in heapwatch::psramFirst). Before this, a turn's setup spent ~16 KB of internal SRAM in blocks of 128 B or less (the per-turn copies of the tool specs, the tool-name map, closures, prompt pieces), measured on unit A: the registry's tool specs 3.8 KB, the prompt's tool list 1.7 KB, the head loop's tool set 8 KB. A turn admitted at ~17 KB reached 772 B free and 20 B largest before its provider request, the Wi-Fi task's own 32 B internal allocation failed, and IDF aborted (a panic). With the switch the same turn's setup costs no internal SRAM. The threshold is device-wide, so for the turn's length every task's plain small malloc (the web server, the relay, audio and card code, and lwIP's and the Wi-Fi driver's own: PCBs, TX pbufs, TCP segments, pbuf headers, as with CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP) goes to PSRAM first too. IDF already does that once internal is empty, so this is a placement that code already meets under pressure, now met before internal runs out; explicit internal or DMA allocations (the Wi-Fi RX buffers, driver DMA, FreeRTOS stacks and objects) never move. The bench legs that run with it: the storm low-memory leg (a turn, the nightly upkeep and card writes under the ballast) and the starvation leg (card log reads in the turn).

Also PSRAM-backed by design: the vector-DB working set (setWorkingAllocators), ArduinoJson node pools (ps_json.h) - including the single-shot turn response docs - per-adapter request/response bodies (serialized into one contiguous PSRAM-spilled string and written once), the SFX manifest, the web audio test-tone buffers, minimp3's ~15 KB per-frame decode scratch (via mp3dec_decode_frame_ex; it used to sit on the audio task stack, forcing the sfx task to 20 KB and leaving the 8 KB music task one MP3 track short of an overflow), and the Telegram poll body plus the poll task's staging buffers (the inbound-drain slot and the shared API response scratch). The last two are safe in PSRAM because tg_poll is their single consumer and its TLS work is fully serialized, so a batch never needs two of either live at once - moving them off internal freed ~6.7 KB of the scarce pool with no behavior change.

Long-lived fixed buffers that would otherwise be file-scope statics in internal .bss are declared through nimbus::psramStatic<T>() (src/sys/psram_static.h): static T& g_x = nimbus::psramStatic<T>(); keeps every use site and sizeof unchanged, starts the object zeroed like a static, and leaves only a 4-byte reference in internal RAM. It applies only to task-context data: never a buffer an ISR, IRAM code or DMA touches, and never the spinlock itself (the lock stays internal, only the data it guards moves). This holds the web model-memory echo, the fold status echo, the system-turn prompt, the large OAuth handoff buffers and the Telegram pending slots (voice, attachment, media, unknown-chat approvals): about 6.3 KB that v4.5.14 had added back to static internal RAM. An object that needs its constructor moves the same way with nimbus::psramObject<T>(args...): it is built in place in PSRAM where the function-local static was, once, and never destroyed (a device never runs exit handlers), under the same rules plus no lock or atomic member. The job engine, the turn engine (about 3.1 KB together) and the model store's slots live there, and the provider park keeps its record table in PSRAM through setRecordMemory, so only its locks and hooks stay internal. tests/hil/test_psram_statics_host.py fails if one moves back inline, and the release gate's static DRAM check (tools/release_gate/check_static_dram.py) fails an image whose static internal RAM grows past its recorded ceiling.

Moving the MP3 scratch to PSRAM let the sfx task stack drop from 20 KB to 12 KB and made the 8 KB music task safe. Measured on the Solide S3 in Orchestrator mode with Wi-Fi up, that returned about 9 KB to the internal free pool: total intFree 59.2 KB to 68.3 KB and the heapMin floor 49.0 KB to 57.9 KB. The largest contiguous block (intLargest, 31.7 KB) did not move, because the freed stack region is not adjacent to it; the gain is in total free and heapMin, which is the "low internal SRAM" headroom. /api/state reports the audio task high-water marks as mem.sfxStackMin and mem.musicStackMin alongside pollStackMin / asyncStackMin.

A deliberate exception: the episodic deep-history read stays internal​

Not every transient belongs in PSRAM. The episodic deep-history search (memory.episodic cold-scan, GET /api/mem/episodic?cold=1) reaches history that sits on the SD card below the boot-scan index by walking the day-streams backward, one small window at a time, on the querying task - the AsyncTCP web task or the turn task, each of which runs on a tight internal stack. That read window is a heap allocation on that task, so its size is a crash boundary, not a performance knob: a large window (an early design used 128 KB) starves the task's contiguous internal SRAM and drops the device off the LAN mid-query. It is kept small (≈8 KB, escalating only when a single record is longer than the window). What bounds the work is the per-call read budget (a few files, ~128 KB total) - not a big buffer - so deep history pages: the store returns a resume cursor rather than allocating for the whole scan. This is the counter-lesson to "route churn to PSRAM" - a small bounded internal read on a stack-tight task is the correct shape. Full design: orchestrator-storage.md §3a.

The word match every text search runs (nimbus/orch/lexical.h) holds to the same shape: the parsed query is a fixed ~220-byte value on the querying task's stack, each row is scanned in place (no lowercased copy, nothing allocated per row), and a ranked page adds one score byte per kept row - at most 200 bytes of heap. test_orch_lexical counts heap allocations and fails if matching or a no-match store scan makes any.

The heap floors are internal-only guards, not a whole-device budget​

agent_config.h defines ORCH_TURN_HARD_FLOOR / ORCH_AUTO_TURN_MIN_HEAP / ORCH_DISPATCH_MIN_HEAP / ORCH_RECALL_MIN_HEAP / ORCH_LOOP_MIN_HEAP, plus provider_verify's VERIFY_MIN_MAX8 and the /api/tools async-stack guard. They all gate on internal heap. Because the heavy allocations they used to protect are now on PSRAM, a turn's true internal cost is small transients plus the lwIP/TLS working set, so admission has two parts:

  • A total-free backstop of 12 KB for a user turn, a dispatch, a loop round and recall (ORCH_TURN_HARD_FLOOR). Background synthesis is held 2 KB higher so it yields to a live turn.
  • A largest-block guard of 5 KB (ORCH_TURN_MIN_LARGEST_BLOCK): the contiguous internal block one mbedTLS handshake needs. This is the real gate. A fragmented but ample heap passes; an obviously starved one is refused.

A static_assert keeps the turn floor below the pre-PSRAM 28 KB danger zone and the background floor above the interactive one.

The turn re-checks before it asks a provider anything. Its setup keeps its small blocks in PSRAM (above), so it costs no internal SRAM (measured: 0 B on the starved bench recipe, ~16 KB before) and the floor the turn was admitted on still holds at its provider request. The setup samples internal SRAM at each phase (turn memory: admit=... recall=... tools=... dispatch=..., logged when the setup cost 1 KB or more) and checks that same floor again at the request (12 KB free and a 5 KB largest block for an owner turn or a routine, the background floor for a synthesis turn: the numbers its later rounds re-gate on). A dip under it, from the recall embed's network buffers (freed a few ms after its connection closes) or work beside the turn (a web page being served), is sampled again up to five times, 200 ms apart. Still under it, the turn ends with one reply, "I'm short of memory right now. Please try again in a minute.", recorded in the chat history, and no provider request; a routine's fire is deferred instead (no message; a one-shot reminder retries in two minutes). What the turn had already taken from its queues (sub-agent results, the last turn's memory results, spawn notes) is put back for the next turn, so a synthesis turn waits and synthesizes later rather than handing the owner a raw dump. A failed C++ allocation in a turn ends it the same way instead of aborting, and nothing it held stays taken: the TLS work slot, the card lock, the file store's upload slot and the mutexes on the turn's path are held by scope guards. Once the turn has asked a provider, a failed allocation is no longer a deferral: a round may already have billed and run tools (a Telegram reply sent, a memory written), so a routine's fire counts as a failure, never a memory deferral, and the rounds it billed are metered. A fire whose turn handed the model's words to the owner before it failed (its reply, a cut reply it salvaged, a Telegram message, file or voice note a tool sent, speech that played; for a routine's delivery to the web chat, whose history is the only copy, once that history row is written) is never run again early, so the owner never gets the same message twice: a one-shot reminder or wakeup retires instead of taking its one short retry, and the owner gets one message saying it was delivered but its turn did not finish; a routine keeps its next slot. A quiet turn's held text does not count, and neither does a delivery that failed before anything was queued. A fire whose turn was served counts as served even when an allocation fails in its bookkeeping afterwards, so a working routine is never paused for it.

Do not re-raise these floors to "survive with no PSRAM". PSRAM is present and carries the churn. If turns are deferring ("low on working memory") while PSRAM is free, move more internal churn to PSRAM (lower the spill threshold) rather than raising the floor. A turn that still runs out of memory fails soft: an honest low-memory reply ("the device ran out of working memory for this request; try a shorter question or wait a minute"), no restart. On every head running the tool loop (the default; the Cumulo router head and a direct OpenAI, Anthropic, Mistral or Z.ai head alike), a request the device could not finish sending is sent once more, on the same provider, after the heap recovers past the round floor (a bounded wait of up to 3 s); only if it does not recover does the turn end with that reply, without switching to another provider (the request would run short the same way there). A request that went out is never sent a second time this way. A turn that starts with too little heap for the tool loop runs single-shot instead, and a failed send there gets the turn's ordinary retry, then another provider.

Admission beside a turn​

The floors admit a turn on one sample at round start. Other consumers of internal SRAM run beside it, so they yield instead of re-raising the floors:

  • Worker tasks (provider verify, cloud key mint, voice catalog, safety report) start only with room for their stack plus 16 KB of internal free, and never while a turn is in flight (heapwatch::spawnGate). A verify refused for a turn starts when the turn ends; one refused for memory is recorded as deferred and retried, early once the resting largest block recovers. The verify's memory gate reads the resting largest block (the minimum of the last idle samples), taken before its stack exists: a sample inside a transient read 7,156 B on a device resting at 15,860 B.
  • Big web responses (over 16 KB: the web app page, file downloads, log files, stored blobs, episodic and vector pages) trickle, about two TCP segments in flight per connection, or answer 503 with Retry-After when internal free is under 20 KB. A download read from the SD card takes that decision when its file opens, inside the stream (see the card lock in storage), and keeps its staging buffer in PSRAM (internal memory only when PSRAM has no room). The cloud relay's own loopback request also gets the 503 while a turn is in flight (the cloud page retries it); a LAN browser trickles. Bodies up to 16 KB are served as before.
  • GET /api/state and GET /api/orch (several KB each, polled by the web app) go out whole or not at all (a body that did not build completely answers 503), through the response filler, which counts the bytes the network stack queued. The library's plain response queues the same bytes again when the stack is short of packet buffers (a photo look-up), so the page arrived with its start repeated past 5,608 B.
  • The state page's slow figures. Its internal flash figures (fsTotal, fsUsed: LittleFS walks the whole file area to count them, about half a second) are measured at most once a minute and only after 10 s without a turn (a turn's end writes flash), so back-to-back turns keep the last figures longer. The spend limits and the usage ledger are written to flash under their own locks; the page tries those locks for 20 ms and keeps its last answer while a write runs.
  • The cloud relay dials and writes responses over 8 KB through the TLS work slot (see the live turn).

A failure is memory-caused only on evidence: an allocation failed during the exchange (its error says alloc failed). Then the turn never switches to another provider and gets no retry (the LowMemory row of the provider failover table), except the one resend above for a request the device could not finish sending. Without evidence the rule above holds: a fragmented but healthy board's outage still fails over.

Levers to free internal SRAM (biggest first, verify on-device)​

  1. Route Wi-Fi/lwIP buffers to PSRAM (CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP, Wi-Fi static-buffer counts) - potentially the largest single win; needs an sdkconfig.defaults.
  2. Lower the malloc spill threshold (heap_caps_malloc_extmem_enable, main.cpp; already 0 for the length of a turn).
  3. Right-size / statically-place buffers (framebuffers, static arrays) into PSRAM.
  4. Re-anchor over-conservative internal floors (above, done).

How to measure (don't guess)​

ESP.getFreeHeap() = internal free; ESP.getFreePsram() = PSRAM free. /api/state reports both (heap/heapMin vs psramFree/psramTotal) and /api/health lists PSRAM as its own row. For an internal-vs-PSRAM-vs-DMA breakdown, read the mem object in /api/state (intFree, intLargest, dmaFree, spiFree, spiLargest), or call heap_caps_get_free_size() and heap_caps_get_largest_free_block() once per pool (MALLOC_CAP_INTERNAL, MALLOC_CAP_SPIRAM, MALLOC_CAP_DMA). The caps are ANDed, so ORing two pools returns 0.

Point samples miss the real low points (inside a TLS write, a handshake, another task's serve), so the device also keeps evidence of its own:

  • mem.lowWater, mem.lowWaterTags, mem.lowWaterUp: the lowest internal free since boot, what was running when it was set (turn, relay.dial, relay.bulk, tunnel, tg.dl, vision, stt, ota, dream, verify, worker, lan.big), and the uptime in seconds. Each new low at least 1 KB down, once under 24 KB, logs heap: new low-water <n> (was <n>) free= largest= tags= up=.
  • mem.allocFails and mem.allocFailLast: allocations that failed since boot (any task), and the newest one. Each logs heap: alloc FAILED size= caps= task= free= largest= up= count= (a few lines a minute; the count stays exact). The records live in RTC memory, so after a panic, watchdog or software reset the next boot logs heap: <n> alloc failure(s) before the last reset with the newest records.
  • mem.restingLargest: the largest internal block at rest (the verify gate's input).
  • Reading intFree, intLargest and largest= in the log: "internal" includes the RTC fast block (about 7.4 KB, intFree - dmaFree), and a largest=7156 is that block, not main SRAM. It can hold a task stack but no DMA buffer, so a Wi-Fi or speaker buffer can fail with several KB of "internal" free. For what those buffers can use, read dmaFree.
  • mem.tlsOverlaps: concurrent work-TLS seen (it stays 0 under the single slot).
  • mem.loopStackMin, mem.panelStackMin, mem.vrelStackMin: worst free stack of the main loop, the display render task and the voice-release watcher; mem.orchBootStackMin: the orchestrator boot task's worst free stack (it reports once, before it ends).
  • mem.bootStackFault: the boot ladder's stack-floor check faulted - the loopTask watermark after the orchestrator boot, or the boot task's own, dropped under 1 KB (boot stack: BOOT FAULT in the log). False on a healthy boot.
  • Every provider exchange logs one transport: heaptrace line on every path, with the heap at four phases and fail= (where it stopped: connect, head, body@<bytes sent>, read, headers, parse, none), af= (failed allocations during it), min= (its local minimum free) and at=/ms= (when it held the TLS slot). The body goes out in 4,096 B slices, so a failed write says how many bytes left.

2. Heap under a live turn - what's movable, what isn't​

A live orchestrator turn runs with only ~47 K free internal SRAM (TLS + lwIP + the orchestrator all resident). PSRAM is nearly empty but is not in the default malloc pool by default. What is already in PSRAM is listed above; this section records what is stuck internal, and why (measured while chasing the heavy-connector-write restart, 2026-07).

What is STILL internal (and why)​

  • Wi-Fi RX buffers - inbound TLS/socket data arrives in Wi-Fi RX buffers allocated MALLOC_CAP_INTERNAL/DMA by design; the extmem hook cannot move them (the pbuf header lwIP wraps around each one is a plain malloc). This was the dominant internal spike when the device buffered a whole large response. Mitigation: streaming. The transport stream-parses the response off the socket (transport_tls.cpp execJson → deserializeJson(doc, BlockingClientReader, Filter)), so pbufs drain continuously as the parser pulls bytes instead of piling up while a whole body is buffered. This is the real fix for the heavy-connector-write restart.
  • Small (< 128 B) allocations outside a turn - stay internal by the extmem threshold; cheap and not worth lowering it for the whole device. During a turn they go to PSRAM (above), because a turn's setup made thousands of them. The same goes for a provider verify or a model-list refresh on its worker: one string per row of the Cumulo router's list, three times over, is most of what took internal free to 968 B on a live device. 5.0.0 moves those blocks to PSRAM; the new low on a board is still to be measured. Anything that keeps a string per row of a list gives it a block over 128 B (assignOffInternal, keptId); test/test_refresh_small_blocks counts them.
  • The speaker's DMA buffers - opening the speaker takes DMA-capable SRAM until the clip ends: 8 x 1024 B on a raw I2S board (Solide S3), 16 x 1024 B on the ES8311 codec boards (Freenove), whose one channel carries both directions. A cue opens only with those and a reserve for the radio free (8 KB raw, 3.2 KB codec), and a failed open holds the cues back (one minute, doubling to 16). A spoken reply or a track keeps a smaller reserve (3.2 KB raw, 1.6 KB codec) and says when it cannot play. One sound holds the speaker at a time, and the memory is read on its turn (nimbus/speaker_memory.h).
  • FreeRTOS task stacks - e.g. tg_poll (24 KB, POLL_STACK_BYTES), which runs the whole turn. Internal by nature. The release gate tools/release_gate/check_tg_poll_stack.py measures its worst case from the built image (every frame and call chain, the 64 levels of a NestingLimit(64) response parse included, at 112 B a level) and fails an image that leaves under 4 KB free. So nothing large lives on it: the 4 KB Telegram queue items, the turn's large locals and settings reads go through PSRAM.

The size-transparency contract​

The harness must handle any response / context / file size without crashing:

  1. Responses stream off the socket; only filter-retained fields are stored (a 128 KB wire body → < 4 KB retained doc - test_harness_streaming). What the filter keeps is capped at 512 KB (its serialized size, kMaxRetainedBytes): past it the answer is dropped and named "response too large for the device" (Cut in the provider failover table). A parse that ran out of memory while a failed allocation was recorded is low memory instead: no retry and no switch.
  2. Tool results into the model are clamped (derived from the head model's context window: 8 KB per result and 64 KB total at a 200K window, see "Derived context budgets" below), so context stays bounded.
  3. Heavy connector work is offloaded to a sub-agent on the connector's provider (the orchestrator is guided to; routing in jobs.cpp), so the device only ever ingests a short result.
  4. Large payloads spill to SD (the artifact store) rather than transiting RAM or the model's context.

Do NOT​

  • Do not raise the turn heap floors to "fix" out-of-memory errors. The fix is streaming plus PSRAM routing, not gating turns out (the historical 34 KB floor deferred healthy turns; the live backstop is 12 KB with a 5 KB largest-block guard).
  • Do not buffer a whole provider response then parse - stream it.
  • Do not put connector write content through the model's context - offload/spill.

3. Conversation compaction - the fold​

How the device keeps long conversations fast, cheap, and continuous: when a chat accumulates enough history, the device summarizes it into a compact per-chat memory (the fold), resets the provider-side thread, and keeps going - nothing the owner said is lost, and every future turn carries the summary instead of an ever-growing transcript.

Owner's view​

The owner's page is compaction.md (when it runs, Summarize Now, the Memory page's Conversation summary card, what happens when a provider has trouble); the fold's ladder, schedule and driver are in architecture/fold-ladder.md. In short:

  • When it happens: automatically, once a chat has grown enough since its last fold (knob: compactKB, 8–512; 48, the default, follows the model in use; 0 turns auto-fold off), after 200 distinct messages, or once the recent history has outgrown its budget - and only when there is something new to summarize. The same message arriving again and again counts once, so a flood of one line never costs a summary. Or on demand with /compact (owner-only, also listed in /help) or Summarize Now on the Memory page (POST /api/fold/run).
  • What you see: automatic compaction is silent - its record is the "Conversation compacted: … folded into a … summary" row in the chat history. An automatic fold waits until the chat has been quiet for two minutes (at most 6 turns or 10 minutes; in a chat with no pause at all, 12 turns or 20 minutes), and each fold request after the first waits for quiet again, so an owner message waits at most one request. A manual request acknowledges immediately and then confirms once with "✓ Compacted. Summary updated: covered N messages from D1 to D2" (or says it couldn't, with the time of the next try). In the web chat the confirmation is a history row, never the reply slot.
  • If a provider is down: the fold walks the providers of your priority list (then the head's Sub model; Cumulo only when it is listed or the only provider), one request per pump pass, before a cycle counts as failed (fold-ladder.md). A provider left out of the list never receives the conversation.
  • If older rows cannot be read yet (after a restart, while the card is indexed, a card outage): the fold waits and looks again, and never moves the summary's anchor past a row it has not summarized; those rows stay named in each request as not included. Rows that stay unreadable for a day are reported to you once a day.
  • If it keeps failing: it never pauses. A failed cycle tries again after 15 minutes, 1 hour, 4 hours, then every 12 hours, each time on a smaller slice; a new firmware restarts the wait; a pause an older version left lifts on the first start. The owner hears about it at most once a day, and only after a day of failing. At most 12 paid automatic fold requests run a day on the whole device.

How it works (the design, in one page)​

The device cannot edit provider-side conversation threads (they're opaque ids - and only OpenAI even has a cross-turn thread; Anthropic is stateless and Mistral's tool-loop mode starts fresh every turn). So compaction is built on the device's own episodic store, provider-uniformly:

  • Trigger (FoldStore::evaluateDue): bytes-since-fold ≥ compactKB OR ≥200 distinct owner messages (noteOwnerMessage: the same text right after itself counts nothing) OR rows the history's overflow shift hid that no summary covers yet - provider-independent by design. A reactive path also classifies real provider context-overflow errors (isContextOverflowError) and queues a fold; the turn itself recovers via the existing fresh-thread retry.
  • The anchor and the slice (turn-structured history): the summary records the newest row it covers (thru), and the history starts after it. A fold digests only the turns after the previous anchor that lie beyond the kept verbatim tail (half the history budget) and the owner's current local day (kept verbatim, up to 16 KB), repeats collapsed to one line with a count; when that slice is under 1 KB there is nothing worth a paid call and the fold is skipped. A manual /compact digests every turn. The anchor and the overflow shift ride the fold blob as suffixes of its numeric fields, which an older image's parser stops before.
  • The fold call (TurnEngine::runFoldRung, one rung of the ladder that FoldDriver paces; runFold walks the whole ladder in one call for tools and tests) is deliberately NOT a turn: no delivery, no recall, no tool loop, no conversation-map writes, no capture of the summary as chat history - the model's reply IS the summary and every other field of its output is structurally inert. It has its own output budget: on Anthropic the request offers no tool (the summary comes back as text), thinks at low effort, and a summary cut at the limit gets one retry with more room. The digest is bounded so summary plus digest stay one whole provider string (ArduinoJson stores a 64 KB string as null). Its spend is metered under the compact attribution (never a routine's budget). Gates (low heap, over budget, turn in flight) defer - only a cycle whose every rung failed counts, and it schedules the next try (fold-ladder.md), never a pause.
  • Dated, from the conversation only: the fold input is the previous summary and the conversation since, nothing else (no data block of one use case closes it, owner ruling 41). The prompt has every date written as YYYY-MM-DD from the conversation's day markers (never today or yesterday) and every total name its day, and drops rules that belonged to a passing situation (how to answer repeated messages, an outage, a workaround) once the conversation no longer shows it.
  • Anchored, not cumulative: each fold UPDATES the previous summary with the new slice (opencode's pattern), so fold cost stays bounded forever. The summary re-enters every prompt as ## CONVERSATION SUMMARY - explicitly framed as information, not instructions, and instructions found inside tool outputs are folded as data, never preserved as directives (prompt- injection posture).
  • Summary + verbatim tail: the summary sits directly above the RECENT CONVERSATION window, the shape every surveyed harness (Claude Code, codex, opencode, aider) converged on. Under prompt-budget pressure the summary is sacrificed BEFORE the window (the tail is the fresher signal).
  • Durability & rollback: all per-chat fold state (summary, counters, the anchor, the schedule) lives in one tolerant-load LittleFS blob (/data/chatsum.txt, LRU-16 chats inside 64 KB, about ten with a full summary; an evicted chat loses its summary). The device-wide state (the daily cap, the alert day, queued manual requests) is /data/fold_ctl.txt, so an eviction never resets it. The NVS conversation map is untouched, so an OTA rollback to pre-v3.6 firmware simply ignores the file. A rollback to v5.1.1 reads the blob (summary, anchor and shift intact, nothing paused), re-caps a summary over 4,096 B, and writes the blob back at 48 KB, which can drop the oldest chats' records. v5.1.1's fold reads only the newest 400 rows after the anchor, so a long window of short messages kept by v5.1.2 can leave rows in neither summary nor history after a rollback: run Summarize Now in each long chat first (one press summarizes up to the newest message). Crash mid-fold: the write order (summary first, thread reset second) means the worst case is a fold that re-runs, never a lost summary with a reset thread.

Verification​

Host: test_model_window (the per-model window table), test_orch_compact (trigger math, backoff, thrash wait, legacy lift, codec and rollback round trip, UTF-8-safe proportional caps, fold-prompt contract, the anchor and shift round trip, a repeat counted once), test_fold_backlog (a replay of a long chat's first anchored fold: a backlog folds again without an alert, a real refill only waits), test_fold_ladder and test_fold_driver (fold-ladder.md), test_owner_first (an automatic fold never starts between the messages of a conversation), test_harness_chatwindow (the fold slice: 500 identical messages never fold, 200 distinct 30-byte lines do), test_harness_history (the slice starts after the anchor), test_harness_turn (runFold's no-side-effects contract incl. a hostile summary carrying device actions - inert), test_harness_compose (§5a placement + budget-pressure drop).

Hardware: tests/hil/test_l16_compaction.py - the full cycle with a marker planted OLDER than the verbatim window, proving recall comes from the summary (/api/lastturn shows it) - and tests/hil/test_l15_memory_caps.py - vector-store cap eviction (synthetic-only damage), episodic retention past the PSRAM ring, and a fold completing from the RAM ring under a simulated SD failure. Measured along the way: 512 episodic-ring rows with short texts pin ~30 K of internal SRAM (small strings don't spill to PSRAM), which is why the ring deliberately stays at 512.

Reference​

thingwhere
knobcompactKB (NVS; default 48 = follows the model, clamp 8–512, 0 = auto off)
command/compact (owner-only; async - runs on the next pump pass)
APIGET /api/fold/status, POST /api/fold/run (src/net/fold_routes.cpp; compaction.md)
boundary recordepisodic row, kind=log, tag ev:compact, in the chat's session
prompt section## CONVERSATION SUMMARY (above the recent window)
state filesLittleFS /data/chatsum.txt (rollback-safe; LRU-16 chats inside 64 KB, written atomically, its write time logged) and /data/fold_ctl.txt (device-wide)
fold prompt + schedulelib/core/{include/nimbus/orch/compact.h, src/orch_compact.cpp}
driver + ladderlib/harness/src/fold_driver.cpp, lib/harness/src/engine_fold.cpp (fold-ladder.md)
window table + trigger mathlib/core/{include/nimbus/orch/model_window.h, src/orch_model_window.cpp}
engine callTurnEngine::runFold (lib/harness/src/engine_fold.cpp) / clearChatConv
device pumpcompactTick() in src/agent/orchestrator.cpp
test seams (TEST builds)CTX? / COMPACT <chat> / FOLDRESET / MEMFILL console + /api/test/{ctx,compact,memfill,epiprune} (memfill kind=epiday writes dated rows with sidecars)

Assert on the ev:compact row, not on CTX?. The diagnostic reads a cross-task echo buffer that is republished on every fold outcome, success or failure. The durable ev:compact episodic row is the right thing to assert on: it is written only on success, it carries the byte and message counts, and it survives a restart.

Derived context budgets​

Every context allocation is derived from the head model's context window rather than hardcoded: nimbus::orch::deriveBudget(ctxTokens, overrides) (lib/core/src/orch_budget.cpp) turns the window into a system-prompt budget, summary cap, verbatim-tail cap, per-tool-result clamp, cumulative tool budget, sub-agent brief size and fold-slice size - each a ratio with a floor and a cap. Every reader of those sizes (the turn, the history window, the fold slice, the results.get view cap, the web console's auto values, the hosted daemon's fold) asks one seam, nimbus::orch::headContextBudget(host, model, loopOn, overrides), which derives over the head's window; test_orch_budget fails on a size derived around it. With the tool loop off a Mistral or Z.ai head sends one prompt string, so the seam sizes it from that string's budget: v5.1.1's history window and summary trigger. The window comes from the modelCtxTokens() table (model_window.h). A Cumulo router pick is stored as <upstream>/<model> (the model picker saves openai/gpt-5.6 for the default); the table splits it with the same router rule the head uses and reads the upstream model's window, so a prefixed pick gets the same budget as the bare id.

Anchor invariant: at a 200K window the derived values are 32768 / 4096 / 8192 / 8192 / 65536 / 1200 / 65536 (system prompt / summary / recent tail / per-tool-result / tool total / brief / fold slice). Each equals the previously hardcoded constant except the recent tail, raised from 3000 to 8192 so the previous reply reaches the next turn whole (3000 is now its floor). A smaller-window model degrades gracefully; a larger one automatically gets a richer prompt.

Owner overrides win. max_context_bytes (memory config) and the two loop-cap NVS keys now treat 0 / absent as "auto"; any value you set is used verbatim under the same clamps as before. /api/orch reports loopRescapEff, loopTotcapEff and ctxTokens so the UI can show "auto (currently N)". Each turn logs one line: budget: <host>/<model> window <W>K target <T>K tok (<B> KB) hist <max>/<soft>/<keep> KB (auto|owner): the head's window, its request budget (the body's, also on a turn that goes out as one prompt string), and the history marks (v5.1.1 and earlier logged budget: ctx=200K sys=32768 res=8192 tot=65536).

Gradient trimming - never a dumb clip​

The research principle (summary + verbatim tail) also applies inside a turn and at every clip site:

  • In-turn replay (every loop provider): the replay counts every replayed byte (call arguments, prose and results) and is append-only while the request fits: a round already sent keeps its bytes, so each round reads the previous round's request from the provider cache. Since v5.2.0 (lane RB-BGb, ruling 93 item 3) the only bound is the request's own body budget: a turn carries as much of its tool traffic as the body has free after the prompt, the history and the summary, never less than v5.1.2's replay figure for the head. When a round does not fit, the turn's own bulk goes first and only as much as the request needs: call arguments that already ran, then the oldest whole rounds (each call with its result, never the newest round) folded into one line each in the seeded message under [EARLIER TOOL ROUNDS OF THIS TURN ...], each line ending with the results.get tag that reads the result back, then the newest round's result cut to a part that ends [cut to fit this request: bytes 0-k of n; next part: results.get {"tag":...,"offset":k}]. Only then does the prompt's context go (recalled memories, skills, older days, and today's turns last). Every tool_use on the wire keeps its tool_result. See the cacheable prefix in turn-anatomy.md.
  • Tool results: a clamped result keeps its full text in the recent-results ring and the marker says how to get it - …[truncated 8192 of 51234 B - fetch the rest with results.get("r3")].
  • Sub-agent results: past the 6-slot block cap, a result parks as a one-line stub with a results.get("sub:<tag>") pointer instead of being dropped; the episodic row on SD keeps the full text.
  • Context assembly: the anchored summary clips (floor 1024 B) before it is dropped, and anything omitted is named in a bounded ## OMITTED (budget) trailer so the model knows a category was withheld rather than empty.

4. The Telegram archive (SD card)​

Everything exchanged with the device over Telegram is kept on the SD card, at full fidelity, separate from the conversation memory above. The conversation keeps its own smaller copy of a photo (Telegram's 800 px size, the one the model reads); the archive is the record and fetches the largest size itself, after the turn. A voice note or a document is downloaded once: the archive takes it from the conversation's download, and an update served again reuses the archived file.

What is saved, and when.

  • Inbound. Every update in a getUpdates page is written as it arrived (the raw update JSON) as soon as the page is read, before the turn path parses, classifies, batches or replays it. A message the turn path ignores is still on the card, and the whole updates of a page that will not parse are kept.
  • Media. Photos at the largest size Telegram offers, documents, voice notes, audio, video, video notes, stickers and animations are downloaded with their own streamed path, up to the 20 MB bot download limit. A type with no file to fetch (a location, a poll) is complete in the raw JSON. A type that cannot be fetched (a story, paid media, a game, an invoice, an unknown type, a file over 20 MB) gets an explicit not archived: <type> row.
  • Outbound. Every message the device sends: the whole text as written, before it is split into Telegram-size parts, and a copy of every file it sends. The record is what the device asked to send; delivery is not tracked there.
  • Chats not on the allowlist are saved as text only, within daily budgets (50 updates per chat, 200 updates and 2 MB across all of them, at most 32 such chats on the card), and their media is never downloaded (security.md).

Layout. One folder per chat and per day; the day of an inbound item is Telegram's own message date (UTC), so names never depend on uptime or the device clock, and a replay of the same update lands on the same name and adds nothing. An update already saved this boot (an album held over several polls, a page served again) is recognized without reading the card at all.

/mem/tg/<chat>/<yyyy-mm-dd>/<update_id>.json raw inbound update
/mem/tg/<chat>/<yyyy-mm-dd>/<update_id>.<ext> its media file
/mem/tg/<chat>/<yyyy-mm-dd>/<update_id>.turn.<ext> the assistant's own (smaller) copy
/mem/tg/<chat>/<yyyy-mm-dd>/o<seq>.json outbound message (o<seq>.<ext> for a file)
/mem/tg/<chat>/<yyyy-mm-dd>/index.jsonl one line per item, plus media status lines

The assistant's copy is kept at once. When a turn downloads a photo, document or voice note, the archive keeps that download the moment it exists. If it is the same file the archive wants, it becomes the media file and nothing is downloaded twice. If it is another size (a turn reads Telegram's 800 px photo, the archive keeps the largest), it is kept as <update_id>.turn.<ext> with its own status line, so the item is on the card at turn time, and the full-size file is still downloaded later, with its own status line; once it lands, the smaller copy is removed.

The outbound sequence continues from the names already in the day folder, so a restart or a clock jump never reuses one.

RAM and the radio. A download never holds a file in RAM: it is written to the card in 8 KB slices from one PSRAM buffer, as <name>.part, renamed when complete. It runs on the Telegram task with the single TLS session (after replies have gone out), for at most 8 s per poll cycle, and resumes from the bytes already on the card. A local turn or a factory reset cuts a transfer short; it resumes later. A card write or rename error leaves the .part file and an incomplete line, and the download is tried again from the .part on a later cycle; a network error is retried the same way. Each file gets four tries in all (the incomplete lines count them across a restart), then its last line says failed or incomplete. After a restart the archive fetches again whatever is still due in each chat's 14 newest day folders. An outbound message from another task is queued in PSRAM and written by the Telegram task, so no caller waits on the card.

Retention. The archive is not part of the episodic retention window or the blob clean-up: those passes never touch /mem/tg. It is removed only by:

  • the storage-pressure policy: when free space falls below 5% of the card (at least 512 MB on a card that can spare it), day folders are deleted until free space is back above one and a half times that mark: every day of the chats not on the allowlist first, then the allowlisted chats' oldest days. The newest allowlisted day is always kept, and the owner is told once per low-space episode.
  • the factory reset with storage erase, which deletes the whole /mem tree.

Reading it. The web page's Telegram archive group (Memory) lists the chats and their days, shows a day's items, opens a record or a photo in place, and Export Day saves a whole day as a ZIP. Each item says where its file stands: saved (a View or Save button), a smaller copy saved with the full size still to come, not saved yet, not saved (with the reason), or no longer on the memory card. Under it, GET /api/tg/archive lists chats, then a chat's days, then a day's items (paged with from and limit, counted in items; a page carries only the items that fit in about 14 KB and next says where the next page starts). The index is append-only (an item row says pending once, and each outcome is a later status line), so the route folds the status lines into their item and checks the card: an item's st is ok when a copy is on the card, pending while its file is still to be fetched, failed, incomplete (the card refused it and no tries are left), missing (not on the card and no longer fetched), or not archived: <why>. When the copy on the card is the assistant's smaller one, the item carries "copy":"turn", file names that copy and full gives the full-size file's own status. GET /api/tg/archive/item streams one record or file; GET /api/tg/archive/zip?chat=&day= streams that day as a ZIP (stored, one pass, no file held in memory). All need the device sign-in token, and the item and ZIP downloads go through the same memory admission as the page and the Files list: they slow down, or answer "busy" with a retry time, when the device is short of working memory. Saved media also appears on the web page under Memory, then Files, as read-only telegram-<chat> folders.

Restoring a backup. tools/tg_archive_import.py uploads a folder of backed-up media sidecars into the archive (each under the chat and day of the memory row that referenced it), through POST /api/tg/archive/import. It is a dry run unless asked to write, and a rerun skips what is already there.