# Mapa images

**Status:** built on `feat/images`, 2026-11-17, after Paul's "Go ahead" the same day on §10's recommended answers. Fable reviewed the build (`49d8df3`) and found CHANGES REQUIRED: 1 high, 7 medium, 14 low. It re-reviewed the answers (`4c95863`) and found CHANGES REQUIRED again: two medium (N1, N2) and six low (N3–N8). Its narrow check of N1 and N2 (`101962f`) APPROVED them, with five lows to fix before merge and no further review. All are answered on the branch, and §11's rounds 3 to 5 map each to its change. §3.1–§3.3 and §1.3 are amended for M1 and L4. Not merged, not deployed: §8's CARLOS steps are still to run. §12 records every choice the build made where this spec was silent, and where it departs.

**Revision 5, 2026-11-17.** Revision 5 names the Notion importer's `ImportCreate` and `ImportUpdate` as verbs that attach (§3.2, §7). That is a text change and was not reviewed.

**Revision 4, 2026-11-17.** For review. Nothing is built.
- Fable reviewed revision 1 (`4d40e4e`) and found CHANGES REQUIRED: 2 high, 9 medium and 16 low findings.
- Revision 2 (`c27a292`) answered them. Fable's round 2 found no high and five mediums, which revision 3 (`a2392bd`) answered. Fable's diff check of revision 3 found two mediums and five lows, with no high, and said no further round was needed. This revision applies them. §11 maps every finding to its change.

**Asked for by Paul, 2026-11-17:** *"we should handle image uploads. CARLOS Platform has everything we need to handle that."* The Notion importer (specced separately) depends on this spec. It must bring Notion's images across as real Mapa images (§7).

**Branch:** `design/images` (Mapa), from `main` `3b20386`.

**What still binds:**
- the base spec, `2026-11-12-mapa-design.md`, which is approved;
- the level-up spec, `2026-11-14-mapa-level-up.md`, which is approved and built;
- `AGENTS.md`'s hard rules.

This spec changes no trust property. It adds:
- one kind of object;
- one gate-4 row;
- one route that serves bytes.

§6 lists every server change and the gate that holds it.

**Names in this spec.** Its decisions are "decision 1" to "decision 4" (§1.2). Its gates are IMG1 to IMG7 (§6).

**Prior art in the suite:**
- **Slides** (`internal/slides/assets.go`, `d047eef`):
  - Bytes go in CARLOS's bucket and are served *through the app*. They are sniffed from the bytes and served with `nosniff` and a `sandbox` CSP.
  - Presigned URLs were tried first and never worked. The page CSP is `img-src 'self' data:`, and the bucket has no CORS rule.
  - Slides keeps SVG behind a sanitiser. Slides does not seal.
- **Docs**, plan 7 (`docs/superpowers/plans/2026-09-02-images-links-tables.md`):
  - It refuses SVG.
  - It stores sealed bytes with the stored type `application/octet-stream`.
  - Its placeholder is a decoration, and the node is inserted only when the upload succeeds.
  - An image pasted from another document is uploaded again.
