# AO_AppMgr

The Active Object that owns the apps region: installs, runs and erases apps from a file, URL, console or mailbox, fetches data folders and updates kodeOS.

## What it is

An app on a Kode Dot is a whole firmware image, written into the **apps region**, a part of the flash. **AO_AppMgr** owns that region. It installs an app, starts an installed app by name, and erases one by name with every file it left on the board. It fetches an app's data folder from a URL. It also writes the inactive kodeOS slot, which is how `install dst=os` updates kodeOS.

It reads no file itself: AO_Storage reads and lends the bytes in chunks (`sdk/kaos/storage`). It does not decide which firmware starts either. AO_Boot does (`sdk/kaos/boot`), and the two AOs write different regions of the flash.

An image can come from four places: a file on a medium, a URL, the console, or the **mailbox**, the `app_pending` partition that a computer writes with esptool. Every install ends the same way. The directory, the list of installed apps, is updated in one commit after the written image is verified. While it has nothing else to do, AO_AppMgr copies each installed app to the card, so an install that must evict apps to make room evicts apps the card already keeps. Each install leaves a record, and the port of the command that asked hears how it ended.

## How it is connected

```mermaid
flowchart LR
  file["File on a medium"] --> sto["AO_Storage"]
  url["URL"] --> net["AO_Net"]
  sto --> ao["AO_AppMgr"]
  net --> ao
  con["Console"] --> ao
  mbx["Mailbox<br/>app_pending"] --> ao
  ao -- "install, erase" --> region["Apps region"]
  ao -- "install dst=os" --> slot["Inactive<br/>kodeOS slot"]
  ao -- "run request" --> boot["AO_Boot"]
  class ao,sto,net,boot ao
  class region,slot,mbx store
```

*Where an image comes from and where it goes*

```mermaid
stateDiagram-v2
  [*] --> idle : claim, kdrv_apps_init, mailbox check
  [*] --> recovering : NVS holds the victims of a cut install
  recovering --> idle : victims put back or given up
  idle --> backing : 100 ms idle, an app has no copy on the card
  backing --> idle : a request, or every app seen to
  idle --> opening : FLASH_REQ_SIG from a file, card or URL
  opening --> flashing : source open, both buffers primed
  flashing --> idle : eof verified and installed, or a failure
  idle --> receiving : APP_RECV_REQ_SIG, console armed first
  receiving --> launching : installed, run requested
  idle --> adopting : APP_ADOPT_SIG, mailbox holds an image
  flashing --> verifying : the plan evicts, the file is read through first
  verifying --> idle : file sound, the request is posted again
  flashing --> keeping : the plan evicts, the victims' CRC first
  adopting --> keeping : the same, for the mailbox
  keeping --> idle : CRCs taken, the request is posted again
  flashing --> copying : the plan evicts an app with no copy yet
  idle --> copying : the same, for a console install
  copying --> idle : the app seen to, the request is posted again
  idle --> asking : APP_EVICT_REQ_SIG
  flashing --> tidying : image committed, data folder follows
  idle --> tidying : app_erase
  tidying --> idle : AO_Storage answered
  idle --> fetching : APPDATA_GET_REQ_SIG
  fetching --> idle : folder written, or the fetch failed
  launching --> idle : APP_RECV_LAUNCH_SIG
```

*AO_AppMgr's states*

```mermaid
sequenceDiagram
  autonumber
  box "kodeOS"
    participant A as AO_AppMgr
    participant S as AO_Storage
  end
  A->>S: STORAGE_OPEN_REQ_SIG
  S-->>A: STORAGE_OPEN_RSP_SIG, size
  A->>S: READ_REQ x2, both buffers
  S-->>A: STORAGE_DATA_SIG, buffer 0
  Note over A: writes chunk N to flash while S fills buffer 1
  A->>S: STORAGE_NEXT_SIG, buffer 0 back
```

*An install from a file, two buffers*

AO_AppMgr in numbers:

| Thing | Value |
| --- | --- |
| Priority | 9 |
| Queue | 16 events |
| Stack | 8192 bytes, the default tier |
| Claims | `KBSP_RES_APPS_REGION`, `KBSP_RES_APP_PENDING`, `KBSP_RES_OTA_SLOT` |
| Compiled under | `KODEOS_APPMGR` |
| Flash access | `kdrv_apps`, `kdrv_slot` and `kdrv_kfw` (`sdk/kdrv/apps`) |

The stack is that large because the install path holds two directory copies of about 1 KB on it, and at 4 KB a streamed install overflowed and hung with no panic.

### The hierarchy

`idle` is the only state that accepts work. Every other working state sits inside a parent, `AppMgr_busy`, which answers a question about the next install ("what would you evict?") with a busy end marker and settles late answers from AO_Storage. A new write, run, erase or list request that arrives in a working state is refused and never queued, so two images cannot mix in one place of the flash. A refused erase is answered, because the console and the launcher wait for its end: `APP_ERASE_DONE_SIG` carries `KODE_DENIED`.

