oficina / mapa Public

Mapa images: design spec, revision 1

Paul, 2026-11-17: "we should handle image uploads." Sealed bytes in
CARLOS's bucket, served through Mapa with scope checked; standard
![alt](/i/<id>) Markdown; pending images attached by commit; per-person
quota; metadata stripped without re-encoding; the importer's AddImage.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 4d40e4e7f88c62437dbd2aca2e3d2218aa9985d8 parent 3b20386
1 file changed, +464 −0
  • docs/superpowers/specs/2026-11-17-mapa-images.md +464 −0

CI passed — run details

CI log
=== editor ===
cd editor && npm ci --no-audit --no-fund --loglevel=error

added 16 packages in 338ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.c25f62142895a785.js (318737 bytes, 99.5KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ L1: mounting then serialising gives cleanBody(body), byte for byte (44.603786ms)
ℹ 760 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (61.613211ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (110.878903ms)
ℹ 748 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (120.385499ms)
ℹ 755 inserts, 715 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (5324.730307ms)
ℹ 18240 edits over 760 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (1222.385746ms)
ℹ 4124 links over 760 bodies; refused: {"A page link can’t hold another link or a line break. Select plain words.":610,"A page link can’t show [ or ]]. Select words without them.":370,"Select some words to link them to a page.":163,"Linked here, the Markdown around these words would read differently: a ! before them makes an embed, and a stray ` or * pairs up. Select other words.":17}
✔ linear: trailing spaces (29.020298ms)
✔ linear: trailing whitespace (15.266025ms)
✔ linear: unclosed web links (12.046982ms)
✔ linear: web links with no address (18.55983ms)
✔ linear: unclosed wiki links (19.456765ms)
✔ linear: unclosed embeds (16.4742ms)
✔ linear: closes only (6.525043ms)
✔ the selected words become the chip's shown text (9.661351ms)
✔ words that are the title make a plain [[Title]] (2.830045ms)
✔ spaces at the selection's edges stay outside the chip (1.248391ms)
✔ a date makes a date link, in a heading, an item and a quote (5.318431ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (0.900891ms)
✔ only the linked block's bytes change, and undo gives the body back (1.806531ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (0.981474ms)
✔ a target the words cannot be linked to as typed is refused (0.216712ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (2.079018ms)
✔ web-linked words are refused: the address would be lost (review M4) (0.839465ms)
✔ words whose Markdown would read otherwise are refused (review M3) (1.633102ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (0.366326ms)
✔ linkCheck says why it refuses (review low 2) (0.514247ms)
✔ golden file has bodies (0.870032ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (17.350645ms)
✔ markup.mjs strips and spans every block as Go does (27.601554ms)
✔ the schema's toDOM draws every body as Go renders it (45.161716ms)
✔ emphasis draws the four pinned outputs (17.971474ms)
✔ a body ends in the editor's empty paragraph (0.251538ms)
✔ a POST that never answers is aborted after the timeout (20.722328ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (1.020778ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (10.221272ms)
✔ an offered draft never commits by itself; Save commits it (1.353ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.71103ms)
✔ closing carries text not yet sent, and the cap leaves it out (24.623107ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (2.674601ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (2.300509ms)
✔ typing mid-flight: the merge is not applied and the base does not move (1.237169ms)
✔ a merge the editor cannot represent stops after three tries (3.200799ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (1.000441ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (1.382747ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (0.763941ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (0.850947ms)
✔ noBase and gone lead to the existing choices (0.670394ms)
✔ a commit that merged is applied when nothing was typed since (0.72147ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (5.959589ms)
✔ an own draft committed meanwhile goes on as a new draft (1.230928ms)
✔ a reload keeps a stored draft; unsent text still commits (0.512724ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (0.980522ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (2.266003ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (1.181585ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (3.396913ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (0.945957ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.262118ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (0.739715ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.39502ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (0.537561ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (0.483348ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (0.493427ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (5.519793ms)
✔ marks close before code, links and atoms, and reopen after (0.465895ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (6.256142ms)
✔ empty blocks are written as nothing (1.850144ms)
✔ an unclosed fence that is no longer last gets its closing fence (1.302605ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (1.919306ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (3.884527ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (2.162267ms)
✔ a trailing hard break stays on screen and is written as nothing (0.506682ms)
✔ the reparse waits while an IME is composing (0.72659ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (3.481172ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.885432ms)
✔ rebuild changes origins only, outside undo history (1.518073ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (1.350204ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (2.330537ms)
✔ a duplicate ^id typed above its holder never takes the id from it (0.81073ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (1.034175ms)
✔ a history command that throws is refused, never thrown (3.291803ms)
✔ one rename at a time, from either field (2.089159ms)
✔ an empty or unchanged title sends nothing (0.232361ms)
✔ a refusal keeps what was typed, and the title (0.241108ms)
✔ the pending state holds for the busy rule (6.074387ms)
✔ a failed POST says so and keeps the title (0.960233ms)
✔ Update links posts the confirm page's POST (0.262228ms)
✔ clean is CleanTitle's whitespace rule (0.220178ms)
✔ the saver's base follows a rename made over it, and only that (0.295111ms)
✔ closing sends the rename as one keepalive POST (2.21146ms)
✔ a drag whose anchor the document no longer reaches selects to its end (5.057656ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 7042.983026
=== vet ===
go vet ./...
go vet -tags browser ./internal/mapatest/
=== fmt ===
=== code ===
go tool rastrillo budget code
The base has no .rastrillo/code.txt: skipping the check that records only go down.
budget code: within the limits.
=== test ===
CGO_ENABLED=0 go test ./...
?   	amadan.net/oficina/mapa/cmd/mapa	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa	0.674s
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/markup	0.089s
ok  	amadan.net/oficina/mapa/internal/mapa/seal	0.009s
ok  	amadan.net/oficina/mapa/internal/mapatest	10.626s
?   	amadan.net/oficina/mapa/scripts/mutate	[no test files]
?   	amadan.net/oficina/mapa/scripts/preview	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
=== credits-check ===
python3 scripts/credits.py --check
credits: checked
diff --git a/docs/superpowers/specs/2026-11-17-mapa-images.md b/docs/superpowers/specs/2026-11-17-mapa-images.md
new file mode 100644
index 0000000..d11f64d
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-17-mapa-images.md
@@ -0,0 +1,464 @@
+# Mapa images
+
+**Status:** revision 1, 2026-11-17. For review. Nothing is built.
+
+**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 and one route that serves bytes. §6 lists every server change and the gate that holds it.
+
+**Prior art in the suite:**
+- **Slides** (`internal/slides/assets.go`, `d047eef`): bytes in CARLOS's bucket, served *through the app*, sniffed from the bytes, `nosniff` and a `sandbox` CSP.
+ - Presigned URLs were tried there 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, stores sealed bytes with the stored type `application/octet-stream`, keeps a placeholder as a decoration and inserts the node when the upload succeeds, and re-uploads an image pasted from another document.
+- **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
+
+Found from `carlos store --help`, Slides' live store (`carlos store status --app slides`), carlos/platform `internal/objstore`, `docs/site/cli.md` and the 2026-11-15 plan catalog:
+
+- **A bucket of its own, with an IAM user of its own,** in `eu-west-1` (Slides' bucket is `carlos-store-bds-slides`). The user's policy allows Get, Put and Delete on objects and List on the bucket.
+- **Credentials as config.** `CARLOS_STORE_BUCKET` and `_REGION` arrive as env. `_ACCESS_KEY` and `_SECRET_KEY` arrive as secrets. `_ENDPOINT` arrives only on a deployment that has one.
+ - `carlos store rotate` mints a new key and keeps the old one live until `--finish`.
+- **No signing service and no proxy.** Presigning is the app's own job (rastrillo signs). Nothing serves the bytes for the app.
+- **Encryption:** AWS's default server-side encryption. That does not stop a credentialled reader, so it is not Mapa's seal.
+- **No versioning and no lifecycle rules.** Nothing is deleted unless the app deletes it. Deleting an instance leaves its bucket.
+- **Size and cost:** the 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.
+ - A store past its plan's grace period has `PutObject` denied, while Get and Delete still work.
+- **Scanning** is off by default. A plan with `storage_scan_required` (Free, under the new catalog) forces scanning. It also refuses a client-encrypted attestation and per-instance stores. Slides' store has no scanning today, so the oficina account's plan does not force it now. §8 and Q5 deal with this.
+
+### 1.2 Decisions
+
+| # | Decision | Rejected |
+|---|---|---|
+| I1 | **The bytes are sealed in Mapa, under Mapa's DEK, before they leave the process.** The bucket holds only ciphertext. Mapa's `seal` package gains a purpose, `image`, so the HKDF-derived key is apart from every other key (build note 21). The object is stored as `application/octet-stream`, so its type is not visible in the bucket either. | Plaintext in the bucket, as Slides does. Slides does not seal anything; Mapa seals everything (base §4), and an image of a whiteboard is as private as the page it sits on. Docs' plan 7 already took the same view. Using rastrillo's `blobs.Sealed`: `AGENTS.md` makes `seal/` Mapa's only encryption |
+| I2 | **Readers get images only through Mapa:** `GET /i/{id}`. That route checks scope, reads the ciphertext, checks it, opens it and writes the image. | Presigned or public URLs. A URL cannot check scope, the bucket holds ciphertext that only the app can open, and Slides found that its CSP and CORS refuse them anyway |
+| I3 | **The object key is the SHA-256 of the ciphertext** (rastrillo's content addressing). Every seal draws a fresh nonce, so two uploads of the same picture are two unrelated objects. **Before opening, Mapa checks that the bytes it read hash to the key.** A swapped object is therefore 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 |
+| I4 | **Development and tests use `blobs.Dir`** beside the database, as Slides does. Production with no store bound boots, and upload answers 503 "Images aren't set up on this Mapa yet". A partly delivered store (a bucket with no key) is a boot refusal in `config.go`. | Falling back to the database or the local disk in production. The disk is ephemeral and hibernates, and blobs in SQLite ride the replicated WAL |
+
+### 1.3 The `images` table, and the gate-4 row
+
+One row per image. "Image" means one picture attached to 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). It is never sequential, so it counts nothing |
+| `owner` (member id) | yes | who uploaded it. Pending images are readable by this person only (§3), and the per-person quota counts by it |
+| `page_id` (nullable) | yes | the page it is attached to; null while pending. S2-style reads answer from the page's rung without unsealing |
+| `created_at` | yes | the pending window and the history window (§3.3) |
+| `stored_bytes` | yes | the ciphertext's size, for the quota. The bucket shows it anyway |
+| `object_key` | yes | the bucket key: a hash of ciphertext, which says nothing about content |
+| `sealed_record` | sealed | the sniffed type, width and height after orientation, and the plaintext 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, stored_bytes, object_key)`, and `image_trash (object_key, queued_at)` | serving, scope and retention without unsealing | **how many images each page holds, who uploaded each and when, and roughly how big each is**, on private pages too. A copy (§3.2) made at the same moment as another image of the same ciphertext size suggests the two are the same picture.
+
+The leak has the same shape as "revision store" and "ciphertext sizes": counts, times and sizes, never content, and never which page an image came from.
+
+### 1.4 Serving
+
+`GET /i/{id}`:
+
+1. **Scope first** (§3.1). If the viewer may not read the image, the answer is the app's ordinary 404. The body and headers are the same as for an id that never existed.
+2. If it is readable, the answer depends on `If-None-Match`:
+ - It names `"<public_id>"`: the answer is `304`, with no store read.
+ - Otherwise Mapa reads the object, checks its hash (I3), opens it, and writes it.
+3. **Headers:**
+ - `Content-Type`: the sniffed type 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 any shared cache out.
+ - **The hour is the honest 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 image bytes are cached.
+5. **Memory:** rastrillo's `S3.Put` and Mapa's seal each hold the whole object. Ten MiB is the cap per image (§5), and at most four uploads run at once per process; a fifth gets 503 with Retry-After. The worst case is therefore about 120 MiB.
+
+---
+
+## 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)`,** and Mapa renders it as an image **only when `src` is exactly `/i/<public id>`**. The public id is `[0-9a-z]{1,13}`.
+- **The alt text** is any text without `[`, `]` or a line break, at most 1,000 bytes. The editor's alt field refuses those characters.
+- **There is no title** (`"…"` after the address) and no size suffix.
+- **Every other `![…](…)` renders as it does today:** a literal `!` followed by a web link. An external image is never fetched or hotlinked, because 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 links (§4.1, §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. A paragraph that is only an image is drawn as one, because the CSS gives an image alone in its block `display: block`.
+- **The text index** reads the alt text as body text. It does not read the address, so search, unlinked mentions and snippets never see `i` or an id.
+- **S3 and memoria** see the image as its alt text. No bytes, and no image id, reach a sibling.
+- **History's word diff** shows an image as `[image: alt]`.
+
+**Rejected: `![[image:…]]`.** `![[app:item]]` is Mapa's embed grammar (base §7). Its rules are a team container's write-time check, render enforcement (gate 12) and S10 payloads, and they would all have to learn that `image` is not an app. It also has no standard place for alt text. It survives nowhere outside Mapa, while `![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 hosts (`paulca.mapa.oficina.works`).
+
+### 2.2 Copy, paste and export
+
+- **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).
+ - **Paste into a different page** first calls `POST /images/copy` with the slice's ids. It gets back a new pending image (§3.2) for each id the viewer may read, and rewrites those addresses in the pasted text before inserting it.
+ - An id the viewer may not read is left as it is, and renders as unavailable. The reply leaves it out exactly as it leaves out an id that does not exist.
+ - Paste into the same page keeps the ids: the picture is already attached there.
+ - The rewritten blocks are new blocks with fresh origins, so fidelity (§2.3) is untouched.
+- **Image files on the clipboard,** from screenshots, Finder or Photos, are uploaded (§4.1).
+- **HTML from outside:** an `<img>` with a remote `src` becomes a web link (`[alt](src)`), or nothing when there is no safe address. Mapa never fetches it.
+- **The scriptless textarea:** text pasted there is kept as typed. A copied `![alt](/i/id)` from another page renders as unavailable on this one (§3.1), so 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, not built yet): each exported page's attached images go into `attachments/<public id>.<ext>`, and the page's addresses are rewritten to `attachments/…`. Obsidian reads that form. Until export exists, there is nothing to do.
+
+### 2.3 Fidelity gates L1–L4
+
+- **Corpus.** New cases include:
+ - an image alone in a paragraph, in a list item and in a quote;
+ - an image between words, two images on one line, and an image with `^id`;
+ - an empty alt, and alt text with `*` and `` ` ``;
+ - `![x](/i/)` and `![x](/i/UPPER)`;
+ - `![x](https://…)`, `![x](/p/…)` and `![x](/i/id "title")`;
+ - `![` with no close, `![[`, and an image inside code.
+ - Every case that is not an image must come out exactly as today's golden file says.
+- **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, and pasting an image slice. The structure check and the reparse rule hold.
+- **L4:**
+ - `markup.mjs` and Go agree on `Image` spans, including the byte offsets.
+ - `toDOM` equals Go's `Render` for every image case, using a fixed resolution table in the golden file: `available`, with width and height, or `unavailable`.
+ - Width and height come from the resolutions, not from the node's attributes, which is how chip state works (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 ever changes rung either. An image's rung is its page's.
+
+**Make team page** (level-up §6.7) is the one way private writing reaches the team. In the same write, `MakeTeamPage`:
+- **copies** each image the moved blocks reference: a new row attached to the new team page, and a new object with a fresh seal;
+- writes the new page's body with the new addresses.
+
+The private note's own images stay private. Its older revisions still reference them, and they age out with its history (§3.3). This is decision 8's rule 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
+
+Images use one rule, the store's scoped accessor (`readrule.go`'s `MayRead` and `around.go`):
+
+- **An attached image** is readable by whoever may read its page, and only while that page is not deleted.
+- **A pending image** (`page_id` null) is readable by its owner only.
+- **Rendering on page P** resolves `/i/<id>` as available only when:
+ - the image is attached to P, or
+ - it is pending and owned by the viewer, which is what a person sees in their own draft.
+
+ Anything else is drawn the same way: a fixed-size "Image not available" box. That covers a missing id, an image attached elsewhere, someone else's pending image, and a removed one. 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 I1).
+
+### 3.2 How an image gets a place
+
+1. **Upload creates a pending image** owned by the uploader. It is attached to nothing, and it logs `uploaded` (object kind `image`).
+ - This is a write by a person. Like every first write, it creates their member row (build note 5).
+ - Upload needs no page, so it works the same for an unwritten day, a new scratch page and a team page.
+2. **A commit attaches it.** `tx.commit` is the one function that writes a revision: create, commit, resolve, restore and Make team page all go through it.
+ - It parses the committed body.
+ - Every referenced image that is **pending and owned by the person committing** is attached to that page in the same transaction.
+ - Nothing else is attached: not someone else's pending image, and not an image already attached elsewhere.
+ - The commit's own event covers it. The body is never rewritten, so the bytes sent are the bytes stored.
+3. **Copy** (paste across pages, `POST /images/copy`) makes a new pending image owned by the person copying, with a new object.
+ - It applies only to images that person may read.
+ - It logs `uploaded`.
+ - Make team page's copies are attached at once, inside its own write.
+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.
+
+### 3.3 Retention, removal and the sweep
+
+**An attached image is kept while any of these holds:**
+- its page's current body references it;
+- a revision still inside the 90-day window references it;
+- a draft on that page references it;
+- its page is deleted but still restorable (90 days).
+
+So an image taken out of the text stays reachable from History, and comes back on Restore, for as long as the text it was in does.
+
+**A pending image is kept while** a draft of its owner references it, or for one day after upload. The day covers an upload whose commit has not landed yet.
+
+**The sweep** is part of `Store.Sweep`, which runs when the app wakes. It never runs on a GET and never on a timer.
+- Images that no rule above keeps are deleted. Their object keys move to `image_trash` in the same transaction.
+- The same pass then deletes the trashed objects from the bucket, and removes each queue row once its delete succeeds. A failed delete is retried at the next wake.
+- **Retention is exempt from gate 8 by name** (base §5, build note 27). It removes only what no person can still reach, and 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 two reasons, and Q7 puts it to Paul.*
+
+**Removing an image now.** "Remove from Mapa" is in the image's menu, and on its own confirm page with script off (`GET /i/{id}/remove`, `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.
+- In one write it deletes the row, queues the object and logs `removed` (object kind `image`) with the actor.
+- Every reference to it, in History too, then renders as unavailable. This is the path for a photo that should never have been uploaded.
+- The object is deleted at the next wake, or straight after the transaction when it can be. The one-hour browser cache (§1.4) is the stated limit.
+
+**Deleting a page** removes nothing at once. Its images answer 404 while it is deleted, come back on Restore, and are swept with its history after 90 days.
+
+**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 40 megapixels, with neither side over 10,000 px (§5).
+- **Per person, not per team:** 1 GiB of `stored_bytes` across everything they own, whether pending, attached or kept for history.
+ - A team-wide total would make one person's refusal depend on everyone's private images: a count of what they cannot see (base §3.3).
+ - The limit is `MAPA_IMAGE_QUOTA_BYTES`, with a default of 1 GiB.
+ - The refusal says how much the person has used, which is their own figure.
+- **The account's plan** (§1.1) bounds everything. When CARLOS denies `PutObject`, the upload answers "Mapa's storage is full. Ask whoever runs your team's Oficina." That signal depends on usage the person cannot see: the account's, across apps. It is the platform's, it is unavoidable, and it is listed 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**;
+ - an **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"`. On iOS, that accept list makes Safari hand 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).
+- **Upload** is `POST /images` (multipart, field `file`), sent with `XMLHttpRequest` so that 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 the upload runs, so autosave, the structure check and every other tab see no dangling address.
+- **On success** the `image` atom is inserted where the decoration has been mapped to. If an undo has removed the decoration, the result is dropped, and the pending image is swept a day later.
+- **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, a small field under the image takes focus: "Describe this image for people who can't see it."
+ - Enter keeps the description, and Esc or Tab skips it.
+ - 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`, which makes the block edited (§2.3).
+ - Empty alt is allowed, and renders `alt=""`. Notion's images often have none.
+- **Sizing:** the natural size, never scaled up, and capped at the column (`max-width: 100%; height: auto`). There is no resize handle and no stored width. The trigger for one is in §9.
+- **Captions:** none. Markdown has no caption, and the line after an image already reads as one. The trigger is in §9.
+
+### 4.4 The scriptless floor
+
+The Markdown screen's form gains a file input and a second button, **Upload and insert**. Its handling:
+- The POST carries the textarea's text, the base revision and the file.
+- The server uploads the file as a pending image, then shows the Markdown screen again: the submitted text, with `![<alt field>](/i/<id>)` added 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 same one a refused save already does, and it works for every page kind, including an unwritten day and a new scratch page.
+
+### 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 any byte arrives.
+ - An unavailable image is a box of fixed size.
+- **The island** (level-up §6.8) gains image resolutions, scoped exactly as rendering is (§3.1), so the editor's NodeView draws identical markup.
+- **L5 gains a page with images:**
+ - one image above the fold, one below, one unavailable, 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
+
+- The image NodeView is named "Image: <alt>", or "Image with no description".
+- A selected image shows the focus ring.
+- The alt field has its label.
+- The upload box is `role="group"`, named "Uploading <file>". Its `<progress>` is labelled.
+- A polite live region announces "Image added" or the failure.
+- Insert → Image is the keyboard path; drag and drop is never the only one.
+- **L10 gains:** a keyboard-only walk of Insert → Image (with the picker stubbed), the alt field, the bubble's Alt text, and Remove's confirm. axe-core then finds nothing serious on a page with images.
+
+---
+
+## 5. Formats and safety
+
+- **Allowed types:** PNG, JPEG, GIF (animation included) and WebP (animation included).
+ - **The type is decided from the bytes** (magic numbers, as Slides' `sniffImage` does). The claimed `Content-Type` and the file name are ignored.
+ - Then the format's own decoder reads the header (`image.DecodeConfig`: 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 that reason; Slides sanitises it, and that is a second parser to keep safe (Q1).
+ - HEIC, AVIF, TIFF, BMP, PDF and anything else.
+ - Each refusal is 415 with a sentence naming the four formats that are accepted.
+- **Metadata is stripped, without re-encoding.** A container walker in pure Go (`CGO_ENABLED=0`, so there is no WebP encoder, and re-encoding a JPEG loses quality) rewrites the file:
+ - **JPEG:** keeps the SOF, DQT, DHT, SOS and scan data, APP0 (JFIF), APP2 ICC and APP14 (Adobe). It drops APP1 (EXIF and XMP), APP13 (IPTC), COM and every other APPn. **Orientation is kept:** when EXIF said anything but 1, Mapa writes a minimal APP1 holding only the Orientation tag, so phone photos stay upright. The stored width and height are the ones after rotation.
+ - **PNG:** keeps the critical chunks, plus `iCCP`, `sRGB`, `gAMA`, `cHRM`, `pHYs`, `tRNS`, `bKGD`, `sBIT` and the APNG chunks. It drops `eXIf`, `tEXt`, `zTXt`, `iTXt`, `tIME` and unknown ancillary chunks.
+ - **WebP:** keeps `VP8`/`VP8L`/`VP8X`, `ALPH`, `ANIM`/`ANMF` and `ICCP`. It drops `EXIF`, `XMP ` and unknown chunks, and fixes VP8X's flags and RIFF's size.
+ - **GIF:** keeps the image data, the graphic control extensions and the `NETSCAPE2.0` loop. It drops comments, plain text and every other application extension (XMP rides in one).
+ - **Anything the walker cannot parse is refused,** not passed through. So location, camera serials, author names, edit history and thumbnails never reach the bucket.
+- **Limits:**
+ - 10 MiB of upload body, enforced with `http.MaxBytesReader` before any parse;
+ - at most 10,000 px on a side and 40 megapixels in all, from `DecodeConfig`, before any further work. Mapa never decodes pixels, so a decompression bomb costs nothing.
+- **Served safely** (§1.4): the stored type, `nosniff`, and `default-src 'none'; sandbox`.
+ - An image opened on its own is still an image on Mapa's origin, and cannot run anything.
+ - A polyglot (a JPEG with HTML after it) is served as `image/jpeg` with `nosniff`, so it cannot become a page.
+ - The page CSP is unchanged (`img-src 'self' data:`).
+- **Scanning** cannot read sealed objects, and Mapa never asks for it (Q5). The format allowlist, the strict walker and the sandboxed serving are Mapa's own defence.
+
+---
+
+## 6. Server changes
+
+| Change | Gate |
+|---|---|
+| **Migration `0005_images`:** `images` and `image_trash` (§1.3). The `public_id` index is unique, and there is an index on `(page_id)` and on `(owner, page_id)` | migration check; **gate 4**: `plaintext_test.go` names the new columns exactly, and the file scan (I2 below) |
+| **`seal` purposes `image` and `image-record`** | **gate 4** |
+| **`images.go`:** sniff, walk and strip, limits, seal, `Put`, row and event. One function serves the route and the importer (§7) | I5, I6 |
+| **`POST /images`:** upload. JSON for script; the Markdown screen's re-render without (§4.4) | I3, I6, L8 |
+| **`GET /i/{id}`:** scoped serving, 304, headers (§1.4) | **gate 1**, I1, **gate 10**/L7, I6 |
+| **`POST /images/copy`:** `{ids}` → `{id: new}`, only for ids the person may read | **gate 1**, I1, **gate 8** |
+| **`GET` and `POST /i/{id}/remove`:** confirm page and removal | **gate 8**, I7, L8 |
+| **`tx.commit` attaches** pending images owned by the person committing (§3.2) | I7, and a mutation: attach without the owner check |
+| **`MakeTeamPage` copies and rewrites; `Restore` re-points** | I7, L9 |
+| **`Store.Sweep` sweeps images and empties the trash** (§3.3) | I7, gate 8's named exemption |
+| **`markup.Image`, `Render` and the resolver;** the text index skips the address | L1–L4, I1 |
+| **Event vocabulary:** object kind `image`, verbs `uploaded` and `removed`. The index already reads only `object_kind = page` events (`index.go`) | **gate 8** |
+| **`config.go`:** `CARLOS_STORE_*` read through `blobs.S3FromEnv`; a partly delivered store refuses to boot; `MAPA_IMAGE_QUOTA_BYTES` | `config_test.go` |
+
+**New gates.** They run in `make ci` unless marked as browser gates.
+
+- **I1, scope** (extends gate 1 and L6). Ana has a private page with images, a pending upload, and a private image whose id is typed into a team page. Bo's view is byte-identical with or without each of these, across:
+ - the team page's HTML and its island;
+ - `GET /i/<Ana's id>`, which gives the same status, headers and body as an id that never existed;
+ - `POST /images/copy`.
+
+ Two `make mutate` mutants must each be caught: one drops the route's scope check, and one resolves images attached to other pages.
+- **I2, the plaintext file scan** (extends gate 4). The test uploads a PNG and a JPEG carrying canary strings in `tEXt`, EXIF, XMP and the file name, and uses a canary alt text. Then neither the database file (WAL included) nor the blob directory holds any canary, a PNG or JPEG magic number, or the alt text. The fake S3 records `Content-Type: application/octet-stream`.
+- **I3, events** (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 is caught.
+- **I4, nothing written by a GET** (extends gate 10 and L7). The row-dump hash is unchanged across `GET /i/{id}` (200 and 304), page views with images, the island, and the remove confirm page.
+- **I5, stripping.** For each format, the canary metadata and GPS are gone from what is served, while ICC and the JPEG orientation stay. The pixels are unchanged: Mapa decodes before and after in the test only. Truncated, oversized and malformed chunks are refused. A Go fuzz target on each walker runs its seed corpus in CI.
+- **I6, refusals and headers.**
+ - Refused: a type claimed but not true; SVG; HEIC; HTML; over 10 MiB; over 10,000 px or 40 MP; over the person's quota; no store (503); five uploads at once.
+ - Every served image carries §1.4's headers.
+- **I7, lifecycle.**
+ - Attach happens only for the committer's own pending images.
+ - Copy happens only for images the person can read.
+ - Make team page copies; Restore re-points.
+ - Removal makes the image unavailable everywhere, History included.
+ - The sweep keeps an image that a retained revision or a draft references. It removes a pending image after a day, and a deleted page's images after 90 days.
+ - 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, and Remove's confirm, with script off;
+ - L9: an upload in flight across autosave, commit, rebase 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. It uses the same function the route uses:
+
+```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. It never names Mapa as the actor.
+func (store *Store) AddImage(ctx context.Context, actor int64,
+ data io.Reader) (Image, error)
+
+// Image.Markdown(alt) is "![alt](/i/<public id>)", with alt cleaned to
+// the form §2.1 allows ([, ] and line breaks removed; at most 1,000
+// bytes).
+func (image Image) Markdown(alt string) string
+```
+
+**How the importer uses it:**
+- It calls `AddImage` for each image file in the Notion export, puts `image.Markdown(caption or alt)` into the page body, and then creates or commits the page through the ordinary verbs as that person. The commit attaches the images (§3.2).
+- **Typed refusals** tell the importer what to write in place of the image: `ErrImageType`, `ErrImageTooLarge`, `ErrImageDimensions`, `ErrImageQuota`, `ErrNoImageStore`. A refused image becomes a text line, `(Image not imported: <file name>, <reason>)`, so nothing vanishes silently.
+- **Notion's remote images** (an `https://` source 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 a day (§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, or the agent with Paul's say-so, runs these steps **after** the build is merged and deployed. Until then, upload answers 503 (I4).
+
+1. **Check the account's plan does not force scanning.** Slides' store has scanning "not requested" today, so the plan does not force it now.
+ - If the account is ever on a plan with `storage_scan_required`, the sealed store would be refused (`store.scan_required.encrypted`).
+ - Keep oficina on a plan, or a house account, that does not force scanning (Q5).
+2. **Declare the store** (and provision it, on an approved account):
+ ```sh
+ carlos store create --app mapa --account oficina
+ ```
+3. **If step 2 left it declared but not provisioned,** an operator (Paul) grants it:
+ ```sh
+ carlos store grant --app mapa --account oficina
+ ```
+4. **Check what was delivered:**
+ ```sh
+ carlos store status --app mapa --account oficina
+ ```
+ It should name bucket `carlos-store-bds-mapa`, and `delivers: CARLOS_STORE_BUCKET, CARLOS_STORE_REGION, CARLOS_STORE_ACCESS_KEY, CARLOS_STORE_SECRET_KEY`, with nothing still to reach the app's config.
+5. **Restart, so the process reads the 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 should say "mapa: object store bound".
+6. **Do not request scanning.** If anyone ever does, the honest attestation is:
+ ```sh
+ carlos store scan request --app mapa --client-encrypted
+ ```
+ That claims no coverage.
+7. **No CORS rule is needed:** no browser ever talks to the bucket.
+8. **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`).
+ - Under the new catalog, a plan that forces scanning refuses per-instance stores outright.
+
+---
+
+## 9. Deliberately not built
+
+| Thing | Trigger |
+|---|---|
+| Resized display copies (thumbnails, `srcset`) | Pages with photos feel slow on a phone. Today a 10 MiB photo is sent whole |
+| 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 |
+| A bucket reconcile (list the bucket, delete unknown keys) | `image_trash` misses something. Today only a crash between `Put` and its transaction can leave an orphan object |
+
+## 10. Open questions for Paul
+
+1. **SVG: refused or sanitised?** *Recommended: refused.* An SVG is a script-capable document served from Mapa's own origin. Slides' sanitiser exists, but it would be a second copy to keep safe. Notion pages rarely hold SVG.
+2. **The per-person quota.** *Recommended: 1 GiB per person and 10 MiB per image.* A team-wide quota would leak a count of private images.
+3. **Captions and sizing.** *Recommended: neither in v1.* Images show at natural size, capped at the column.
+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 naming them.
+7. **The sweep's events.** *Recommended: keep retention exempt from gate 8 by name*, as it is today. Removal by a person logs an event, but the sweep would have to name Mapa as the actor.
+
+---
+
+## 11. Findings and what changed
+
+*(Filled in by each review round.)*