- **rastrillo `blobs`** (in Mapa's pin):
  - `S3FromEnv` reads `CARLOS_STORE_*`.
  - It is a content-addressed `Put`/`Get`/`Delete`, with a SigV4 signer and no SDK.

---

## 1. Storage and sealing

### 1.1 What CARLOS gives an app

This comes from `carlos store --help`, Slides' live store, carlos/platform `internal/objstore` and `internal/console`, `docs/site/cli.md`, and the 2026-11-15 plan catalog.

- **The app gets its own bucket and IAM user** in `eu-west-1`. Slides' bucket is `carlos-store-bds-slides`.
  - The policy allows Get, Put and Delete on objects, and List on the bucket.
- **Credentials arrive as config:**
  - `CARLOS_STORE_BUCKET` and `_REGION` as env;
  - `_ACCESS_KEY` and `_SECRET_KEY` as secrets;
  - `_ENDPOINT` only on a deployment that has one.
  - `carlos store rotate` mints a new key and keeps the old one live until `--finish`.
- **There is no signing service and no proxy.** Presigning is the app's own job; rastrillo signs.
- **Encryption:** AWS's default server-side encryption. A reader with the credentials still sees plaintext, so this is not Mapa's seal.
- **There is no versioning and no lifecycle rule.** Nothing is deleted unless the app deletes it. Deleting an instance leaves its bucket.
- **Size and cost:** stored bytes count against the account's plan.
  - Free: 50 MB, or 1 GB kept for accounts approved for storage before 2026-11-15.
  - Personal: 25 GiB. Business: 500 GiB. Storage packs add 50 GiB each.
  - Past the plan's grace, `PutObject` is denied. Get and Delete still work.
- **Scanning is off by default.**
  - Under the new catalog, a plan with `storage_scan_required` (Free) does not refuse `store create`. It creates the store and then **forces scanning and enforcement** on it (`forceStoreScanning`).
  - It refuses a client-encrypted attestation. It refuses per-instance stores too.
  - A scanner reading ciphertext claims coverage it cannot have. One false "infected" tag would make an image unreadable.
  - §8 step 1 and Q5 deal with this.

### 1.2 Decisions

| # | Decision | Rejected |
|---|---|---|
| 1 | **The bytes are sealed in Mapa, under Mapa's DEK, before they leave the process. The bucket holds only ciphertext.** <br>• Mapa's `seal` package gains the purposes `image` and `image-record`, so each key is derived apart from every other key (build note 21). <br>• Before sealing, the plaintext is padded to the next multiple of 64 KiB. The true length is kept in the sealed record. <br>• The object is stored as `application/octet-stream`. | Plaintext in the bucket, as Slides does. Slides seals nothing; Mapa seals everything (base §4). An image of a whiteboard is as private as the page it sits on. Docs' plan 7 took the same view. <br>Using rastrillo's `blobs.Sealed`: `AGENTS.md` makes `seal/` Mapa's only encryption |
| 2 | **Readers get images only through Mapa**, at `GET /i/{id}`. That route checks scope, then reads, checks, opens and writes the image. | Presigned or public URLs. A URL cannot check scope, and the bucket holds ciphertext only the app can open. Slides found that its own CSP and the missing CORS rule refuse them anyway |
| 3 | **The object key is the SHA-256 of the ciphertext**, as rastrillo addresses everything. <br>• Every seal draws a fresh nonce, so two uploads of the same picture are unrelated objects. <br>• Before opening, Mapa checks that the bytes read hash to the key. A swapped object is refused, not served. | De-duplicating by plaintext hash. Equal keys would show, in plaintext, that Ana's private note and a team page hold the same picture: a link-graph fact that base decision 14 keeps sealed. Exact ciphertext sizes would show it too, which is why decision 1 pads |
| 4 | **Development and tests use `blobs.Dir`** beside the database, as Slides does. <br>• Production with no store bound boots, and upload answers 503: "Images aren't set up on this Mapa yet". <br>• A partly delivered store (a bucket with no key) also boots. Uploads answer 503 and a loud log line names the missing variable. An images fault never takes the knowledge base down. | Falling back to the database or local disk in production. The disk is ephemeral and hibernates, and SQLite blobs ride the replicated WAL. <br>Refusing to boot on a partial store, as Slides does |

### 1.3 The `images` table, and the gate-4 row

**One row per image.** An image is one picture in one place (§3). Copies are separate rows with separate objects.

| Column | Plaintext? | Why |
|---|---|---|
| `id` | yes | the row's own key, never shown |
| `public_id` | yes | the URL's id. Random base 36 from its own nonce stream, unique, as pages' public ids are (build note 32). Never sequential, so it counts nothing |
| `owner` (member id) | yes | who uploaded it. Pending images are their owner's only (§3.1), and quota counts by it |
| `page_id` (nullable) | yes | the page it is attached to; null while pending. Scope is answered from the page's rung without unsealing |
| `created_at` | yes | the pending window (§3.3) |
| `unreferenced_at` (nullable) | yes | when the page's current body stopped referencing it (§3.3). Retention runs as SQL over it |
| `stored_bytes` | yes | the ciphertext's size, padded to 64 KiB steps, for the quota. The bucket shows it anyway |
| `moved_from` (nullable) | yes | the deleted page a Restore moved it from (§3.2 item 4), so that page's drafts follow it. Added by the build (round 3, L4) |
| `object_key` | yes | the bucket key: a hash of ciphertext, which says nothing about content |
| `sealed_record` | sealed | the sniffed type, the width and height after orientation, and the true size |

- **No filename is kept,** sealed or not.
- **The alt text lives in the page body** (§2), so it is sealed with the body.
- **`image_trash (object_key, queued_at)`** is the queue of objects to delete (§3.3). It is plaintext and holds only keys.

**Base §4 gains one row:**

> `images (id, public_id, owner, page_id, created_at, unreferenced_at, stored_bytes, object_key)` and `image_trash (object_key, queued_at)` | serving, scope, quota and retention without unsealing | **how many images each page holds, who uploaded each, when, when it was taken out of the text, and its size to within 64 KiB**, on private pages too. Two images of the same padded size are not thereby the same picture, but small images all pad to one size, and large ones narrow the field.

That is the same shape as the existing rows "revision store" and "ciphertext sizes": counts, times and coarse sizes. It never shows content. It does not by itself show that an image on one page came from another page.

### 1.4 Serving

`GET /i/{id}` works in this order:

1. **Scope first** (§3.1). If the viewer may not read the image, the answer is the app's ordinary 404, with the same body and headers as an id that never existed.
2. **A readable image:**
   - If `If-None-Match` names `"<public_id>"`, the answer is `304`, and the store is not read.
   - Otherwise Mapa reads the object, checks its hash (decision 3), opens it, removes the padding and writes it.
3. **Headers:**
   - `Content-Type`: the sniffed type, taken from the sealed record;
   - `X-Content-Type-Options: nosniff`;
   - `Content-Security-Policy: default-src 'none'; sandbox`;
   - `Content-Disposition: inline`;
   - `Cross-Origin-Resource-Policy: same-origin`;
   - `ETag: "<public_id>"`.
4. **Caching:** `Cache-Control: private, max-age=3600, immutable`.
   - An id's bytes never change, so `immutable` is honest.
   - `private` keeps CARLOS's edge and every shared cache out.
   - **The hour is the stated bound.** A person who loses access to an image, or sees it removed (§3.3), may still have their browser's own copy for up to an hour. Help says so.
   - Pages that carry the editor island stay `no-store` (level-up §6.8). Only the bytes are cached.
5. **Memory: one semaphore covers every blob operation.** That means uploads, serving, copies and the importer.
   - It admits four at a time. Each holds at most about 30 MiB: the body, the sealed copy and the opened copy, for a 10 MiB image.
   - Waiters queue. An upload or copy that waits 10 s answers 503 with `Retry-After`. **`GET /i/{id}` waits up to 30 s**, because a 503 there is a broken image. The editor's NodeView reloads a failed image once after 2 s. The importer's calls wait without a limit (§7).
   - So blob work costs at most about 120 MiB. The figure is measured on the instance's real memory size at build time and recorded in the build notes.
   - Streaming, chunked sealing is the fix if that bound is ever too much (§9).

---

## 2. The Markdown form

### 2.1 Syntax: the standard form, with an address of Mapa's own

```
![A whiteboard after the pilot review](/i/2kq9xw3m1ab)
```

- **An image is the standard `![alt](src)`.** Mapa renders it as an image **only when `src` is exactly `/i/<public id>`**, where the public id is `[0-9a-z]{1,13}`.
- **Alt text** is any text without `[`, `]` or a line break, at most 1,000 bytes of UTF-8. The editor's alt field refuses those characters and that length.
- **There is no title** (`"…"` after the address), and **no size suffix**.
- **Every other `![…](…)` renders exactly as it does today.**
  - Today `![x](/i/id)` is literal text, because `SafeURL` refuses a relative address. So no existing golden case changes meaning.
  - An external image is never fetched or hotlinked. That would hand a reader's address to a third party, and `img-src 'self'` refuses it anyway.
  - Paste and the importer turn external images into Mapa images or into links (§2.2, §7).
- **It is an inline span** (`markup.Image`) wherever links are parsed, and never inside code.
  - Like a link, it is part of its block.
  - **When a block's text is only one image**, perhaps with a `^id`, Go's `Render` marks that image with the class `alone`. The CSS draws it as a block. In the editor, the class comes from a node decoration that the settle plugin recomputes for each changed block, not from `toDOM`, so it is never an attribute. L4 compares the decorated DOM with Go's HTML.
- **The text index** reads alt text as body text. It does not read the address.
  - So search and snippets find alt text, and never `i` or an id.
  - **Unlinked mentions ignore alt text.** `linkFirstMention` edits only text spans, so it could never link one.
- **S3 and memoria** see an image as its alt text. No bytes and no image id reach a sibling.
- **History's word diff** treats the image span as one token, so it shows as changed when its id changes, even under the same alt text. It is drawn as `[image: alt]`.

**Rejected: `![[image:…]]`.**
- `![[app:item]]` is Mapa's embed grammar (base §7). Its rules would all have to learn that `image` is not an app. Those rules are the team container's check at write, render enforcement (gate 12) and S10 payloads.
- It has no standard place for alt text.
- It survives nowhere outside Mapa. `![alt](…)` is what Obsidian, GitHub and every Markdown tool read.
- The stored address is relative, so it never names a host. That matters because Paul's team URLs will move host (`paulca.mapa.oficina.works`).

### 2.2 Copy, paste and export

- **Copying within Mapa, with script:**
  - Copy and cut put `![alt](/i/id)` into `text/plain` and into the `application/x-mapa` slice (level-up §6.6).
  - **The slice also carries the public id of the page it came from.**
- **Paste into the same page** keeps the ids.
- **Paste into any other page,** or from a slice with no source page, works like this:
  - It calls `POST /images/copy` with every image id that the island does not resolve as attached here.
  - The reply holds `{id, width, height}` for each new pending image (§3.2), one for each id the person may read.
  - The editor rewrites those addresses in the pasted text before inserting it.
  - Any other id stays as it is and renders as unavailable. The reply leaves it out, exactly as it leaves out an id that does not exist.
  - The pasted blocks are new blocks with fresh origins, so fidelity (§2.3) is untouched.
- **Image files on the clipboard** are uploaded (§4.1). They come from screenshots, Finder or Photos.
- **HTML from outside:** an `<img>` with a remote `src` becomes a web link, `[alt](src)`. With no safe address it becomes nothing. Mapa never fetches it.
- **An address typed by hand** gets its state from `POST /links/resolve`, which now answers image ids too. It is scoped as rendering is (§3.1), so the editor reserves the right box.
- **The scriptless textarea keeps pasted text as typed.**
  - A copied `![alt](/i/id)` from another page renders as unavailable there (§3.1). The Markdown screen's help line says to use Upload instead.
  - This is a known limit of the floor, not a leak.
- **Export** (base decision 15) is not built yet. When it is:
  - each page's attached images go into `attachments/<public id>.<ext>`;
  - the page's addresses are rewritten to `attachments/…`, which Obsidian reads.

### 2.3 Fidelity gates L1–L4

- **New corpus cases:**
  - an image alone in a paragraph, in a list item, in a task item, in a quote and in a heading;
  - an image between words, two images on one line, and an image with `^id`;
  - an image inside emphasis, and inside a web link's label (`[![a](/i/x)](https://…)`);
  - an empty alt; alt with `*` and `` ` ``; alt at exactly 1,000 bytes, and at 1,001, made of multi-byte characters;
  - `![x](/i/)` and `![x](/i/UPPER)`;
  - `![x](https://…)`, `![x](/p/…)` and `![x](/i/id "title")`;
  - `![` with no close; `![[`; an image inside code.
  - Every case that is not an image keeps today's golden output.
- **L1 and L2:** an untouched image re-emits its `source`, byte for byte. Editing the alt text changes only that span.
- **L3:** seeded edits gain:
  - inserting, removing and moving an image atom;
  - editing its alt text;
  - pasting an image slice.
  
  The structure check and the reparse rule still hold.
- **L4:**
  - `markup.mjs` and Go agree on `Image` spans, byte offsets included.
  - The editor's decorated DOM (its `toDOM` output plus the `alone` node decoration, §2.1) equals Go's `Render`. Both read a fixed resolution table in the golden file: available with a width and height, or unavailable.
  - Width, height and state come from resolutions, never from the node's attributes, as chip state does (level-up §6.4, step 2). So an image's state never makes a block count as edited.

### 2.4 An image whose page becomes a team page

**A page never changes rung** (base decision 8), so no image does either. An image's rung is its page's rung.

**Make team page** (level-up §6.7) is the one way private writing reaches the team. It handles images in two steps.

**Before its transaction:**
- It parses the moved blocks.
- For each image there that is **attached to the source page**, it calls the same copy function as `/images/copy`. Each copy becomes a new pending image owned by the actor, with a new object under a fresh seal.
- Any other image id in the moved blocks is not copied. That covers an image attached elsewhere, and someone else's pending image typed in by hand. Those ids stay as typed and render as unavailable.

**Inside its write:**
- It re-checks the source revision, as today.
- It writes the new page's body with the new addresses.
- `tx.commit` then attaches the copies by its ordinary rule (§3.2).

If the write fails, the verb deletes its own copies at once (§3.2, item 3). No object is orphaned. No S3 call happens while SQLite's writer lock is held.

The private note's own images stay private. Its older revisions still reference them, and they age out with its history. This is decision 8 applied to bytes: nothing from the private era ever becomes team-readable in place.

---

## 3. Ownership and lifecycle

### 3.1 Who may read an image

One rule, through the store's scoped accessor (`readrule.go`'s `MayRead`, `around.go`):

- **An attached image** is readable by whoever may read its page, while that page is not deleted.
- **A pending image** (`page_id` null) is readable by its owner only, for as long as its row exists. *Amended in the build (round 3, M1):* the seven days are the sweep's alone. Reads applied them too, so a pending image a draft kept past seven days was kept, but its owner got a 404 and could not attach it.
- **Rendering on page P** resolves `/i/<id>` as available only when:
  - the image is attached to P, or
  - the image is pending and owned by the viewer. That is what a person sees in their own draft.
- **Everything else is drawn as the same fixed-size box: "Image not available".** That covers:
  - a missing id;
  - an image attached to another page;
  - someone else's pending image;
  - a removed image.
- So Bo's rendering of a team page is byte for byte the same whether or not an id in it names one of Ana's private images (gate IMG1).

### 3.2 How an image gets a place

1. **Upload creates a pending image** owned by the uploader and attached to nothing.
   - It logs `uploaded`, with object kind `image`.
   - It is a write by a person, so like any first write it creates their member row (build note 5).
   - Upload needs no page. It works the same for an unwritten day, a new scratch page and a team page.
2. **A commit of the person's own text attaches it.** `tx.commit` writes every revision. **Attaching is an explicit argument to it,** and only the verbs that carry the person's own text pass it:
   - create;
   - saving or committing a draft, `commit=1` included, and a daily note's or a scratch page's first commit;
   - Resolve;
   - Make team page;
   - `draftToScratch`;
   - the Notion importer's `ImportCreate` and `ImportUpdate` (the Notion import spec, §12). They carry the importing person's own staged content, so they attach (§7).

   **Every other verb passes "attach nothing":**
   - Revert (restore from history), which still clears `unreferenced_at`;
   - Restore of a deleted page, which still re-points (item 4);
   - the bulk verbs: "Update links", "Link it" and markers.

   With attaching on, `tx.commit` attaches each image that is all four of:
   - **introduced by this commit:** referenced by the new body, and by neither the page's current body nor the draft's base revision. For a new page, every reference is introduced. So a draft started on a revision that held a planted id cannot publish it after the planter takes it out;
   - pending;
   - owned by the person committing;
   - still a row (§3.3; amended, round 3, M1: no window of its own).

   Notes on the rule:
   - Nothing else is attached.
   - Suppose Bo types the id of Ana's pending image into a team page. Neither Ana's later commit of that page, nor her Revert to a revision that held Bo's text, nor her Restore of the page after Bo deletes it can publish the image. None of those introduced it from Ana's own text.
   - The commit's own event covers the attaching. The body is never rewritten: the bytes sent are the bytes stored.
3. **A copy** (`POST /images/copy`, a paste, Make team page, the deleted-page draft below) makes a new pending image, owned by the person copying, with a new object.
   - The source must be an image that person may read.
   - Each copy logs `uploaded`.
   - The object work happens before any transaction (§2.4).
   - **When the write that was to use a copy fails** (Make team page, `draftToScratch`), that verb deletes its own copies at once, as a removal (§3.3). One transaction deletes the rows, moves their keys to `image_trash` and logs `removed` with the person as actor. The objects are deleted after it, and from the queue if that fails. So a failure holds no quota for seven days and orphans no object.
4. **Restoring a deleted page** (base §3.4) creates a new page id. Its images are re-pointed to that page in the restore's transaction.
5. **A draft on a deleted page** becomes a new scratch page (base §5, `draftToScratch`). This is **the one named exception to item 3's read rule.** The images on a deleted page answer 404 to everyone, so `CopyImage` would refuse them. Before that write:
   - each image the draft references is copied for the person, **only when it is attached to the draft's own deleted page and the person passes that page's rule** (a team page, or a private page they own);
   - an image attached anywhere else is left as typed, and renders as unavailable;
   - the scratch body is written with the new addresses.

   The 90-day window does not cut this short: the sweep keeps an image a draft references (§3.3), so a draft never outlives its own pictures. The person's own text keeps its pictures, and the server writes that body itself.

### 3.3 Retention, removal and the sweep

**`unreferenced_at`:**
- `tx.commit` stamps it, **only where it is null,** on each of the page's images that the new body no longer references. A later edit never moves an existing stamp, so an image removed from the text reaches its 90 days however often the page is edited after.
- It clears the stamp when a body references the image again, as Revert does.
- It is plaintext (§1.3). It leaks a time only.

**An attached image is kept while any of these holds:**
- `unreferenced_at` is null: the current body references it;
- `unreferenced_at` is within the 90-day history window;
- its page is deleted but still restorable (90 days);
- a draft on its page references it.

So an image taken out of the text stays reachable from History and comes back with Restore, for as long as that text does.

**A pending image is kept for seven days after upload, or while a draft of its owner references it.** While it is kept, it is its owner's to read, draw, remove and attach (amended, round 3, M1).
- Seven days, not one, so an upload whose commit has not landed survives the wait. That covers an undo-redo a few days later, and a scriptless form left open.
- A pending image referenced only by an unsaved form or an undo stack older than that is gone. Help says so.

**The sweep is part of `Store.Sweep`, which runs when the app wakes.** It never runs on a GET and never on a timer. Its steps:
1. **Choose candidates with SQL alone:**
   - attached images stamped more than 90 days ago;
   - images of pages deleted more than 90 days ago;
   - pending images more than seven days old.
2. **Unseal only the drafts that could keep a candidate,** and drop those candidates:
   - drafts on the candidates' pages;
   - drafts of the owners of pending candidates.

   The common wake unseals nothing.
3. **Delete the remaining rows.** Their keys move to `image_trash` in the same transaction.
4. **Empty `image_trash` in a goroutine after boot.**
   - It deletes the bucket objects and removes each queue row whose delete succeeded.
   - It never returns an error to boot. A bucket outage delays deletion and nothing else.

**Retention stays exempt from gate 8 by name** (base §5, build note 27), for two reasons:
- It removes only what no person can still reach.
- An event would have to name Mapa as its actor, which base §2 forbids.

*The brief asked for sweeps as "writes with events". This spec keeps the existing exemption for those reasons, and Q7 puts it to Paul.*

**Removing an image now:**
- **Where it is offered:**
  - with script, "Remove from Mapa" in a selected image's bubble;
  - without script, the Markdown screen's **Images on this page** list. It names each image attached to the page by its alt text or "Image without a description", and the viewer's own pending images referenced in the text. It links to **Open** and **Remove**.
  - **Images already taken out of the text** are in that list too, as "Earlier image, taken out on <date>". A photo deleted from the text can still be removed from History. That list is shown with script on as well, under History.
  - When History shows an old revision rendered, each image drawn there links to the same confirm page. The word diff's `[image: alt]` tokens are text and link nowhere.
- **The confirm page** is `GET /i/{id}/remove`, and the action is `POST /i/{id}/remove`.
- **Who may remove:**
  - any member, for an image on a team page, as any member may delete a page;
  - the owner, for a private or pending image.
  - Anyone else gets the app's 404 from both, the same as for an id that does not exist (gate IMG1).
- **What it does, in one write:**
  - deletes the row;
  - queues the object;
  - logs `removed`, with object kind `image` and the actor.
- **After removal:**
  - Every reference to the image renders as unavailable, in History too. This is the path for a photo that should never have been uploaded.
  - The object is deleted straight after the transaction, and from the queue if that fails.
  - A browser may still hold its own copy for up to an hour (§1.4). That is the stated limit.

**Deleting a page removes nothing at once.**
- While the page is deleted, its images answer 404.
- They come back on Restore.
- They are swept 90 days after the delete.

**A removed member** (gate 9) keeps their private images, under gate 5's reading. Team images stay the team's.

### 3.4 Quota and limits

- **Per image:** 10 MiB, and at most 50 megapixels with neither side over 10,000 px (§5).
- **Two quotas.** Each counts only what its readers can see.
  - **A person's own allowance,** `MAPA_IMAGE_QUOTA_PERSON` (default 1 GiB), counts their pending images and the images on their private pages. Only they can see those.
  - **The team's allowance,** `MAPA_IMAGE_QUOTA_TEAM` (default 10 GiB), counts images attached to team pages. Every member can see all of those, so a total over them counts nothing hidden.
- **Checks happen at upload and copy, never at commit.** A commit is never refused for images.
  - Upload and copy are refused when the person is over their own allowance.
  - They are also refused when the team pages are over the team's.
  - Each refusal names its own figure. For the person: "You've used 1 GiB of images". For the team, the sentence below.
  - **Over the team's allowance, every upload is refused, private ones included,** because an upload does not know where it will go. The message says so: "Team pages hold 10 GiB of images, so Mapa takes no more uploads until some are removed."
  - **The team's allowance is a soft cap.** It is checked at upload, against images already on team pages. Pending images committed later can carry the total past it, by at most what the members hold pending.
- **The account's plan** (§1.1) bounds everything.
  - When CARLOS denies `PutObject`, upload answers: "Mapa's storage is full. Ask whoever runs your team's Oficina."
  - That refusal depends on the whole account's use, across apps, which the person cannot see. It is the platform's signal and cannot be avoided. It is recorded here as a residual.

---

## 4. The editor

### 4.1 Getting an image in

- **The ways in:**
  - paste image files;
  - drop image files, where the existing drop cursor marks the spot;
  - **Insert → Image…**;
  - `/` → **Image**;
  - the **image button** on the phone's accessory row (level-up §6.11, 7).
- **The last three open a file input** with `accept="image/png,image/jpeg,image/gif,image/webp"`. Given that list, iOS Safari hands over a HEIC photo as JPEG.
- **Several files** upload in order, each into its own place.
- **The client checks type and size first,** for a quick message. The server's check is the one that counts (§5).
- **Large JPEGs are scaled down first** (decision Q3).
  - With script, a JPEG over 4,096 px on its long side is decoded with `createImageBitmap(file, {imageOrientation: 'from-image', resizeWidth, resizeHeight, resizeQuality: 'high'})`. An `<img>` on a `blob:` URL would be refused by the CSP.
  - The bitmap is drawn to a canvas and sent as JPEG at quality 0.9. A canvas drops EXIF, so the orientation is applied while decoding and the result is upright with no tag.
  - The scaling happens **before** the 10 MiB check, so a large photo is checked at its scaled size.
  - If decoding fails, the original is sent as it is.
  - Colour is converted to sRGB. A Display P3 photo loses some saturation (Q3).
  - That is what makes a 48-megapixel phone photo usable, and readable on a phone.
  - Other formats, and every scriptless or importer upload, go as they are, within §5's limits.
  - A browser test sends a JPEG over 4,096 px with EXIF orientation 6. It must arrive at no more than 4,096 px and upright.
- **Upload** is `POST /images`, multipart with the field `file`, sent with `XMLHttpRequest` so progress events exist. The reply is `{id, src, width, height}`.

### 4.2 Progress and failure

- **The placeholder is a decoration, never a node** (Docs plan 7, D4).
  - A box at the mapped position shows the file name and a `<progress>`, at a fixed height.
  - There is no local preview. A `blob:` preview would need the page's CSP widened.
  - The document holds nothing while an upload runs, so autosave, the structure check, other tabs and teammates never see a dangling address.
- **The decoration maps through every transaction**, the rebuilds that a rebase or the inline choice makes included (level-up §6.5).
  - If its position is deleted, the finished image is placed at the end of the document. A notice says "Image added at the end of the page".
  - If an undo removed the decoration, the result is dropped, and the pending image is swept later.
- **On success,** the `image` atom is inserted at the decoration's position.
- **On failure,** the box says why: too large, not a supported image, SVG, storage full, offline, or not set up. It offers **Retry** and **Remove**.
- **Leaving with an upload in flight** gets the same "Leave anyway?" as unsaved text (level-up §6.5).

### 4.3 Alt text, sizing and captions

- **Alt text after an insert** (amended by build note I22: the field now lies over the image, not under it):
  - When the upload finishes and **the selection has not changed since it started**, a small field under the image takes focus: "Describe this image for people who can't see it". Enter keeps the text; Esc or Tab skips it.
  - Otherwise focus stays where the person is typing. The live region says "Image added", and the bubble's **Alt text** is there when the person selects the image.
- **A selected image's bubble** offers **Alt text**, **Replace…**, **Open full size** and **Remove from Mapa**.
- **Editing the alt text** changes the atom's `alt`, so the block counts as edited (§2.3).
- **Empty alt is allowed** and renders `alt=""`. Notion's images often have none.
- **Sizing:** natural size, never scaled up, capped at the column (`max-width: 100%; height: auto`). There is no resize handle and no stored width. §9 gives the trigger.
- **Captions:** none. Markdown has no caption, and the line after an image already reads as one. §9 gives the trigger.

### 4.4 The scriptless floor

The Markdown screen's form gains a file input and a second button, **Upload and insert**.

- **What the POST carries:** the textarea's text, the base revision and the file.
  - `MaxBytesReader` bounds the request at the text's own limit plus 10 MiB.
  - The file part alone is held to 10 MiB.
- **What the server does:**
  - It uploads the file as a pending image.
  - It shows the Markdown screen again: the submitted text, with `![<alt field>](/i/<id>)` added **at the end** on a line of its own, and the base unchanged.
  - Nothing is committed, and no draft is written.
- **Save** commits as before, and the commit attaches the image (§3.2).
- **This re-render is the one a refused save already does.** It works for every kind of page, an unwritten day and a new scratch page included.
- **Below the form,** "Images on this page" (§3.3) offers Open and Remove.

### 4.5 No shift: L5

- **The server draws** `<img src="/i/{id}" alt="…" width="W" height="H" loading="lazy" decoding="async">`, with W and H from the sealed record.
  - The browser reserves the box from the aspect ratio before a byte arrives.
  - An unavailable image is a box of fixed size.
- **The island** (level-up §6.8) gains image resolutions, scoped as rendering is (§3.1). So the editor's NodeView draws identical markup.
- **New images get their size** from the upload reply, the copy reply and `/links/resolve` (§2.2).
- **L5 gains a page with images:**
  - one above the fold, one below, one unavailable, and one in a draft;
  - every block's box is the same before and after mount, **and before and after the images load**;
  - no `layout-shift` entry is recorded.

### 4.6 Accessibility: L10

- **Naming:**
  - The image NodeView is named "Image: <alt>", or "Image with no description".
  - The alt field has its label.
  - The upload box is `role="group"`, named "Uploading <file>". Its `<progress>` is labelled.
- **A selected image** shows the focus ring.
- **A polite live region** announces "Image added" or the failure.
- **Insert → Image is the keyboard path.** Drag and drop is never the only way in.
- **L10 gains:**
  - a keyboard-only walk of Insert → Image with the file picker stubbed, then the alt field, the bubble's Alt text, and Remove's confirm;
  - an upload finishing while the person types elsewhere: focus does not move, and the live region speaks;
  - axe-core finds nothing serious on a page with images.

---

## 5. Formats and safety

- **Allowed:** PNG, JPEG, GIF and WebP, animated GIF and WebP included.
- **The type is decided from the bytes** (magic numbers, as Slides' `sniffImage` does). The claimed `Content-Type` and the file name are ignored.
- **The format's own decoder then reads the header** (`image.DecodeConfig`). That is the standard library, plus `golang.org/x/image/webp`, a new dependency added to the Colophon. It must agree on the type, and give dimensions inside the limits.
- **Refused:**
  - **SVG.** It is a document that can carry script, served from Mapa's own origin. Docs refused it for this reason. Slides sanitises it, and that would be a second parser to keep safe (Q1).
  - HEIC, AVIF, TIFF, BMP, PDF, and everything else.
  - Each refusal is a 415 with a sentence naming the four formats Mapa takes.
- **Metadata is stripped without re-encoding.**
  - The work is done by a container walker in pure Go. `CGO_ENABLED=0` means there is no WebP encoder, and re-encoding a JPEG loses quality.
  - **The walker drops named kinds of metadata and keeps the image's own structure**, so a segment it does not list is never lost when the picture needs it.
- **JPEG:**
  - **Dropped:**
    - every APPn segment except three: APP0 that starts `JFIF\0`, APP2 that starts `ICC_PROFILE\0`, and APP14 that starts `Adobe`;
    - every COM segment.
  - **Kept:** every other marker segment. That covers every SOFn, DQT, DHT, DRI, DNL, DAC and SOS, with the scan data and its RSTn markers.
  - **In the kept APP0,** the JFIF thumbnail is removed (width and height set to 0, data dropped). JFXX APP0 segments go.
  - **Orientation is kept.** When EXIF gave anything but 1, Mapa writes a minimal APP1 holding only the Orientation tag, so phone photos stay upright. The stored width and height are those after rotation.
  - **The file ends at EOI.** That drops Motion Photo video, MPF second images, gain maps and vendor trailers.
- **PNG:**
  - **Kept:**
    - the critical chunks;
    - `iCCP`, `sRGB`, `gAMA`, `cHRM`, `cICP`, `mDCV`, `cLLI`, `sBIT`, `pHYs`, `tRNS` and `bKGD`;
    - the APNG chunks (`acTL`, `fcTL`, `fdAT`).
  - **Dropped:** `eXIf`, `tEXt`, `zTXt`, `iTXt`, `tIME` and every unknown ancillary chunk.
  - **The file ends at IEND.**
- **WebP:**
  - **Kept:** `VP8 `, `VP8L`, `VP8X`, `ALPH`, `ANIM`, `ANMF` and `ICCP`.
  - **Dropped:** `EXIF`, `XMP ` and unknown chunks. VP8X's flags and RIFF's size are rewritten to match.
  - **The file ends at the RIFF length.**
- **GIF:**
  - **Kept:** the image data, the graphic control extensions, and the `NETSCAPE2.0` loop extension.
  - **Dropped:** comments, plain-text extensions and every other application extension. XMP rides in one.
  - **The file ends at the trailer.**
- **ICC profiles are kept** because colour needs them. A profile can name a monitor or the person who calibrated it. That is the one piece of descriptive metadata left, and Help says so.
- **Anything the walker cannot parse is refused,** never passed through. So location, camera serials, author names, edit history, thumbnails and hidden trailers never reach the bucket.
- **Limits:**
  - The upload body is bounded with `http.MaxBytesReader` before anything is parsed.
  - From `DecodeConfig`, before any further work:
    - at most 10,000 px on a side;
    - at most 50 megapixels in all (§4.1 scales large photos down when script is on).
  - Mapa never decodes pixels, so a decompression bomb costs it nothing.
  - A reader's browser still decodes whatever is shown. 50 MP is about 200 MB there, and that is why script scales photos down.
- **Served safely** (§1.4):
  - The headers are the stored type, `nosniff`, and `default-src 'none'; sandbox`.
  - An image opened on its own is still an image on Mapa's origin, and can run nothing.
  - Nothing follows the image's end, so no trailing document is served.
  - The page CSP does not change (`img-src 'self' data:`).
- **Scanning cannot read sealed objects,** and Mapa never asks for it (Q5). The allowlist, the strict walker and sandboxed serving are Mapa's own defence.

---

## 6. Server changes

| Change | Gate |
|---|---|
| **Migration `0005_images`:** `images` and `image_trash` (§1.3). <br>Unique `public_id`. Indexes on `(page_id, unreferenced_at)` and `(owner, page_id)` | the migration check <br>**gate 4**: `plaintext_test.go` names the new columns exactly, and IMG2 |
| **`seal` purposes `image` and `image-record`;** the 64 KiB padding | **gate 4**, IMG2 |
| **`images.go`:** sniffing, the walker, the limits, the seal, `Put`, the row and the event. One function serves the route and the importer (§7), and another serves copies. <br>Object work runs before any transaction. If a transaction fails after a `Put`, the object is deleted | IMG5, IMG6, IMG7 |
| **The blob semaphore** (§1.4) | IMG6 |
| **`POST /images`:** the upload. JSON with script; the Markdown screen re-rendered without it (§4.4) | IMG3, IMG6, L8 |
| **`GET /i/{id}`:** scoped serving, 304, headers (§1.4) | **gate 1**, IMG1, **gate 10**/L7, IMG6 |
| **`POST /images/copy`:** `{ids}` → `{id: {id, width, height}}`, only for ids the person may read | **gate 1**, IMG1, **gate 8** |
| **`POST /links/resolve`** answers image ids, scoped | IMG1, L6 |
| **`GET` and `POST /i/{id}/remove`:** the confirm page and removal. The Markdown screen's Images on this page list | **gate 8**, IMG1, IMG7, L8 |
| **`tx.commit`** attaches the committer's own pending images that the commit introduces, and stamps and clears `unreferenced_at` (§3.2, §3.3) | IMG7 <br>Two mutants: attaching without the owner check; attaching ids that were not introduced |
| **`MakeTeamPage` copies, then writes. `Restore` re-points. `draftToScratch` copies** | IMG7, L9 <br>A mutant: Make team page copying an image that is not attached to its source |
| **`Store.Sweep`** sweeps images. `image_trash` is emptied off the boot path (§3.3) | IMG7, gate 8's named exemption |
| **`markup.Image`, `Render` with its `alone` class, the editor's `alone` decoration, and the resolver.** The text index skips the address; mentions skip alt text | L1–L4, IMG1 |
| **Event vocabulary:** object kind `image`, verbs `uploaded` and `removed`. Every event reader already filters on `object_kind = page` (index, recent, versions, verbs) | **gate 8** |
| **`config.go`:** `CARLOS_STORE_*` through `blobs.S3FromEnv`. A partial store boots with uploads at 503 and logs loudly (decision 4). Also `MAPA_IMAGE_QUOTA_PERSON` and `MAPA_IMAGE_QUOTA_TEAM` | `config_test.go` |

**New gates.** They run in `make ci` unless marked "browser".

- **IMG1, scope.** This extends gate 1 and L6.
  - **The setup:** Ana has:
    - a private page with images;
    - a pending upload;
    - a private image whose id is typed into a team page.
  - **What must not change:** Bo's output is byte-identical with or without each of those, across:
    - the team page's HTML and its island;
    - `/links/resolve`;
    - `GET /i/<Ana's id>` and `GET /i/<Ana's id>/remove`, which give the same status, headers and body as an id that never existed;
    - `POST /images/copy`.
  - **Bo has typed Ana's pending id into a team page.** Each of these leaves the image unattached:
    - Ana's own commit of that page;
    - Ana's Revert to the revision that held Bo's text, after Bo removed it;
    - Ana's Restore of the page, after Bo deleted it;
    - Ana's save or Resolve of a draft she started on the revision that held Bo's text, after Bo removed it.
  - **Mutants** (`make mutate`), each of which must be caught:
    - one drops the route's scope check;
    - one resolves images attached to other pages;
    - one makes attach ignore "introduced";
    - one makes Revert or Restore pass "attach".
- **IMG2, the plaintext file scan.** This extends gate 4.
  - **The setup:** a PNG and a JPEG are uploaded with canary strings:
    - in `tEXt`, EXIF, XMP and a JPEG trailer after EOI;
    - in the file name;
    - in the alt text.
  - **What must hold:**
    - The database file holds no canary and no alt text, WAL included.
    - The blob directory holds no canary and no alt text.
    - No blob starts with a PNG or JPEG magic number. Only offset 0 is checked, because ciphertext matches by chance elsewhere.
    - The fake S3 records `Content-Type: application/octet-stream`.
    - Every stored size is a multiple of 64 KiB plus the seal's constant.
- **IMG3, events.** This extends gate 8.
  - Upload, copy and removal each log their event.
  - The sweep is the named exemption.
  - A mutant that drops the upload's event must be caught.
- **IMG4, nothing written by a GET.** This extends gate 10 and L7. The row-dump hash stays unchanged across:
  - `GET /i/{id}`, both 200 and 304;
  - page views with images;
  - the island;
  - the remove confirm page.
- **IMG5, stripping.** For each format:
  - The canary metadata, GPS and trailers are gone from what is served.
  - ICC and the JPEG orientation stay.
  - **The pixels are unchanged.** The test decodes before and after; Mapa itself never decodes.
  - JPEG fixtures cover baseline, progressive, **restart intervals (DRI)**, CMYK with Adobe APP14, a JFIF thumbnail, and Motion Photo.
  - Truncated, oversized and malformed chunks are refused.
  - A Go fuzz target on each walker runs its seed corpus in CI.
- **IMG6, refusals, headers and memory.**
  - **Each of these is refused:**
    - a claimed type that is not true;
    - SVG, HEIC and HTML;
    - a file over 10 MiB;
    - an image over 10,000 px on a side or over 50 MP;
    - an upload over either quota;
    - an upload with no store (503);
    - an upload or copy that has waited 10 s for the blob semaphore, and a `GET /i/{id}` that has waited 30 s. Each answers 503 with `Retry-After`.
  - Every served image carries §1.4's headers.
- **IMG7, lifecycle.**
  - **Attaching:** a commit attaches only the committer's own pending images that it introduces. Bulk verbs attach nothing.
  - **Copying:** only images the person can read are copied.
  - **`draftToScratch`** copies only images attached to the draft's own deleted page, under that page's rule. A mutant that copies an image attached to another page must be caught.
  - **A failed Make team page or `draftToScratch` write** deletes its own copies at once. It logs `removed` and queues the keys in `image_trash`.
  - **Make team page:**
    - copies only images attached to its source;
    - makes no S3 call inside its transaction.
  - **Restore** re-points. A deleted page's draft brings copies into its scratch page.
  - **`unreferenced_at`** is stamped on removal from the text and cleared on Revert.
  - **Removal** makes the image unavailable everywhere, History included.
  - **The sweep:**
    - keeps an image that a draft or a revision in the window references;
    - removes a pending image after seven days, and a deleted page's images after 90;
    - unseals nothing when no candidate exists;
    - sweeps an image taken out of the text after 90 days, even when the page has had commits through all 91 of them (the stamp is never moved);
    - never fails boot when the bucket is down.
  - **Failures:** a failed object delete stays queued. A failed transaction after `Put` deletes the object.
- **The page gates extend:**
  - **L5:** §4.5's page.
  - **L8:** Upload and insert, the Images on this page list, and Remove's confirm, all with script off.
  - **L9:** an upload in flight across autosave, commit, rebase, the inline choice, and leaving.
  - **L10:** §4.6.
  - **L12:** the bundle's size is logged.

---

## 7. The importer hook

The Notion importer calls the store, never the HTTP route, through the same functions the routes use:

```go
// AddImage reads one image, checks and strips it (§5), seals it, stores
// it, and records it as a pending image owned by actor, logging
// "uploaded" by actor (never Mapa). It waits for the blob semaphore
// (§1.4) rather than failing.
func (store *Store) AddImage(ctx context.Context, actor int64,
	data io.Reader) (Image, error)

// CopyImage makes a new pending image owned by actor from one actor may
// read, with a new object. It is the function /images/copy and Make
// team page use.
func (store *Store) CopyImage(ctx context.Context, actor int64,
	publicID string) (Image, error)

// Markdown is "![alt](/i/<public id>)", with alt cleaned to §2.1's form:
// [, ] and line breaks removed, and at most 1,000 bytes, cut at a rune.
func (image Image) Markdown(alt string) string
```

**How the importer uses them:**
- **Commit as it goes.** Pending images count against the importing person's own allowance until a commit attaches them. So the importer commits each page before it adds the next page's images. Otherwise a large workspace would stop at the person's 1 GiB, however much of it was bound for team pages.
- **One image per place.**
  - An `Image` attaches to the first page whose commit introduces it.
  - When a Notion file appears on two pages, the importer calls `AddImage` once and `CopyImage` for each further page.
  - It puts `image.Markdown(caption or alt)` in each body, then writes each page through the importer's own store methods, `ImportCreate` and `ImportUpdate` (the Notion import spec, `design/notion-import`, §12), as that person. Both reach `tx.commit` with attaching on, so the write attaches the images (§3.2).
- **Quota.** Images imported into team pages count against the team's allowance (`MAPA_IMAGE_QUOTA_TEAM`, default 10 GiB). Images in private pages count against the importing person's allowance.
  - Both are checked at `AddImage` and `CopyImage`.
  - The importer spec should check the export's total against them before it starts, and say so to the person.
- **Typed refusals** tell the importer what to write in place of an image: `ErrImageType`, `ErrImageTooLarge`, `ErrImageDimensions`, `ErrImageQuota` and `ErrNoImageStore`.
  - A refused image becomes a text line: `(Image not imported: <file name>, <reason>)`. Nothing vanishes silently.
- **Notion's remote images** (an `https://` source that is not in the export) are not fetched by `AddImage`. Whether the importer fetches them is that spec's call. If it does, it passes the bytes in here.
- **A failed import** leaves pending images, which are swept after seven days (§3.3). The importer needs no cleanup of its own.

---

## 8. CARLOS setup for the live instance

The live instance is the lone app `mapa`, on account `oficina` (`bds`), at mapa.oficina.works. On 2026-11-17, `carlos store status --app mapa --account oficina` answered "no store is declared for this app".

Paul runs these steps, or the agent runs them with his say-so, **after** the build is merged and deployed. Until then, upload answers 503 (decision 4).

1. **Read the account's plan directly.** Use the console's Billing page for `oficina`.
   - **Stop if the plan has object storage "scanned for viruses"** (`storage_scan_required`). On that plan, `store create` would force scanning onto ciphertext (§1.1).
   - Move the account to a plan that does not force scanning, or make it a house account (Q5).
   - Slides' store is not evidence either way: it was granted before the 2026-11-15 catalog.
2. **Declare the store.** On an approved account, this also provisions it:
   ```sh
   carlos store create --app mapa --account oficina
   ```
3. **If step 2 left the store declared but not provisioned,** an operator (Paul) grants it:
   ```sh
   carlos store grant --app mapa --account oficina
   ```
4. **Check that scanning is off:**
   ```sh
   carlos store scan status --app mapa --account oficina
   ```
   It should say "not requested". If scanning is on, stop and bring it to Paul. Do not upload anything until it is off: `carlos store scan revoke --app mapa --account oficina` is an operator verb.
5. **Check what was delivered:**
   ```sh
   carlos store status --app mapa --account oficina
   ```
   - It should name a bucket, presumably `carlos-store-bds-mapa`.
   - It should list `delivers: CARLOS_STORE_BUCKET, CARLOS_STORE_REGION, CARLOS_STORE_ACCESS_KEY, CARLOS_STORE_SECRET_KEY`.
   - Nothing should still be waiting to reach the app's config.
6. **Restart, so the process reads its new config, then check:**
   ```sh
   carlos restart --app mapa --account oficina
   curl -s https://mapa.oficina.works/api/version
   carlos logs --app mapa --account oficina
   ```
   The log says "mapa: object store bound". Upload one image and open it.
   **Do this before trusting the store** (round 4, N6). Mapa's Put is its own, over a URL `blobs.S3` presigns with query signing (`images_bucket.go`). It has run only against a fake S3. One real upload, opened, shows that CARLOS's bucket takes it. If that upload fails, read `carlos logs`. A 403 there is not proof that storage is full: on a new store, it is far more likely the signing or the IAM policy. Mapa says "storage is full" only for a 403 on the Put, so a misconfigured store would read as full until this check.
7. **Never request scanning.** If anyone ever does, the honest attestation is `carlos store scan request --app mapa --client-encrypted`. It claims no coverage.
8. **No CORS rule is needed.** No browser ever talks to the bucket.
9. **Later, for team instances through Alta:**
   - Paul runs `carlos instances enable --app mapa --private-storage`.
   - Alta's `provision/apps.go` gains Mapa with `Store: true`, as Slides has (Alta `916aac3`).
   - A plan that forces scanning refuses per-instance stores outright.

---

## 9. Deliberately not built

| Thing | Trigger |
|---|---|
| Display copies made on the server (thumbnails, `srcset`) | Pages with photos feel slow on a phone even after §4.1's scaling |
| A width per image | People ask for a smaller picture beside text |
| Captions | People write captions under images and want them tied to the image |
| SVG, behind Slides' sanitiser | Paul rules yes on Q1 |
| AVIF and HEIC | A browser hands Mapa one. iOS converts HEIC today |
| Presigned direct reads | Never, while images are sealed |
| Streaming, chunked sealing | §1.4's semaphore makes pages wait in real use |
| A bucket reconcile: list the bucket, delete unknown keys | `image_trash` misses something. Today only a crash between `Put` and the transaction's cleanup can leave an orphan object |

## 10. Open questions for Paul

1. **SVG: refused or sanitised?** *Recommended: refused.* An SVG is a script-capable document on Mapa's own origin. Slides' sanitiser exists, but it would be a second copy to keep safe. Notion pages rarely hold SVG.
2. **Quotas.** *Recommended: 1 GiB per person, for pending images and images on private pages; 10 GiB for the team, for images on team pages; and 10 MiB per image.* A single team-wide total over everything would leak a count of private images.
3. **Captions, sizing and scaling.** *Recommended:* no captions and no resizing in v1. With script, JPEGs over 4,096 px on the long side are scaled down before upload (§4.1). So a 48 MP photo becomes about 12 MP, upright and in sRGB. The original is not kept, and a Display P3 photo loses some saturation.
4. **External image Markdown** (`![x](https://…)`). *Recommended: render as today,* a `!` and a link. It is never fetched.
5. **The oficina account's plan.** *Recommended:* keep it on a plan that does not force scanning, because a sealed store cannot be scanned. Turn on `--private-storage` for Mapa when it joins Alta.
6. **Who may remove an image on a team page.** *Recommended: any member,* as with deleting a page, with a confirm page and an event that names them.
7. **The sweep's events.** *Recommended: keep retention exempt from gate 8 by name,* as it is today. A person's removal logs an event. An event for the sweep would have to name Mapa as the actor.

---

## 11. Findings and what changed

### Round 1: Fable on revision 1 (`4d40e4e`), CHANGES REQUIRED, answered in revision 2

| Finding | Change | Where |
|---|---|---|
| **H1** Make team page copied every image the moved blocks named, with no scope, and did S3 work inside its SQLite write | Copies only images attached to the source page. Copies are made before the transaction, as pending images owned by the actor, through `CopyImage`. `tx.commit` attaches them. A failed write leaves pending copies for the sweep. A mutant was added | §2.4, §3.2, §6, IMG7 |
| **H2** The JPEG keep-list omitted DRI, corrupting photos with restart intervals for good | The rule is inverted: drop named APPn and COM, keep every other marker. DRI, progressive and CMYK fixtures were added | §5, IMG5 |
| **M1** Attach at commit was a confused deputy: a typed pending id was published by its owner's next commit, bulk verbs included | Attach only ids the commit introduces. Bulk verbs attach nothing. Added to IMG1, IMG7 and a mutant | §3.2, §6 |
| **M2** Exact `stored_bytes` showed the same picture across rungs, undoing decision 3 | Plaintext is padded to 64 KiB before sealing. The gate-4 row says what remains | §1.2 decision 1, §1.3, IMG2 |
| **M3** Trailing data and JFIF thumbnails survived | Each format is cut at its end. JFIF APP0 is kept with no thumbnail, and JFXX goes. ICC kept and stated. A trailer canary was added | §5, IMG2, IMG5 |
| **M4** The sweep would unseal every revision at boot, and bucket deletes could block boot | `unreferenced_at` is stamped by `tx.commit`. Candidates are chosen by SQL, and only the drafts that could keep a candidate are unsealed. The trash is emptied off the boot path | §1.3, §3.3, IMG7 |
| **M5** The memory bound covered uploads only | One semaphore over every blob operation. Waiters queue. The figure is measured on the real instance | §1.4, IMG6 |
| **M6** A per-person quota blocked the importer, and gate 1 does not need it for team images | Two quotas: a person's (pending and private images) and the team's (team-page images) | §3.4, §7, Q2 |
| **M7** The hook had no copy function and was silent on reuse and waiting | `CopyImage` exported. One `AddImage` per file, copies for each further place. `AddImage` waits on the semaphore | §7 |
| **M8** The alt field took focus whenever an upload finished | Focus moves only if the selection is unchanged. Otherwise the live region speaks. Added to L10 | §4.3, §4.6 |
| **M9** Slides' store was no evidence about the plan, and a scan-required plan forces scanning onto the store | Step 1 reads the plan directly. A `scan status` check comes after create. §1.1 corrected | §1.1, §8 |
| **L1** `display: block` for a lone image cannot be done in CSS | Go and `toDOM` emit the class `alone`, pinned in L4 | §2.1, §2.3 |
| **L2** Alt text in unlinked mentions could never be linked | Mentions skip alt text; search keeps it | §2.1 |
| **L3** "No JPEG magic anywhere" would flake on ciphertext | Only offset 0 is checked, plus the canaries | IMG2 |
| **L4** No scriptless way to reach Remove; its 404 was ungated | The Markdown screen gains "Images on this page" with Open and Remove. Both remove routes are in IMG1 | §3.3, §4.4, IMG1 |
| **L5** The clipboard slice had no source page | The slice carries the source page. Any id not attached here is copied | §2.2 |
| **L6** Copied and typed images had no size, so the page shifted | The copy reply carries width and height. `/links/resolve` answers image ids | §2.2, §4.5, §6 |
| **L7** No rule for a placeholder across a rebuild | The decoration maps through every transaction. A lost position puts the image at the end, with a notice | §4.2, L9 |
| **L8** A deleted page's draft became a scratch page with unavailable images | `draftToScratch` copies them and writes the new addresses | §3.2, IMG7 |
| **L9** A one-day pending window lost images in open forms and undo | The window is seven days, applied by reads before the sweep, and stated | §3.1, §3.3 |
| **L10** `MaxBytesReader` covered the textarea too; where the line goes was unsaid | The bound is the text plus 10 MiB, with the file part held to 10 MiB. The line goes at the end | §4.4 |
| **L11** 40 MP refused 48 MP phone photos, and huge images cost readers' browsers | The cap is 50 MP. With script, JPEGs are scaled to 4,096 px on the long side (Q3) | §4.1, §5 |
| **L12** HDR colour chunks were dropped | `cICP`, `mDCV` and `cLLI` are kept | §5 |
| **L13** A partial store refused boot | It boots with uploads at 503 and a loud log | decision 4, §6 |
| **L14** Decision and gate ids collided | The gates are IMG1–IMG7 | throughout |
| **L15** Corpus gaps | Added: image in a heading and a task item, inside emphasis and a link label, and alt at the byte limit in multi-byte characters | §2.3 |
| **L16** History hid an image replaced under the same alt | The diff treats the span as one token, id included | §2.1 |

### Round 2: Fable on revision 2 (`c27a292`), CHANGES REQUIRED, answered in revision 3

There were no high findings. Fable said that once M1–M5 were applied as proposed, no further full round was needed, only a check of the diff.

| Finding | Change | Where |
|---|---|---|
| **M1** "Introduced by this commit" still published a planted id. Bo plants Ana's pending id, then removes it; Ana reverts. Or Bo plants it and deletes the page; Ana restores | Attaching is an explicit `tx.commit` argument. Only the verbs that carry the person's own text pass it (create, draft commits, Resolve, Make team page, `draftToScratch`). Revert, Restore and bulk verbs attach nothing. Both cases are in IMG1, with a mutant | §3.2, IMG1 |
| **M2** `draftToScratch` copied images that nobody may read | Named as the one exception. It copies only images attached to the draft's own page, under that page's rule. The 90-day window does not apply, because a draft keeps its images. A mutant was added | §3.2, IMG7 |
| **M3** Every edit re-stamped `unreferenced_at`, so nothing ever reached 90 days | Stamped only where null. The IMG7 case has 91 days of commits | §3.3, IMG7 |
| **M4** A photo deleted from the text could not be removed from History | "Images on this page" lists earlier images, "taken out on <date>", with Remove. History's images link to the confirm page | §3.3 |
| **M5** Pending images capped the importer at 1 GiB, and failed copies held quota for seven days | The importer commits page by page. Failed writes delete their own copies. The team allowance is stated as a soft cap | §3.2, §3.4, §7 |
| **L1** Downscale mechanism, orientation, order and colour | `createImageBitmap` with `imageOrientation`. Scaled before the size check. The original is sent if decoding fails. sRGB is in Q3. A browser test was added | §4.1, Q3 |
| **L2** The `alone` class had no editor mechanism | A node decoration. L4 compares the decorated DOM | §2.1 |
| **L3** §8's order | create, grant if needed, scan status, then store status | §8 |
| **L4** "It never shows" overstated | "It does not by itself show" | §1.3 |
| **L5** Attaching a pending image past its window | Attach needs the row still inside its seven days | §3.2 |
| **L6** A 10 s wait made a broken image | Serving waits 30 s, and the NodeView retries once | §1.4 |
| **L7** Over the team allowance, private uploads were refused without saying why | The message says so | §3.4 |

**Fable's diff check of revision 3 (`a2392bd`).** No high. Fable said the answers needed no further review round.

| Finding | Change | Where |
|---|---|---|
| **M1** §2.4 and IMG7 still said a failed write leaves pending copies, which contradicted M5 | Both now say the verb deletes its copies at once | §2.4, IMG7 |
| **M2** The cleanup of failed copies logged no event and could orphan an object | It is a removal: one transaction deletes the rows, queues the keys in `image_trash` and logs `removed` with the person as actor | §3.2, IMG7 |
| **L3** L4 still said `toDOM` draws `alone` | "The editor's decorated DOM", in §6's row too | §2.3, §6 |
| **L4** IMG6 kept the single 10 s limit | 10 s for uploads and copies, 30 s for serving | IMG6 |
| **L5** Two messages for the team refusal | One | §3.4 |
| **L6** "History's drawn images" was ambiguous | Images in a rendered old revision link to the confirm page. Diff tokens link nowhere | §3.3 |
| **L7** A draft based on a revision holding a planted id could publish it after the planter removed it | "Introduced" also excludes the draft's base revision. The case is in IMG1 | §3.2, IMG1 |

---

### Round 3: Fable on the build (`49d8df3`), CHANGES REQUIRED, answered on `feat/images`

Each high and medium has a gate that is red without its fix. Each was run red, then green.

| Finding | Change | Gate |
|---|---|---|
| **H1** `ParseMultipartForm(1<<20)` spilled any part over 1 MiB to `$TMPDIR/multipart-*`. chi hands the handler a copy of the request, so net/http's cleanup never ran: the picture as sent, metadata and all, stayed on disk | Parts are read with `MultipartReader` under `MaxBytesReader`, into memory, by `POST /images` and the scriptless path alike (`handlers_upload_read.go`) | `TestAnUploadSpillsNothingToDisk`: a 1.5 MiB PNG with a canary, both paths, a real server, `$TMPDIR` scanned. Red: two `multipart-*` files holding the canary |
| **M1** A pending image a draft kept past seven days answered 404 to its owner, and could not be attached | The pending window is the sweep's alone. Reads, drawing, removal, the list and attaching take a pending row of the owner's for as long as it exists. §3.1–§3.3 amended | `TestAPendingImageADraftKeepsStaysItsOwners` |
| **M2** The limits read only GIF's logical screen. A 35-byte GIF declared 1×1 carried a 60,000×60,000 frame | A frame extending past the logical screen is refused | `TestAGIFFrameStaysInsideItsScreen`, and a mutant |
| **M3** A paste with text or HTML and a picture (spreadsheet cells) kept only the picture | Files upload only from a clipboard with no text and no HTML (`pastedFiles`) | `upload.test.mjs` |
| **M4** Replace… deleted the old image before the new one arrived: a failed replace left none, and autosave could save that. It could drop the alt | `replaceImage` uploads beside the old image, which stays. On success the node takes the new id and keeps its alt | `upload.test.mjs` |
| **M5** One Backspace before an uploading box counted as "place deleted" and sent the image to the end. Undoing text typed just before the box dropped the upload silently | Only a box whose own place was deleted, with both sides gone (`deletedAcross`), is lost; edits beside it move it | `upload.test.mjs` (both cases), and L9 (L14) |
| **M6** Several files landed in reverse order | Each file goes after the image before it | `upload.test.mjs` |
| **M7** L5 could not fail: on loopback the pictures loaded before the first measurement | The test holds every image's bytes, measures, then lets them come | `TestL5ImagesReserveTheirBoxes`, red with width and height removed from `markup/images.go` and `imagedom.mjs` |
| **L1** Help did not say the three things §1.4, §3.3 and §5 promise | Help → Markdown in Mapa has an Images section: an hour of the browser's own copy, seven days unless a draft names it, and the colour profile kept | `TestHelpSaysWhatImagesKeep` |
| **L2** A failed `/images/copy` left its earlier copies; a repeated id was copied twice | Each id once; a refusal removes the copies made before it | `TestACopyIsAllOrNothingAndOncePerID` |
| **L3** A paste whose copy failed pasted the foreign ids silently | It pastes nothing and says why, the server's sentence (507, 503) when there is one | `serialize.test.mjs` |
| **L4** Restore moved images to the new page id, so `draftToScratch` on a draft left on the deleted page copied nothing | `images.moved_from`; `draftToScratch` copies an image attached to its page or moved from it. §1.3 gains the column | `TestAnOldDraftFollowsItsImagesThroughARestore` |
| **L5** A scriptless upload over about 20 MiB lost the typed text | The text fields are read before the file (the alt field now comes first too). A refused file keeps them and says why | `TestL8AnOversizedUploadKeepsTheText` |
| **L6** `uploadOnEdit` stored the file before checking the page | The page is checked first | `TestL8UploadAndInsertNeedsThePage` |
| **L7** `backTo` let `/<tab>/evil.example` through | `safeReturn`'s rule | `TestRemovesWayBackStaysInMapa` |
| **L8** "Storage is full" was inferred from "403" anywhere in an error's text | Mapa does its own Put over a presigned URL, and reads the status. IMG2 now binds its fake S3 through `LoadConfig` | `TestStorageIsFullOnlyWhenThePutIsRefused` |
| **L9** The WebP walker used two buffers | One | IMG5 |
| **L10** Data after Adobe APP14's header, extra NETSCAPE2.0 sub-blocks, and unknown chunks inside WebP ANMF survived | Each is dropped: APP14 keeps 12 bytes, the loop extension keeps its count, a frame keeps its header and picture chunks | `review_test.go`: three canary cases |
| **L11** Only a JPEG keeps its orientation | Accepted, as §5 says: PNG `eXIf` and WebP `EXIF` are dropped whole, orientation included | build note I17 |
| **L12** A failed upload an undo took away stalled the queue | Its Retry/Remove wait ends when the undo drops it | `upload.test.mjs` |
| **L13** IMG1 did not compare History's rendered revisions or the conflict view | Both compared, and checked to draw images | `TestIMG1ImagesLeakNothing` |
| **L14** L9's upload test passed without position mapping | Text is typed before the box while it uploads | `TestL9AnUploadInFlightCrossesSavingAndLeaving`, red with the mapping removed |
| Resource: the semaphore's figure is unmeasured | `BlobSlots` is 2 until it is measured on the instance | I14 |

### Round 4: Fable on round 3's answers (`4c95863`), CHANGES REQUIRED, answered on `feat/images`

H1 and every round-3 item were resolved except M3, which N1 reopens. "A narrow check of those two is enough next time."

| Finding | Change | Gate |
|---|---|---|
| **N1** (M) M3's fix stopped a browser's Copy image from uploading. Chrome sends the picture with HTML that is one `<img>`; Firefox adds the address as text. The paste became a link | The picture wins when the HTML is one `<img>` and nothing else (any text then ignored), or with no HTML and no text, or with no HTML and text that is only a web address. Otherwise text wins (`pastedFiles`, `loneImage`) | `upload.test.mjs`: Chrome's and Firefox's shapes upload; cells, plain text, and an `<img>` inside other HTML do not. The `<img>` case was red |
| **N2** (M) `refusal`'s 10 MB check ran before a JPEG was scaled, so a 48 MP photo was refused in the browser | No size check before scaling for a JPEG; the check after `prepared` stands | `upload.test.mjs`, red first |
| **N3** (L) Every other route's `PostFormValue` would spill a multipart file part over 32 MiB to `$TMPDIR`, the sign-in door's included | Router-level `bounded`: multipart is refused (415) everywhere but an upload route, and every other body is capped at the form's bound | `TestOnlyUploadRoutesTakeMultipart`: four routes, `$TMPDIR` scanned. Red: 200 and 422 |
| **N4** (L) M1's gate covered reading and attaching only | It also checks the draft draws the image, the list names it, and its owner may remove it | `TestAPendingImageADraftKeepsStaysItsOwners`, red with each of the three checks broken |
| **N5** (L) A Put failing on the wire logged its presigned URL (`*url.Error`), valid for five minutes | The URL is unwrapped away; `presignFor` is 60 s | `TestAFailedPutNamesNoSignedAddress`, red first |
| **N6** (L) The query-signed Put has run only against a fake S3 | §8 step 6: one real upload before trusting the store, and why a 403 there is likely signing, not a full plan | §8 |
| **N7** (L) Reading uploads into memory was unbounded in number, and the bytes were copied twice more | `UploadReads` (4) bounds the reads, 503 with `Retry-After` past 10 s. The bytes go through `UploadBytes` and the bucket's Put without copies. On the Markdown screen an unread upload answers a 503 page, not the form again empty: Back keeps the text | `TestReadingUploadsIsBounded`, red first |
| **N8** (L) Nits | Stale window comments fixed. `/images/copy`'s "too many" is a sentence. Replace… finds its image by id. A WebP frame's size is checked against 24 bytes. A broken form part is a 400, not "too large". `moved_from` keeps the last Restore only (I20) | — |

**Safari's own Copy image** could not be driven headless: it is a native context-menu action, and WebKit's `clipboard.read()` waits for a person's gesture. So WebKit was checked with the clipboard shapes a Copy image produces (the picture with a lone `<img>`; with the address as text), and those upload. A copy in Safari by hand is still to do.

### Round 5: Fable's narrow check of N1 and N2 (`101962f`), APPROVED, five lows fixed before merge

| Finding | Change | Gate |
|---|---|---|
| `?upload=1` made any POST an upload route, so `/auth/begin?upload=1` took multipart | An upload route is a POST to `/images`, or `?upload=1` on `/scratch`, `/p/<id>` or `/d/<date>` | `TestOnlyUploadRoutesTakeMultipart` gains `/auth/begin?upload=1` and `/pages?upload=1`, red first |
| A file copied in Finder (Chrome on macOS: the file and its name as text) became text | With no HTML, the picture also wins when every line of the text is the name of one of the files | `upload.test.mjs`, red first |
| The read slot was released before the image was stored, so bodies waiting for a blob slot were unbounded | `receiveImage` holds it until the image is stored | `TestReadingUploadsIsBounded` |
| `loneImage` refused an `<img>` with a `>` inside a quoted attribute | The pattern reads quoted attributes whole | `upload.test.mjs`, red first |
| Replace… searched the document for its image first | It uses the image's place when that still holds the id, and searches only otherwise | — |

## 12. Build notes

The build is on `feat/images`, from `main` `3b20386`, with `main` `0296a7e` (the week strip and date picker) merged in. Paul's answers to §10, 2026-11-17, "Go ahead": refuse SVG; 1 GiB per person, 10 GiB for team pages, 10 MiB per image; no captions or resize handles, JPEGs over 4,096 px scaled down in the browser; external `![x](https://…)` never fetched; any member may remove a team-page image, with a confirm page and an event; the sweep stays exempt; and the oficina plan must not force scanning (Paul's to check).

**What landed, by §6's rows:**
- `0005_images.sql` and the gate-4 row: `plaintext_test.go` lists every new column, and `images`, `image_trash` are Mapa's own tables.
- `seal`: purposes `image` and `image-record`, `Pad`, and `SealPadded`, which pads and seals in one buffer.
- `imagefile/`: sniffing, the four walkers, the limits; committed fixtures from `testdata/make.py` (Pillow) and a fuzz target per walker.
- `images*.go`: upload, copy, the read rule, attach at commit, copies before a write and their removal on failure, removal, the sweep, the quotas, the semaphore, config.
- `handlers_images*.go`: `POST /images`, `POST /images/copy`, `GET /i/{id}`, the remove confirm page and its POST, and the Markdown screen's Upload and insert with "Images on this page".
- `markup/images.go` and its port in `markup.mjs`; the schema's `image` atom (`imagedom.mjs`), `imageview.mjs`, `upload.mjs`, `imagebubble.mjs`, and the clipboard's copy on paste.

**I1. The scriptless upload posts to the form's own action.** §4.4's Upload and insert is a second submit button with `formaction="<the form's action>?upload=1"` and `formenctype="multipart/form-data"`. The page's `POST /p/{id}`, the day's `POST /d/{date}` and New scratch page's `POST /scratch` each check `?upload=1` before anything parses the body. The bound (`MaxBytesReader`, 10 MiB of text plus 10 MiB plus 64 KiB of multipart overhead) is applied first. The parts are read with `MultipartReader` into memory, never to a temporary file (round 3, H1), the fields before the file. Each handler then re-renders its own screen, which is "the re-render a refused save already does". `POST /images` is the JSON upload only. New team page has no text field (level-up §4.7), so it has no upload; the page's own Markdown screen does.

**I2. "Images on this page" with script on.** The History panel ends with a link, "Images on this page", to the Markdown screen's list (`…/edit#page-images-title`), which lists earlier images too. The list itself is drawn only on the Markdown screen.

**I3. `/links/resolve` answers images under their own key.** A request may carry `image` fields, with the editor's `page` (a public id, used only when the viewer may open it). When it carries any, the reply is `{"links": {…}, "images": {id: {available, width, height}}}`; otherwise it is the map it always was, so the chips' client is unchanged. A wiki target can be any text, so no key prefix could keep the two apart in one map.

**I4. Which page "rendering on P" means, path by path.** The page view, a day, Preview (with the editor's page), Make team page's block list, the conflict view and History's old revisions draw for their own page. Backlinks' and mentions' snippets draw each block for the page it comes from. History's old revisions link each available image to its confirm page (`a[mapa-image-remove]`); an unavailable box links nowhere, and the word diff's `[image: alt]` is text.

**I5. Statuses.** A type Mapa does not take, or a file one of the walkers cannot read, is 415 with the one sentence. Over 10 MiB is 413. Past 10,000 px or 50 MP, or no file chosen, is 422. Over either allowance, or CARLOS refusing the Put, is 507, each with its §3.4 sentence. No store, or a 10 s wait for a slot, is 503 (the wait with `Retry-After: 5`). `GET /i/{id}` past its 30 s wait is 503, `no-store`, with `Retry-After`.

**I6. An upload's box across rewrites.** §4.2 says a deleted place puts the image at the end. A rebase or the inline choice writes a block again through `applyBody` (now marked `mapa-applied`), which deletes the old block's positions. The box then keeps its offset in the block that replaced it. Only a box whose own place the person deleted, with both sides gone, is lost (round 3, M5). That image goes at the end of the page with the notice. An undo that took the place away drops the result, and ends a failed upload's wait (L12). `TestL9AnUploadInFlightCrossesTheInlineChoice` holds the case where Resolve's `cleanBody` trimmed the space the box sat after.

**I7. What the walkers refuse, and what they read.** A PNG chunk whose CRC is wrong, or an unknown critical chunk, is refused. A JPEG needs a frame and a scan, and must reach EOI. An EXIF block Mapa cannot parse gives orientation 1: it is dropped whole either way, so nothing in it is passed through. A kept JPEG segment is a slice of the upload, never copied, except JFIF's APP0, which is written again without its thumbnail.

**I8. Alt text.** `Image.Markdown` and the editor's field remove `[`, `]` and line breaks (as §7 says), and cut at 1,000 bytes on a character. The NodeView is named "Image: <alt>", "Image with no description", or, for the box, the same followed by ", not available".

**I9. Attaching.** `tx.commit` takes `attaching{on, base}`: `attachOwn(base)` or `attachNothing`. `CommitFrom` passes the draft's or form's base revision; Resolve reads the base from the person's draft row (its `current` is the page's head, not where the text started); create, a day's first commit, scratch pages, Make team page and `draftToScratch` pass `attachOwn(0)`. Revert, Restore, Rename, "Update links", "Link it" and markers pass `attachNothing`. The Notion importer's `ImportCreate` and `ImportUpdate` are not on `main` yet; they should pass `attachOwn(0)`. `AddImage`, `CopyImage` and `Image.Markdown` have §7's signatures.

**I10. Copies.** On paste, a slice whose `page` is this page keeps its ids. A slice from another page, or one with no page, has every image in it copied, its code blocks aside. Make team page's and `draftToScratch`'s copies wait for a blob slot as uploads do (10 s); a copy that is refused (an allowance, no store) fails the verb, with its copies so far removed.

**I11. The queue and the exemption.** Deleting a key from `image_trash` after its object is gone is retention's housekeeping, exempt with it. The row went with an event (a removal) or under the sweep's exemption.

**I12. Allowances count padded bytes**, the person's including pending images past their window that the sweep has not taken yet. `MAPA_IMAGE_QUOTA_PERSON` and `_TEAM` take bytes or a number of KiB, MiB or GiB; anything else refuses boot.

**I13. Development.** `cmd/mapa` keeps images in `<database>.images/` (`blobs.Dir`) only for a loopback origin with no `CARLOS_STORE_*` set. `make preview` keeps them beside its temporary database. A partial store logs, at error level, the variables it lacks.

**I14. Memory (§1.4).** The figure could not be measured on the instance: CARLOS has no store for Mapa yet, so nothing is deployed. On the build machine (arm64, Go 1.26.11), eight concurrent uploads of a 9.8 MB PNG through `AddImage`, four at a time, raised the heap in use from about 43 MiB to a peak of 182–245 MiB: about 50 MiB per upload in flight, not 30. The excess is the object store's own copy (`blobs` reads the whole reader again before its Put) and garbage not yet collected. Two cheap cuts are in (`SealPadded`, and the walkers writing into one buffer of the upload's size). After round 3, `BlobSlots` is 2 until the figure is measured on the instance after §8. If that is still too much, build §9's streaming sealing.