`opening`, `flashing`, `adopting`, `verifying`, `keeping`, `copying`, `tidying` and `fetching` log the refusal. `receiving` and `launching` ignore it silently. `app_cat` is the exception: the console waits for its answer, so a refused one is answered with `KODE_DENIED`.

`backing` is the one working state inside `idle` rather than `AppMgr_busy`. A request that `idle` acts on gives up the copy in hand first, then runs as it would from `idle`.

### The copy

`FLASH_REQ_SIG` carries three things:

- a source kind: `KFW_SRC_FS`, `_SD`, `_HTTP` or `_PENDING`;
- a destination: `KFW_TARGET_APP`, `_OS`, or `KODE_FLASH_DST_PENDING`, the mailbox;
- a `launch` flag.

A URL moves the whole conversation from AO_Storage to the stream loan of AO_Net; the protocol is the same. Each chunk goes to the decoder of `kdrv_kfw`, which tells a bare `0xE9` image from a `KFW1` container and inflates compressed ones, so progress counts the image and not the bytes that carried it. A URL holds up to 256 characters and travels whole. The progress events and the log of AO_AppMgr name it by its last path segment, and no log line prints its query, where a token usually rides. A file name holds up to 63.

The image is placed in the decoder's header callback, the only moment its true length is known. For `dst=app` that is `kdrv_apps_plan()` on a copy of the directory, told which installed app the header names. When there is no room it evicts that app's old copy first, then the oldest apps the card keeps, then the oldest of the rest, by sequence number, so a new version costs no other app while it fits the room of the old one. For `dst=os` it is a size check against the slot, and `launch` is forced off because the switch of AO_Boot is the launch. `dst=c5` never reaches AO_AppMgr: the console sends it to AO_Radio.

### The pacer

After a chunk is written, AO_AppMgr waits one 10 ms tick before it hands the buffer back. Erasing flash holds the cache down and nothing in flash runs, the GUI included, so the gap gives the interface a slot.

The returned buffers collect in the `to_return` bitmask and one pacer returns them all. Arming it once per buffer would produce two "next" requests for one loan, AO_Storage would refill the same buffer twice, and the image would be corrupt with a byte count that still adds up. The gap costs about 1.6 s on a 5 MB image.

### Verify, then commit

`xfer_end()` verifies the written extent in place with the real image verifier. For `dst=app`, `region_install()` then runs these steps:

1. Zero the entry of an app with the same name (installing replaces).
2. Take the next sequence number, before compacting.
3. Compact the directory.
4. Evict the oldest entry when the directory holds `KAPPS_MAX_ENTRIES` (64).
5. Append the new entry.
6. Make one `kdrv_apps_dir_commit()`.

AO_AppMgr then publishes `APP_FLASH_DONE_SIG` with the project name. An image sent to the mailbox (`dst=pending`) is parked, not installed: it has no directory entry, and the done goes out with an empty name so that the card the interface raised for the write ends. When `launch` is set, `region_launch()` resolves the extent out of the committed directory by name, the same path `APP_RUN_REQ_SIG` takes, and asks AO_Boot for a one-shot run.

### The install records

AO_AppMgr keeps two records in NVS, in the namespace `kappmgr`: the last app install (`inst_app`) and the last kodeOS update (`inst_os`). It numbers an install when it takes it, with one count for both kinds; a request refused before that leaves no record. An image from the mailbox, or for the mailbox or the C5, keeps none. The record is one line on the port of the command that asked:

```text
>|install id=7 dst=app state=installed pct=100 name="blinky" version="1.2.0" why=-
```

The line goes out when the install is taken, every 5 points while it runs, and once more when it ends. The progress lines are plain lines, kept nowhere. None goes to a stream from the terminal while it is sending, to the scheduler or to a port that is down, and one the console is too far behind for is skipped. An install from the launcher keeps its record and tells no port.

| Field | Values |
| --- | --- |
| `id` | AO_AppMgr's number, from 1. `0` with `state=none`: no install of that kind was ever taken |
| `dst` | `app` or `os` |
| `state` | `none`, `running`, `installed` (an app in the directory, or kodeOS in its slot with the switch asked), `failed`, `confirmed` (the new kodeOS stayed up a minute), `rolled_back` (the board came back to the old kodeOS) |
| `pct` | How far the install got, copies included. A running record read with `install_info` shows the live percent |
| `name`, `version` | The image's project name and version, quoted, once the image named itself |
| `why` | `-` when nothing went wrong. `missing` (no such file, or the server said no), `cut` (the source stopped before the image ended), `corrupt` (what arrived did not verify, or a file read through before an eviction did not hold together), `write` (the image could not be written), `no_room`, `wrong_board`, `busy` (the network's one download was someone else's), `keep` (an app it would evict has no copy on the card yet: ask again), `cancelled`, `stalled` (the terminal stopped sending), `reset` (a reset cut the install), `switch`, `unconfirmed`, `crashed`, `other` |

A kodeOS update ends `installed` just before the switch. Its verdict comes with AO_Boot's `BOOT_STABLE_SIG`, once the kodeOS running has stayed up 60 s (`KODE_BOOT_STABLE_MS`): `confirmed` when the written slot runs, `failed why=switch` when the board never ran it, or `rolled_back` with `why=crashed` or `why=unconfirmed`. `BOOT_OS_SWITCH_FAIL_SIG`, otadata that could not be pointed at the slot, is `failed why=switch` at once. A record left `running` by a reset reads `failed why=reset` at the next boot.

On the Kode channel and the BLE console a record is a confirmed line (`CONSOLE_SENT_SIG`). One that did not leave the board is owed and told again when that port comes up. A final record is said at once and confirmed later. An app launch and a kodeOS switch reset the board right after the record is written, so on those two ports the record is told again once the board is back in kodeOS. A host may hear the same state twice and tells the lines apart by `id` and `state`.

`install_info` (`INSTALL_INFO_REQ_SIG`, `InstallInfoReqEvt` with `who` and `src`) writes both records to the asking port, the app's first, then `>ok`. AO_AppMgr writes the lines itself, so they reach the port before the `APP_REQ_RSP_SIG` that closes the command.

### Erasing an app

`APP_ERASE_REQ_SIG` takes everything of an app off the board. In one idle step AO_AppMgr zeroes the directory entry, compacts and commits it, clears the first 4 KB of the extent, drops the app's category override and consumes a mailbox image of the same project. It then asks AO_Storage to take the rest in one request: the app's image files at the root of the card and of the internal FAT, found by the project name in their descriptor, and its data folder on each medium. The app need not be installed, so a file left on a medium is removed the same way.

Every erase ends in one published `APP_ERASE_DONE_SIG` (`name`, `status`, `image`, and the `fs` and `sd` results), a refusal included. `status` is `KODE_OK` when nothing of the app is left, `KODE_ERROR` when there was nothing of that name, `KODE_IO_ERROR` when something would not go, `KODE_DENIED` when AO_AppMgr or AO_Storage was busy and `KODE_TIMEOUT` when AO_Storage did not answer within `APPMGR_WIPE_MS` (20 s). The console's `app_erase` waits for it.

### Fetching a data folder

An app's data folder travels apart from its image and can be on the board before the app is. `APPDATA_GET_REQ_SIG` (`appmgr_appdata_get_request(project, url, install, who)`) reads `<url>app.json` and, when that file names its icon `icon.k64`, `<url>icon.k64`, through AO_Net into one buffer. It then hands the buffer to AO_Storage, the folder's only writer. The base URL holds up to 199 characters (`KODE_APPDATA_URL_MAX`) and ends with a slash.

The file is judged before the folder is written: `app.json` must parse as the folder's reader parses it, and an icon of another name is refused. The icon is only how the app looks, so an icon that does not come whole, or is neither 49152 nor 12288 bytes, costs the icon alone: `app.json` is written without it, the app shows the letters of its name, and the log says `the icon of '<project>' did not come; its app.json is written alone`. One fetch runs at a time, and none while an image is written, since the transfer is AO_Net's one. `APPDATA_GET_RSP_SIG` (`project`, `why`, `icon`) always answers: `why` is one of `ok`, `busy`, `name`, `fetch` (`app.json` did not come), `json`, `full` (the internal partition would be left under 128 KB free) or `store`. A fetch that made no folder ends its card with `APP_FLASH_FAIL_SIG` and `KFAIL_DATA`: no app was installed or touched, and the interface lets the card go without a failure.

A fetch asked with `install` is the first step of an install, and its card is the install's. Whatever the fetch's end, no done and no failure goes out: the card stays at 0 %, said again every second, until an install from a medium or a URL takes it over. Anything else AO_AppMgr turns to, or 15 s with no install (`KODE_APPMGR_HOLD_MS`), ends the card with an unnamed `APP_FLASH_DONE_SIG`. The console's `appdata_get` asks with `install` unless its line says `install=off`.

### Copies on the card

An app that came from a URL, the console, the mailbox or the internal FAT has no other copy. Once AO_AppMgr has been idle for 100 ms (`KODE_APP_BACKUP_IDLE_MS`), at boot and after every install, it enters `backing` and copies the installed apps to `/sdcard/<project>.bin`, oldest first, one at a time. A copy that was written, or could not be, is followed by a pause of 1 s (`KODE_APP_BACKUP_GAP_MS`) so AO_Storage's other askers get their turn, and an app whose copy was already on the card is followed by the next app with no pause. The copy is the extent byte for byte: a verified, bootable image with its own manifest, so the launcher shows the file as an app to install again.

For each app a STAT asks whether the file is there, and the descriptor of a file found there gives its build id. A file of the same length with the app's build id is the copy, and nothing is written. With no file there, or with an older copy this board wrote, the extent is read from the region 32 KB per tick into PSRAM, written as `/sdcard/<project>.bin.tmp` and then put on its name, so a cut copy never looks like an app. The log says `'<project>' copied to /sdcard/<project>.bin`. AO_Storage removes what a cut copy left when the card mounts.