An upload is now read whole into memory before it asks for a slot (H1), so a slow sender holds no slot. But each request in flight holds up to its bound (about 20 MiB on the Markdown screen, 10 MiB for `POST /images`) outside the semaphore, until its slot comes or its wait ends. Only the server's own limits bound how many such requests there are.

**I15. `golang.org/x/image` is pinned at v0.45.0**, the newest that moves no other pin. It is in the Colophon.

**I16a. Remove from Mapa with script** commits first, as leaving does, then opens the confirm page, whose way back is read after the commit: a new scratch page has its address by then. After the POST the page says "Removed the image from Mapa".

**I16. The menus.** Insert gains "Image…" where the page editor runs, beside Date…; `/` gains "Image"; the phone's row gains an "Image" button. The Markdown screen has Upload and insert instead.

**I17. Only a JPEG keeps its orientation** (§5, round 3 L11). PNG's `eXIf` and WebP's `EXIF` are dropped whole, orientation included. Browsers apply neither consistently, and §5 keeps orientation for JPEG alone.

**I18. A full bucket is read from the Put's status** (round 3, L8). `bucket` (`images_bucket.go`) reads and deletes through `blobs.S3`, and Puts over a URL `blobs.S3` presigns. A 403 is `ErrStorageFull`; any other failure is a failure.