Any other file at the app's name is left as it is: a newer build put on the card to install from, or a file that is not an app. The log says `'/sdcard/<project>.bin' is not a copy this board wrote; it is left as it is, and '<project>' has no copy on the card`. Until the next boot or change of card the app counts as one whose copy could not be made, so an install evicts it without waiting. AO_AppMgr tells its own copies by their build ids, which it keeps in NVS (`kappmgr`, key `written`, the last 32): the id of each copy it writes, and of each copy it finds that matches the installed image.

What has been copied lives in RAM only. It starts again at every boot and at every change `STORAGE_CARD_SIG` reports: a mount, a removal, and a card an app's rest put away, since a card can be changed while its supply is off. Only a card that took the write check gets a copy (`sdk/kaos/storage`). With no card, nothing is copied until one mounts. A card too full for an app's copy is said once per card mounted: the log names the app, and `APP_CARD_FULL_SIG` tells the interface.

A card at rest for an app (`KODE_REST_CARD`, `sdk/kaos/part-rest`) is still in, and AO_AppMgr leaves it at rest: the idle copies and the dark wake begin nothing on it. Only an install that waits for a victim's copy wakes it, with the log line `an install wakes the card from its rest to copy '<project>' first`, and the card then stays awake. A copy step already out when the rest lands may still bring the card back.

The copy gives way. Every request that `idle` acts on gives up the copy in hand, and the copies start again 100 ms after AO_AppMgr is idle again. A download into a file cuts a copy in flight and refuses new ones while it runs (`sdk/kaos/storage`). With `CONFIG_KODE_LOWPOWER` a board about to sleep with copies owed asks AO_LowPower to wake it 5 s later (`KODE_APP_BACKUP_DARK_MS`, `lowpower_wake_at`), and the copies run in that dark wake with the glass off. A copy that the end of a dark wake cuts waits for the board to be awake.

### Evicting

`kdrv_apps_plan()` evicts the app being replaced first, then the apps the card keeps, oldest first, and only then the others (`sdk/kdrv/apps`). Before anything is evicted, AO_AppMgr looks at each victim:

- **The card could take its copy and has none yet.** The install waits in `copying` with nothing committed, and AO_AppMgr copies that app at once with the steps of the idle copies. The log says `the install waits: '<project>', which it would evict, is copied to the card first`. A card at rest for an app counts as in, and the copy's first request wakes it. The app the install replaces never makes it wait.
- **The card keeps it, its copy could not be made, or no card answers.** It is evicted. `APP_EVICTED_SIG` says with `kept` whether the card holds a copy. The log says `evicting '<project>' to make room; its copy is on the card` as a notice, or `evicting '<project>' to make room; no copy kept` as a warning. A kept app keeps its data folder; the install's tidy step deletes the others' folders.

While it waits, the install publishes `APP_FLASH_PROGRESS_SIG` at 0 % at once and every second, so the write card and the LED have something to follow, and every other request is refused as busy. Once the app is seen to, the same request starts again at the front of the queue, and a plan that then names another app with no copy waits for that one too. An install from a file or a URL lets its source go and opens it again. A console install is held before the console is armed (see below). The mailbox stays where it is and is adopted once that app is seen to.

The wait ends in one of three ways:

- **The copy is made, or was already there.** The app is evicted with its copy on the card.
- **The card takes no write, is full, is gone or never answers.** The app is evicted with no copy, as with no card. A step that gets no answer is given up at its own deadline, `APPMGR_OPEN_TICKS` for a STAT and `APPMGR_KEEP_WRITE_TICKS` for a write.
- **The card stays busy.** A step the card refuses as busy is asked again 1 s later. After 30 refusals (`KODE_APP_COPY_BUSY_TRIES`) the install ends as busy with nothing changed. `APP_FLASH_FAIL_SIG` carries `KFAIL_BUSY`, the record of an install from a file or a URL says `why=keep`, and a console install answers `>err code=4 msg=busy`.

An install from a file on a medium that evicts reads the file through once first, in `verifying`, so a file that does not verify costs no app. The chunks go through the decoder into `kdrv_image_check`'s sink and are written nowhere, one 32 KB chunk per paced step with no buffer of its own. A bare image is judged as it is. A `.kfw` container is judged as the image its payload decodes to, inflated when it is deflated, and the container's digest is compared at its end, so a cut container evicts nothing. The log says `'<file>' reads through whole`, or the install fails with nothing given up:

| Log line, after `install failed:` | `why` | Cause |
| --- | --- | --- |
| `the file is cut or damaged; nothing was given up` | `corrupt` | The image or the container does not hold together: cut, a bad chain or a digest that does not match |
| `the file is cut or damaged; nothing was given up` | `wrong_board` | The image or the container is for another chip or target |
| `the decoder is busy; nothing was given up` | `other` | Another owner holds the one decoder, AO_Radio updating the C5 |
| `the file could not be read through; nothing was given up` | `other` | The decoder could not run, for example with no PSRAM for the inflater |
| `the file could not be read through; nothing was given up` | `corrupt` | The file would not open a second time |

An install from a URL or from the terminal cannot be read twice and is not read through, and the mailbox is verified in place (`sdk/kdrv/apps`). AO_AppMgr then takes the CRC of each victim's extent, 512 KB a step, in `keeping`, and posts the same request again at the front of its queue. The victims go into NVS (`kappmgr`, key `undo`) before the directory is committed. An install that fails puts back, in one directory commit, every victim its write did not reach. One a reset cuts is settled at the next boot in `recovering`: each victim whose extent still has its CRC is put back. Until then every request but a listing is refused as busy, and a listing waits. A console install cannot pause for the CRC; its victims are read in one step.

### Install from the console

`install src="terminal"` is its own request, `APP_RECV_REQ_SIG`. In `idle` AO_AppMgr checks that the region or the slot exists and fits, then asks AO_Log for raw mode first, before any flash work, because an erase stops the reader task and an arming that lands inside it cannot tell the command's newline from the first payload byte.

In `receiving`, the transfer runs in four steps:

1. AO_AppMgr makes room, opens the sink, tightens the watchdog from the 30 s long-stop to the 5 s gap and publishes `RECV_READY_SIG`.
2. The host sends 4096-byte chunks (`RECV_DATA_SIG`, posted by the reader task).
3. AO_AppMgr stages each chunk, takes its CRC, writes it, and publishes `RECV_ACK_SIG` for each whole chunk.
4. At the full count it compares the CRC, verifies, installs and publishes one of three static outcome events: `RECV_DONE_SIG`, `RECV_FAIL_SIG` or `RECV_STALL_SIG`.

The room is made before the first byte arrives, so the plan cannot read the image's name. The request carries it instead, from `install … name="<project>"`, which kcli and kble send, and the old copy of that app goes first. Without `name` the plan treats the image as a new app. Each app evicted is published as `APP_EVICTED_SIG` before `RECV_READY_SIG`, and the console prints it as `>|evicted`.

A plan that would evict an app the card could still copy is made in `idle`, before raw mode is asked for. The request waits in `copying` and comes back by itself once that app is seen to, so the ready is late and the host sends nothing meanwhile. With each 0 % of the wait AO_AppMgr publishes `RECV_WAIT_SIG`, and the console answers `>|wait` and gives the command its 5 s again. `RECV_AGAIN_SIG` ends a stream with `>err code=4 msg=busy` when the card stayed busy through the wait. It does the same when a compressed image evicts an app with no copy that its length on the wire did not, which AO_AppMgr learns from the image's header once the bytes are arriving.

The acks pace the transfer on every port: the host sends the next chunk only when the last one is in flash. A failed write stops neither the draining nor the acks, since the host still owes the full count.

A failure after the 0 % report also publishes `APP_FLASH_FAIL_SIG`, so the Opening card ends as a failure. The `launching` state waits 50 ms so the `>ok` leaves the console before the board resets.

### Mailbox adoption

At boot, and for `install src="pending"`, AO_AppMgr checks `kdrv_apps_pending_present()` and posts `APP_ADOPT_SIG` to itself, because a copy of several MB must not run inside an initial transition. It reads the destination from the OS-intent sector (unless `dst=` was typed), reads the project name from the head of the mailbox, plans with it, and copies 4 KB per tick in `adopting`.

A deterministic failure (the image does not verify, the directory is full and nothing can be evicted) consumes the mailbox so no later boot adopts it again. A directory commit failure or an I/O error leaves it, and the next boot tries again. On success the mailbox is consumed after the commit.

A boot-time adoption then starts the app with `KBOOT_RUN_STICKY`, the one sticky request kodeOS writes, so the app survives the reset that the host's port opening causes. A typed `install src="pending"` starts it once, and only with `run=on`.

### Resting with the board

With `CONFIG_KODE_LOWPOWER`, AO_AppMgr joins the rounds of AO_LowPower as `appmgr` (`sdk/kaos/lowpower`). It owns no device that sleeps. It owns work that must not be cut: an image being written, verified or received, an install that waits for a copy, a launch on its way and the asks of an eviction are every state but `idle`. Each of those answers a round busy (`app write`), and `idle` answers ready. A copy to the card never refuses a round: `backing` gives up the copy in hand and answers ready, and a round for ASLEEP with copies owed asks for the dark wake described above. Nothing is restored when the board wakes. An AWAKE that arrives during an install ends the rest AO_AppMgr had noted, so the copies go on as soon as the install ends.

## Specifications

### Requests