**I19. A pending image is its owner's for as long as it exists** (round 3, M1), amending §3.1 and §3.2. `TestAnAttachNeedsTheImageInsideItsWindow` is gone with the window it tested.

**I20. `moved_from` keeps the last Restore only.** A page deleted, restored, then that restored page deleted and restored again leaves its images naming the second deleted page. A draft left on the first deleted page then copies nothing, as before round 3.

**I21. Bodies.** `bounded` (`bodies.go`) caps every request body at the form's bound (10 MiB plus 64 KiB). It refuses multipart, 415, except on `POST /images` and `?upload=1`. Those set their own, larger bound when they read.

**I22. The description is asked for on the image itself** (2026-11-17, after the merge; Paul: *"can it be more ... inset in the image rather than under it? Or maybe in a modal?"*). Inset, not a modal: a modal covers the picture being described, and is heavy for one line. Branch `fix/alt-inset`.
- **The frame.** The editor's NodeView is now a `span[mapa-image-frame]` around the server's own `<img>` (or the "not available" box): `inline-block`, `vertical-align: bottom`, `line-height: 0`, so its box is the picture's and the mount moves nothing (L5 unchanged, and green). A lone image's frame is the block, `fit-content`. The node decorations (`alone`, `data-mapa-drawn`) land on the frame; a new answer draws the picture again inside the same frame. The server's HTML and the scriptless screens are unchanged.
- **The ALT badge** (`editor/altinset.mjs`) is a `<button>` in the picture's bottom-left corner, drawn only on an available image. Filled (a light pill) when the image has alt; outlined (a dark pill with a white rim) and always shown when it has none. Otherwise it shows on hover (pointers that hover), on focus, and while the image is selected; hidden it takes no pointer events, so a tap on a phone never lands on an unseen badge. It is named "Alt text: describe this image" or "Alt text: <first words>, edit" (five words or 40 characters, then "…"): the name starts with the visible word, so voice control reaches it (WCAG 2.5.3; the coordinator's ruling on Fable M3). The badge of an image with no description is a Tab stop inside the editor, as the task boxes are (level-up §6.11), so the keyboard finds what is missing; a described image's badge is `tabindex="-1"`, reached through ⌥F10 → Alt text (Fable L4). A badge pressed while its field is open closes it. 24 px tall, 32 px on coarse pointers; hidden in print; no transition under reduced motion.
- **The field.** The badge, the bubble's Alt text and a finished upload (when the selection has not moved, as before) open one field: a label, "Describe this image for people who can't see it", and a one-row `<textarea>` that grows to four lines, and over the image never past the picture's top: it scrolls instead (a pasted line break becomes a space; the field holds no more than `MaxAlt` bytes, cut at a character, as `cleanAlt` keeps; spaces at either end are dropped, on the Markdown screen too). A press on the label or the band keeps the field open (Fable M1). On an image at least 240 × 120 px as drawn it lies over the bottom edge, inside the frame, on `rgb(17 17 17 / 0.84)` with white text and the field on the page's own surface, so it reads over a white picture or a black one. Smaller, it is a popover under the badge, over the text below. Both are absolutely placed inside the frame: no block moves while either is open, and nothing is drawn below the image any more.
- **Keys.** Enter, Shift+Enter and Tab keep the text; ⌘S keeps it and saves the page; Esc puts back what was there (nothing was written); leaving the field keeps it, but another window taking focus does not count as leaving, unless focus comes back somewhere else. Not while composing.
- **Leaving with the field open** (Fable M2): a link's click (Safari's tap moves no focus, so no blur) and `pagehide` keep the field's text before the page is settled, so the leaving commit holds the description.
- **A block drawn again.** The editor may move the image's frame into a block it draws anew (a rebase, the inline choice): the field goes with it and takes its focus back. A frame the editor destroys keeps the text for the image by its id, and gives focus back if nothing else has it; an answer that arrives while the field is open draws the picture again when the field closes. A finished upload does not open its field while another image's field is in use; it says "Image added". Keeping is the same one `setNodeAttribute` transaction as before, sent only when the text changed, so autosave sees it and an unchanged field writes nothing.
- **Focus afterwards:** to the badge when the badge opened it (found again, since saving can draw the block anew through the settle plugin's reparse); to the image, selected, from the bubble; to the text just after the image after an upload. A save that does not return to the badge says the image's new name in the live region ("Image: <alt>"), so a screen reader hears it.
- **Gates** (`images_alt_browser_test.go`, `images_alt_badge_browser_test.go`, `images_alt_leave_browser_test.go`; the first five fail on `main` `f9337f9`, and each of Fable's findings has a gate that fails with its fix taken out: a press on the label, a link and the tab's close (one commit, holding it), ⌘S, the block drawn again, another window, a long description on a 120 px image, the badge's tab order, the badge pressed again; the badges' and the band's backdrops by opacity; the open field in print; the live region; the popover at the right edge of a 390 px phone): the field after an upload and from the bubble is inside the picture's box (`elementFromPoint` over the bottom edge hits it, and the textarea's centre hits the textarea), none of it lies outside the frame, and `boxes` is the same open and closed; Enter, Shift+Enter, Esc (restoring, and the image selected again) and leaving; the badges' states, names, hover and print, and axe with the field open and after; a 100 × 60 image's popover, on screen and over the text, moving nothing; a tap on the badge at 390 px with a coarse pointer opens the field with focus, 16 px text. `altinset.test.mjs` holds the names.
- **Strings:** `copy-review/images/strings.json` holds every user-facing string of the images feature, which never went through copy review, and these new ones.

### Departures from the spec

- **§6's `POST /images` serves JSON only;** the scriptless Upload and insert posts to the Markdown screen's own action (I1).
- **§4.2's "a deleted place goes at the end"** does not apply to a block the server's text rewrote, or to a box whose neighbours were deleted (I6, round 3 M5).
- **§4.3's field under the image** is now laid over the image, with an ALT badge, and §4.6's walk reaches it from the badge as well as the bubble (I22).
- **§1.3 gains `moved_from`** (round 3, L4); **§3.1–§3.3 lose the read-side window** (round 3, M1). Both are recorded in their sections.

### Gates

- **IMG1** `TestIMG1ImagesLeakNothing` (two worlds, byte for byte: the team page and its island, its Markdown screen, `/links/resolve`, `GET /i/{id}` and its remove page against an id that never was, `/images/copy`), `TestIMG1AnaSeesHerOwn`, and the attach cases at store level (`images_attach_test.go`).
- **IMG2** `TestImagesReachTheDiskSealed`, over a fake S3.
- **IMG3** gate 8 drives `POST /images`, `/images/copy` and `/i/{id}/remove`; `images` and `image_trash` are recorded tables.
- **IMG4** `TestIMG4AGetWritesNothing`.
- **IMG5** `internal/mapa/imagefile`: every fixture loses its canaries, keeps ICC and orientation, and decodes to the same pixels; truncations and bad lengths are refused; `FuzzJPEG`, `FuzzPNG`, `FuzzWebP`, `FuzzGIF` and `FuzzClean` run their seeds in CI.
- **IMG6** `images_refusal_test.go`.
- **IMG7** `images_lifecycle_test.go`, with an object store that fails the test if called inside a write transaction.
- **L1–L4** image corpus cases (no existing body changed output), L3's image edits, and a serialiser case.
- **L5** `TestL5ImagesReserveTheirBoxes`; **L8** `images_floor_test.go`; **L9** `TestL9AnUploadInFlightCrossesSavingAndLeaving` and `…TheInlineChoice`; **L10** `TestL10ImagesByKeyboard`, `TestL10InsertImageByKeyboard`, `TestL10AFinishedUploadMovesNoFocus`, axe on a page with an image. `TestABigPhotoArrivesUprightAndSmaller` is §4.1's JPEG; `TestAPasteFromAnotherPageCopiesItsImages` is §2.2's paste.
- **`make mutate`** gains 18 mutants (17 at `49d8df3`, and round 3's M2) (`scripts/mutate/images.go`; `MUTATE_GATES=IMG1,IMG7` runs a subset), every one caught: IMG1's four (the route's scope check, resolving images attached elsewhere, attach ignoring "introduced", Revert and Restore passing attach), the owner check, both copy rules, sealing before Put, IMG3's event, the size limit, the semaphore, and one per walker.
- **WebKit by hand** (Playwright 1.62, WebKit 2336, against `make preview`): Insert → Image… with the alt field, paste of an image file, drop of an image file, the phone's row on an iPhone 13 profile, `/` → Image then the bubble's Remove from Mapa through its confirm page and back, and the 6,000 × 4,000 JPEG with orientation 6, which arrived 2,731 × 4,096 and upright. Chromium the same, with no console errors in either.