| Signal | Event | From | What AO_AppMgr does |
| --- | --- | --- | --- |
| `FLASH_REQ_SIG` | `FlashReqEvt` (`src_kind`, `dst_kind`, `launch`, `src`) | `kode_sys_flash()`, the console, the launcher | The only way to ask for a copy. `appmgr_flash_request(file, launch)` is the form `src="fs:…" dst=app` |
| `APP_RECV_REQ_SIG` | `AppRecvReqEvt` (`dst`, `size`, `crc32`, `launch`, `src`, `name`) | `appmgr_recv_request()` | An image arrives on the console |
| `APP_RUN_REQ_SIG` | `AppFlashEvt` (`file`) | `appmgr_run_request()` | Resolves the name in the directory and asks AO_Boot for a one-shot run. Logs `'<name>' is not installed` otherwise |
| `APP_ERASE_REQ_SIG` | `AppFlashEvt` | `appmgr_erase_request()` | Zeroes the entry, compacts, commits, then `kdrv_apps_erase_header()` clears the first 4 KB of the extent, and AO_Storage takes the app's files off both media. Ends in `APP_ERASE_DONE_SIG` |
| `APPDATA_GET_REQ_SIG` | `AppDataGetReqEvt` (`project`, `url`, `install`, `who`) | `appmgr_appdata_get_request()`, the console's `appdata_get` | Fetches an app's data folder from a base URL and has AO_Storage write it |
| `APP_CAT_REQ_SIG` | `AppCatReqEvt` (`project`, `cats`, `clear`) | `appmgr_cat_request()` | Sets or clears the category override in NVS. AO_AppMgr is the only writer of that table |
| `APP_LIST_REQ_SIG` | `AppListReqEvt` (`skip`, `who`) | `appmgr_list_page()` | Posts up to 24 `APP_ENTRY_SIG` and an end marker to `who` |
| `APP_EVICT_REQ_SIG` | `AppEvictReqEvt` (`size`, `project`, `who`) | `appmgr_evict_query()` | Plans an install on a copy of the directory and posts up to 8 `APP_EVICT_ENTRY_SIG`, then `APP_EVICT_END_SIG` (`victims`, `fits`, `busy`) |
| `INSTALL_INFO_REQ_SIG` | `InstallInfoReqEvt` (`who`, `src`) | `install_info` | Writes the two install records to the port `src`, then posts `APP_REQ_RSP_SIG` to `who` |
| `STORAGE_OPEN_RSP_SIG`, `STORAGE_DATA_SIG`, `NET_STREAM_OPEN_RSP_SIG`, `NET_STREAM_DATA_SIG` | Storage and stream events | AO_Storage, AO_Net | The loan |
| `STORAGE_PATH_RSP_SIG`, `STORAGE_WRITE_RSP_SIG` | `StoragePathRspEvt`, `StorageWriteRspEvt` | AO_Storage | The answers of `backing`, `copying` and `asking` |
| `STORAGE_CARD_SIG` | `StorageCardEvt` (`mounted`, `rested`) | AO_Storage | Forgets what has been copied, and starts the copies again. With `rested` set the card counts as in, and only an install that waits for a copy wakes it. A card that goes ends the wait of `copying` |
| `BOOT_STABLE_SIG`, `BOOT_OS_SWITCH_FAIL_SIG` | `BootStableEvt` (`running`, `other`), none | AO_Boot | Settle the record of the last kodeOS update |
| `CONSOLE_SENT_SIG` | `ConsoleSentEvt` | AO_Log (BLE), AO_Net (the Kode channel) | A record line left the board, or could not |
| `APPDATA_PUT_RSP_SIG`, `APPDATA_RM_RSP_SIG`, `STORAGE_APP_WIPE_RSP_SIG` | `AppDataPutRspEvt`, `AppDataRmRspEvt`, `StorageAppWipeRspEvt` | AO_Storage | The answers of `tidying`, `fetching` and an erase |
| `CONSOLE_RAW_RSP_SIG`, `RECV_DATA_SIG` | `ConsoleRawRspEvt`, `RecvDataEvt` | AO_Log, the reader task | The console install |
| `LOWPOWER_ROUND_SIG` | `LowPowerRoundEvt` | AO_LowPower, subscribed with `CONFIG_KODE_LOWPOWER` | Answers ready in `idle` and `backing`, busy `app write` in every other state |
| `LOWPOWER_STATE_SIG` | `LowPowerStateEvt` | AO_LowPower, with `CONFIG_KODE_LOWPOWER` | Runs the copies when the board is awake or in a dark wake. In a working state it only notes that the board is awake |

Private: `APP_ADOPT_SIG`, and the `QTimeEvt`s `APP_FLASH_CHUNK_SIG`, `APP_RECV_IDLE_SIG` and `APP_RECV_LAUNCH_SIG`.

### What it sends

| Signal | Event | Range | Meaning |
| --- | --- | --- | --- |
| `APP_FLASH_PROGRESS_SIG` | `AppProgressEvt` (`percent`, `what`, `file`, `project`) | publish | 0 % when a write starts, then each whole percent. `what` is `KWRITE_APP`, `_APP_RUN`, `_OS` or `_C5`. `project` names the app once the writer knows it, so the card can show the app's own data folder while it is written; it is empty for kodeOS and the radio. The Opening card and the LED pulse of AO_Power follow it. The log keeps a 10 % step |
| `APP_FLASH_DONE_SIG` | `AppFlashDoneEvt` (`name`) | publish | The app installed; `name` is empty when the descriptor could not be read or when an image was parked in the mailbox, and a static event goes out when the pool is dry |
| `APP_EVICTED_SIG` | `AppEvictedEvt` (`name`, `kept`) | publish | One per app an install evicts, before the write starts. `kept` says a copy is on the card. The old copy of the app being replaced is not one |
| `APP_FLASH_FAIL_SIG` | `AppFlashFailEvt` (`why`) | publish | `KFAIL_WRITE`, `KFAIL_BUSY` when nothing was written because the card stayed busy while an app the install would evict was copied to it (ask again), or `KFAIL_DATA` when a fetch made no data folder. One static event per reason |
| `APP_CARD_FULL_SIG` | none | publish | An app's copy does not fit the card, and that app has none. Once per card mounted; bare and static. The interface says the card is full |
| `>\|install` lines | none | to the asker's port | The install records, through the console's reply path |
| `APP_ERASE_DONE_SIG` | `AppEraseDoneEvt` (`name`, `status`, `image`, `fs`, `sd`) | publish | The end of every erase, a refusal included. `image` says an installed image was removed. `fs` and `sd` each say whether the medium was walked, how many images went or stayed and what became of the data folder |
| `APPDATA_GET_RSP_SIG` | `AppDataGetRspEvt` (`project`, `why`, `icon`) | post to the asker | How a data folder's fetch ended |
| `APP_CAT_RSP_SIG` | `AppCatRspEvt` | publish | The outcome of `APP_CAT_REQ_SIG` |
| `RECV_READY_SIG`, `RECV_ACK_SIG`, `RECV_DONE_SIG`, `RECV_FAIL_SIG`, `RECV_STALL_SIG`, `RECV_AGAIN_SIG`, `RECV_WAIT_SIG` | none | publish | The receive protocol. The three outcomes are static and cannot fail to allocate. `RECV_WAIT_SIG` says a stream is held back while an app it evicts is copied, at once and every second. `RECV_AGAIN_SIG` refuses a stream for now |
| `APP_ENTRY_SIG`, `APP_LIST_END_SIG`, `APP_EVICT_ENTRY_SIG`, `APP_EVICT_END_SIG` | `AppEntryEvt`, `ListEndEvt`, `AppEvictEntryEvt`, `AppEvictEndEvt` | post to the asker | Pages and eviction answers |
| `BOOT_APP_RUN_SIG`, `BOOT_OS_SWITCH_SIG` | `BootRunEvt`, none | post to AO_Boot | After a verified write, `app_run`, or an adoption |
| `CONSOLE_RAW_REQ_SIG`, `CONSOLE_RAW_END_SIG` | `ConsoleRawReqEvt`, none | post to AO_Log | Arm raw mode; abandon it on a stall |

### Timers and limits

| Name | Value | Bounds |
| --- | --- | --- |
| `pacer` (`APPMGR_CHUNK_GAP_TICKS`) | 10 ms | The pause before a buffer goes back, each 4 KB step of adoption and each 32 KB step of a copy to the card |
| `idle`, `APPMGR_RECV_IDLE_TICKS` | 5 s (`KODE_RECV_IDLE_MS`) | The gap between two chunks of a console install |
| `idle`, `APPMGR_RECV_LONGSTOP_TICKS` | 30 s | The wait for the answer that arms raw mode |
| `idle`, `APPMGR_OPEN_TICKS` | 30 s | `opening`, and a STAT answer |
| `idle`, `APPMGR_CHUNK_TICKS` | 30 s | The gap between chunks in `flashing`. Expiry is `KFAIL_WRITE` |
| `KODE_APP_BACKUP_IDLE_MS` | 100 ms | How long AO_AppMgr is idle before it looks at the copies of its apps |
| `KODE_APP_BACKUP_GAP_MS` | 1 s | The pause after a copy was written, or could not be, before the next app |
| `KODE_APP_BACKUP_DARK_MS` | 5 s | From the board falling asleep to the dark wake its copies ask for |
| `KODE_APP_COPY_BUSY_TRIES` | 30 | Steps the card may refuse as busy, 1 s apart, while an install waits for a copy |
| `APPMGR_KEEP_WRITE_TICKS` | 60 s plus 1 s per 128 KB | One copy to the card |
| `APPMGR_UNDO_STEP_BYTES` | 512 KB | What one step of `keeping` or `recovering` folds into a victim's CRC |
| `answer`, `APPMGR_ANSWER_DRAIN_TICKS` | 50 ms | From "installed" to the reset |
| `KAPPS_MAX_ENTRIES` | 64 | Apps in the directory. A full listing is three pages |
| `KODE_APP_EVICT_MAX` | 8 | Victims in one eviction answer |
| `KODE_RECV_CHUNK` | 4096 | Console chunk, and the static adoption buffer |
| `APPMGR_TIDY_MS` | 5 s | AO_AppMgr's wait for AO_Storage's answer to one data-folder request of an install |
| `APPMGR_WIPE_MS` | 20 s | AO_AppMgr's wait for AO_Storage to take an erased app's files off both media |
| `KODE_APPDATA_URL_MAX` | 200 | The base URL of a data folder's fetch, terminator included |
| `KODE_FLASH_SRC_MAX` | 257 | A source with its terminator: a URL of up to 256 characters. A console line carries fewer |

The `idle` timer is shared by `opening`, `flashing` and `receiving`. These states exclude each other and each disarms it on exit. The timer `idle` and the state `idle` are two things. The copies to the card run on a timer of their own, `bk_tmo`, which holds the wait, the pace and the deadline of the step in hand.

### Console verbs, calls and settings

`app_list`, `app_run name="…"`, `app_erase name="…"`, `appdata_get name="…" url="…"`, `app_cat`, `install_info`, `install src=… dst=os|app|c5|pending`, with `name="<project>"` for `src="terminal" dst=app` only. `install` off a medium, a URL or the mailbox answers `>ok` once AO_AppMgr took it, `>err code=4 msg=busy` when it has work in hand, and `>err code=5` with `missing`, `empty` or `refused` otherwise; the `>|install` record of a taken install comes before that answer. `app_erase` holds the console until the erase ends and prints `>|erased name=… image=removed|none` and one `>|erased where=fs|sd` record per medium, then `>ok`. It answers `>err msg=missing` when there was nothing of that name, `left` when something stayed, `busy` and `storage`. `appdata_get` answers `>|appdata project=… json=ok icon=ok|none` and `>ok`, or `>err msg=<why>`. The call for an Active Object or a task is `kode_sys_flash(src, dst, run)`: `src` is `"fs:<file>"`, `"sd:<file>"`, a bare name or an `http://` or `https://` URL, `dst` is `"os"` or `"app"`, and it posts and returns `KODE_OK` when AO_AppMgr's queue took the request. AO_AppMgr owns the category override table of `kapp_cat`, an NVS blob. The format of the region and the directory is on `internals/apps-region`.

## Gotchas

> **WARNING**
>
> **A request that arrives during a write is dropped.** The log reads `busy writing the region (40%); request ignored`. Nothing is queued. Wait for `APP_FLASH_DONE_SIG` or `APP_FLASH_FAIL_SIG` before you ask for the next install or a run.

> **WARNING**
>
> **An uploaded sketch loops until you replace it.** Mailbox adoption at boot writes a sticky request. The bootloader keeps it across the resets a working app or its host produce, including the port opening, and retires it on power-on (BOT+LEFT), a hardware watchdog or brownout. A crashing sketch therefore restarts on its own until a new upload or BOT+LEFT (`internals/boot-model`).

> **WARNING**
>
> **An install ends with `busy`.** AO_AppMgr copies an app the install would evict to the card first, and two things can still end that as busy with nothing changed. The card stayed busy with another file for 30 s of the wait, and the log says `the card stayed busy while an app the install would evict was copied to it; ask again`. Or a `.kfw` sent over the console decodes to an image that evicts an app with no copy, and the log says `an app it would evict has no copy on the card yet; ask again`. The record of the install says `why=keep` when it has one. Ask again in both cases, once the card is free or the log says `'<project>' copied to /sdcard/<project>.bin`.

> **NOTE**
>
> **A transient adoption failure repeats at every boot.** A directory commit error or an I/O error leaves the mailbox in place, so the next boot adopts it again. A verification failure consumes it. Read the log for `mailbox left intact` before you reflash the mailbox.

## Example code

Install an app from the card and start it. With `blinky.bin` on the card, the board writes it, resets and runs it.

```c
/*
 * install_from_card.c - from Kode with love
 *
 * Asks AO_AppMgr to install /sdcard/blinky.bin into the apps region and run
 * it. kode_sys_flash() posts the request and returns; AO_AppMgr reads the file
 * through AO_Storage, verifies it, commits the directory and resets into the
 * new app. On a Kode Dot the Opening card shows, then the app starts.
 */
#include "kode.h"
#include "kode_sys.h"

#define TAG "install"

/* Post the install, then wait for the reset. */
void app_main(void)
{
    kode_init();

    if (kode_sys_flash("sd:blinky.bin", "app", true) != KODE_OK) {
        KLOG_E(TAG, "no installer in this firmware, or a bad argument");
        return;
    }
    KLOG_I(TAG, "install requested");
    for (;;) {
        kode_delay(1000);
    }
}
```

Compiled against the 0.1.1 SDK with ESP-IDF v6.1 on 2026-11-11. Not run on a Kode Dot.

## In the SDK

- [`components/kaos/appmgr`](https://github.com/kodediy/kode-sdk/tree/main/components/kaos/appmgr): `appmgr_ao.c`, the states, the copy and the adoption; `appmgr_backup.c`, the table of the copies on the card; `appmgr_outcome.c`, the install records.
- [`components/kdrv/apps`](https://github.com/kodediy/kode-sdk/tree/main/components/kdrv/apps): the directory format (`kapps_fmt.h`), the sinks and the decoder (`sdk/kdrv/apps`).
- [`kaos.h`](https://github.com/kodediy/kode-sdk/blob/main/components/kaos/core/include/kaos.h): `appmgr_flash_request()`, `appmgr_list_page()` and the other request helpers.
