oficina / mapa Public

Notion import design, revision 2: answer Fable's round 1

Import-only store methods with the map in the same transaction; staged
trees kept to the end of the run; literal-text neutralising with a
fallback; run lease, Stop and liveness; link syntax limits; provenance
cleared by every other verb; retirement order; A8-A11 for images.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev fda6c12654d376093cc805a69e538bea05367dd7 parent bb9b30d
1 file changed, +138 −61
  • docs/superpowers/specs/2026-11-17-notion-import.md +138 −61

CI passed — run details

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

added 16 packages in 314ms
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.956187ms)
ℹ 760 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (58.147468ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (90.967503ms)
ℹ 748 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (106.865836ms)
ℹ 755 inserts, 715 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (3113.033815ms)
ℹ 18240 edits over 760 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (957.630376ms)
ℹ 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 (21.280047ms)
✔ linear: trailing whitespace (11.459614ms)
✔ linear: unclosed web links (15.195177ms)
✔ linear: web links with no address (22.179216ms)
✔ linear: unclosed wiki links (22.960102ms)
✔ linear: unclosed embeds (13.540177ms)
✔ linear: closes only (4.494098ms)
✔ the selected words become the chip's shown text (9.696441ms)
✔ words that are the title make a plain [[Title]] (2.52234ms)
✔ spaces at the selection's edges stay outside the chip (0.908155ms)
✔ a date makes a date link, in a heading, an item and a quote (4.903334ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (0.787907ms)
✔ only the linked block's bytes change, and undo gives the body back (1.636305ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (0.828862ms)
✔ a target the words cannot be linked to as typed is refused (0.144981ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (1.521228ms)
✔ web-linked words are refused: the address would be lost (review M4) (0.686095ms)
✔ words whose Markdown would read otherwise are refused (review M3) (4.745981ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (0.303516ms)
✔ linkCheck says why it refuses (review low 2) (0.530545ms)
✔ golden file has bodies (0.948036ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (12.833706ms)
✔ markup.mjs strips and spans every block as Go does (27.818736ms)
✔ the schema's toDOM draws every body as Go renders it (39.427317ms)
✔ emphasis draws the four pinned outputs (12.144116ms)
✔ a body ends in the editor's empty paragraph (0.2056ms)
✔ a POST that never answers is aborted after the timeout (21.527463ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (1.165127ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (8.597252ms)
✔ an offered draft never commits by itself; Save commits it (1.22213ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.579182ms)
✔ closing carries text not yet sent, and the cap leaves it out (20.264019ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (3.019805ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (2.358846ms)
✔ typing mid-flight: the merge is not applied and the base does not move (0.954117ms)
✔ a merge the editor cannot represent stops after three tries (3.236965ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (1.170718ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (1.323492ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (0.773502ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (0.709317ms)
✔ noBase and gone lead to the existing choices (0.728531ms)
✔ a commit that merged is applied when nothing was typed since (0.86154ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (5.609426ms)
✔ an own draft committed meanwhile goes on as a new draft (1.190633ms)
✔ a reload keeps a stored draft; unsent text still commits (0.440472ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (0.849389ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (3.60069ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (1.030925ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (2.537207ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (0.847115ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.26075ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (0.750971ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.4166ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (0.540823ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (0.471669ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (0.499179ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (4.925766ms)
✔ marks close before code, links and atoms, and reopen after (0.377379ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (5.585443ms)
✔ empty blocks are written as nothing (1.835674ms)
✔ an unclosed fence that is no longer last gets its closing fence (1.199749ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (1.919144ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (3.161751ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (1.962181ms)
✔ a trailing hard break stays on screen and is written as nothing (0.472771ms)
✔ the reparse waits while an IME is composing (0.695682ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (2.993939ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.802194ms)
✔ rebuild changes origins only, outside undo history (1.37249ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (1.13362ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (1.564906ms)
✔ a duplicate ^id typed above its holder never takes the id from it (1.276678ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (0.874173ms)
✔ a history command that throws is refused, never thrown (2.943277ms)
✔ one rename at a time, from either field (1.474944ms)
✔ an empty or unchanged title sends nothing (0.131727ms)
✔ a refusal keeps what was typed, and the title (0.203827ms)
✔ the pending state holds for the busy rule (4.379341ms)
✔ a failed POST says so and keeps the title (0.360198ms)
✔ Update links posts the confirm page's POST (0.240723ms)
✔ clean is CleanTitle's whitespace rule (0.146043ms)
✔ the saver's base follows a rename made over it, and only that (0.230766ms)
✔ closing sends the rename as one keepalive POST (1.799488ms)
✔ a drag whose anchor the document no longer reaches selects to its end (4.593296ms)
ℹ tests 90
ℹ suites 0
ℹ pass 90
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4504.806007
=== 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	(cached)
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/markup	(cached)
ok  	amadan.net/oficina/mapa/internal/mapa/seal	(cached)
ok  	amadan.net/oficina/mapa/internal/mapatest	9.621s
?   	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-notion-import.md b/docs/superpowers/specs/2026-11-17-notion-import.md
index 67f5698..5375665 100644
--- a/docs/superpowers/specs/2026-11-17-notion-import.md
+++ b/docs/superpowers/specs/2026-11-17-notion-import.md
@@ -1,6 +1,6 @@
# Notion import: pages into Mapa, databases into Fichas later
-**Status:** revision 1, 2026-11-17, for review. **Paul approved the import on 2026-11-17**, with his 2026-11-14 defaults (§1) and one overrule: images come in as real Mapa images. Everything marked **Proposed** in this spec is the author's recommendation and has not been ruled. Nothing is built.
+**Status:** revision 2, 2026-11-17, for review. Revision 1 (`bb9b30d`) was reviewed by Fable (CHANGES REQUIRED: 3 high, 12 medium, 12 low); §24 records what changed. **Paul approved the import on 2026-11-17**, with his 2026-11-14 defaults (§1) and one overrule: images come in as real Mapa images. Everything marked **Proposed** in this spec is the author's recommendation and has not been ruled. Nothing is built.
**Branch:** `design/notion-import` (Mapa).
@@ -60,6 +60,8 @@ Three things follow, and each has a section:
| D12 | **Title collisions take the parent's name, then a number**: `Week 1`, `Week 1 (Onboarding)`, `Week 1 (Onboarding) 2` | Merging into an existing Mapa page with the same title | §9 |
| D13 | **Notion-hosted images are downloaded. External images stay links** | Fetching from any host on the internet | §12 |
| D14 | **memoria retires its connector once it is shown to hold no Notion documents**, before Mapa's producer is live if so, after it if not | Running both | §16 |
+| D15 | **Two import-only store methods, `ImportCreate` and `ImportUpdate`**, each one `Store.write` that checks, writes the page and writes the map together, and never merges | Calling `CreateTeamPage`, `Retitle` and `CommitFrom`, which merge on a stale base, mint a revision per step and cannot carry the provenance | §14.1 |
+| D16 | **Literal text that Mapa would read as markup is neutralised**, with a zero-width space at the one place that breaks the reading, and counted. A block that still fails the check is written as a fenced copy of its text | Accepting Mapa's reading; failing the page | §11.4 |
---
@@ -68,7 +70,7 @@ Three things follow, and each has a section:
memoria's connector (`internal/memoria/notion/`, spec 2026-09-05) was designed, reviewed twice by Fable and built. **It never ran against a real workspace.** Every lesson below came from reading Notion's documentation or from review, and every one of them is untested against Notion itself. §19's checklist is where that ends.
**Kept, as they are:**
-- **Traversal from shared roots, never `/v1/search` as an enumerator.** Search is used only to find the directly-shared roots, which Notion guarantees. Children come from `GET /v1/blocks/{id}/children`, cursor by cursor (memoria §6).
+- **Traversal from shared roots, never `/v1/search` as an enumerator.** Notion guarantees that search returns every page *directly* shared with the integration, but search also returns children of shared pages, unreliably. So search only proposes candidates: a result is a root when its parent is not itself in the results, and children come from `GET /v1/blocks/{id}/children`, cursor by cursor (memoria §6). A fixture where search leaks children (M2) holds this.
- **Roots and orphans are separate.** A page under a `block_id` parent looks like a root to search. Orphans are walked only after the real traversal drains (memoria §1.3, the blocker).
- **The total decoder.** `has_more` with no cursor, a repeated cursor, or a 429/529 past the retry budget fails the run. There is no partial result (memoria §6).
- **`Notion-Version` pinned as a constant, with a gate.** memoria pinned `2026-03-11`, which is real: it replaced `archived` with `in_trash` and renamed `transcription` to `meeting_notes`. Notion's changelog (2026-10-30) announces a later version, not yet named, that makes its Markdown output the default. The build re-reads the changelog and pins the version current then, with fixtures recorded against it.
@@ -98,7 +100,7 @@ memoria's connector (`internal/memoria/notion/`, spec 2026-09-05) was designed,
- `blocks.go` (new): the typed tree. A `Page` (id, title runs, parent, created and edited times, icon, `in_trash`) and its `Block`s (id, type, `last_edited_time`, `has_children`, the type's payload decoded into typed fields, children). Rich text is `[]Run`, each run with its text, its annotations (bold, italic, strikethrough, underline, code, colour), its link, and a typed mention (page, database, date, user, link preview, template, custom emoji) carrying its target id;
- `files.go` (new): the file fetcher (§5);
- `verify.go`: `GET /v1/users/me`.
-- `notiontest` — the fake server, exported so both apps run against it, and the fixture set (§18).
+- `notiontest` — the fake server, exported so both apps run against it, the fixture set (§18), and **the only constructor that takes a base URL**, `notiontest.Client(token, base)`. The production package exports `New(token)` and nothing that accepts a host. memoria's `NewForTest(token, base)` sat in the production package; lifted as it was, any caller could point the token at any host and no gate would notice. Both constructors share an internal package of the module, so the test client still goes through the pinned transport, pinned to the fake's host.
- `cmd/notion-record` — records a real workspace's responses for fixtures, and scrubs them (§18, §19).
**What does not go in the module:** any mapping into an app's model, any storage, any HTML. The module knows Notion. Mapa knows Mapa. Fichas will know Fichas.
@@ -119,12 +121,13 @@ memoria's connector (`internal/memoria/notion/`, spec 2026-09-05) was designed,
**Proposed (D2):**
- **Mapa's own tree stays clean.** A new gate, I8, walks `internal/mapa/**` and `cmd/**` and fails on `http.Client`, `http.Transport`, `http.Get` and its siblings, `http.NewRequest`, `net.Dial*` and `net.Resolver`. **No directory is exempt.** rastrillo's mail path lives in rastrillo.
-- **Only the module dials.** I8's second half reads `go list -deps` and fails if any package other than `internal/mapa` imports `amadan.net/oficina/notion.git/...`, and an AST check fails if any file other than `import_*.go` does.
+- **Only the module dials.** I8's second half reads `go list -deps` and fails if any package other than `internal/mapa` imports `amadan.net/oficina/notion.git/...`, an AST check fails if any file other than `import_*.go` does, and it fails if any non-`_test.go` file imports `notiontest`.
- **Two transports, both pinned in the module:**
- - **The API transport** refuses every host but `api.notion.com` and every scheme but `https` (two checks, two gates, memoria §1.2). The base URL is a constant. It refuses every redirect. It sends only `GET`, and `POST` to `/v1/search` (phase 1 never queries a data source). Any other method or path is refused before it dials, so the client cannot write to Notion even if a caller asks it to.
+ - **The API transport** refuses every host but `api.notion.com` and every scheme but `https` (two checks, two gates, memoria §1.2). The base URL is a constant. It refuses every redirect. It sends only `GET` (to `/v1/users/me`, `/v1/blocks/…`, `/v1/pages/…`), and `POST` to `/v1/search` (phase 1 never queries a data source). Any other method or path is refused before it dials, so the client cannot write to Notion even if a caller asks it to.
- **The file transport** fetches Notion-hosted files. It refuses every URL outside a constant allowlist of **(host, path prefix)** pairs. A host alone is not enough: Notion's documented example is `https://s3.us-west-2.amazonaws.com/secure.notion-static.com/…`, a path-style URL on Amazon's shared regional endpoint, where any AWS customer's bucket also lives. So the pin is that host *and* the `/secure.notion-static.com/` prefix, plus whatever pairs §19's first run finds Notion actually sending (a virtual-hosted bucket such as `prod-files-secure.s3.us-west-2.amazonaws.com` would be its own pair). It refuses every redirect. **It never sends the Notion token**, because a signed file URL needs none and a token in a request to a storage host is a token handed to a third party. It reads at most the images spec's size cap plus one byte, and fails on the extra byte (memoria AGENTS.md's detectable cap).
- **External URLs are never fetched.** An image or file whose Notion type is `external` stays a link (D13, §12). Fetching it would mean dialling any host a page names, which is a server-side request forgery surface, not a pin.
-- **Nothing dials unless a run is active.** The client is built when a run starts and dropped when it ends. Mapa does not poll Notion.
+- **Nothing dials except two things a person asks for:** the one verify call when a token is saved (§6), and an active run. The client is built for each and dropped after. Mapa does not poll Notion.
+- **Both transports also pin the port** (443, or none given), refuse a URL with userinfo, match the file path prefix on the *escaped* path, and give every request a total timeout of 60 seconds. memoria's transport compared `Hostname()` only.
**Leak list additions** (base §4 and the README):
- Mapa holds a Notion token while a connection exists, sealed (§6).
@@ -175,18 +178,19 @@ A run is started by an importer's `POST`, mounted inside the session and CSRF gr
- read its blocks, recursively, down to child pages, which are not entered from inside the body;
- **stage** what was read: the page's title, times, parent, and its block tree, sealed under `notion.staged`, on the ledger row;
- record the child pages found, which the walk visits next.
- - Pages whose parent is a database or data source are database rows. Phase 1 counts them and does not stage them (§17).
+ - **Database rows are not staged.** A search result whose parent is a data source is a row shared directly: it is skipped and counted. Phase 1 never queries a data source, so the rows *inside* a database are not counted: the report says "not counted until the databases move" (§8.5's rule), and names each database found.
+ - **A page beneath a database row** is not reached by the walk, which never enters a row. If search returns it, it is an orphan whose parent is not imported: it is imported without an `In:` line, and the report lists it.
- Trashed pages and blocks (`in_trash`) are skipped.
2. **Write.** With every page surveyed:
- assign titles across the whole set (§9.2);
- for each page, in survey order, render its body from the staged tree (§10, §11), fetch its new images (§12), and decide what to do (§13);
- - commit through Mapa's verbs (§14);
- - clear the staged tree once the row is written.
- - Then the fix-up pass (§13.6).
+ - commit through `ImportCreate` or `ImportUpdate` (§14.1);
+ - then the fix-up pass (§13.6), which renders again from the same staged trees.
+ - **Only when the run is `done` are the staged trees cleared**, in one bookkeeping write. A run that stops for any reason keeps them, so Resume can use them.
**Why two phases.** A `[[link]]` in Mapa is the target's title as text (base decision 9). Page A, written first, may mention page B, whose final title depends on collisions decided later. Writing A then would write a link to the wrong text. memoria never had this problem because its documents did not link.
-**What it costs.** Survey reads every block of every shared page on every run, because child pages are found only inside their parent's blocks (memoria §1.2). The staged trees sit sealed in the database until Write consumes them.
+**What it costs.** Survey reads every block of every shared page on every run, because child pages are found only inside their parent's blocks (memoria §1.2). The staged trees sit sealed in the database until the run is done.
### 8.2 Rate
@@ -196,11 +200,15 @@ A run is started by an importer's `POST`, mounted inside the session and CSRF gr
### 8.3 Resuming
-- **Single-flight.** One run at a time per instance, held by a conditional update on `notion_runs`.
+- **Single-flight, with a lease.** One run at a time per instance. Starting or resuming a run draws a random **lease** and writes it to the run's row with a conditional update. **Every page transaction checks the lease** and fails if it has changed. So a goroutine that has been reclaimed cannot write another page: its next transaction fails and it exits. Two goroutines can never write the same ledger.
- **At boot,** a run in `surveying` or `writing` becomes `interrupted`. No run can be live at boot (memoria §9).
-- **A heartbeat every 20 seconds.** A run whose heartbeat is older than two minutes, in a live process, may be reclaimed by the next Start (memoria §1.3: time, not pages).
+- **Liveness is time and progress.** A 20-second ticker writes `heartbeat_at` (memoria §1.3), and every page written or surveyed writes `progress_at`. A run may be reclaimed by Resume when its heartbeat is older than two minutes **or** its progress is older than ten minutes. A ticker alone would keep a wedged run alive forever.
+- **The goroutine recovers its own panics** and ends the run `failed` with `internal`, so a crash never leaves a run that looks alive.
+- **Stop** is a button while a run is active. It cancels the run's context. The run ends `stopped`, which offers Resume like `interrupted`.
+- **Disconnect, Finish and Forget are refused while a run is active.** Their pages say "Stop the run first". The run holds the token and reads the staged trees and the map.
+- **Resume and Start.** After `interrupted` or `stopped`, the page offers Resume, which continues the same run with its staged trees. Start is offered only after `done` or `failed`; a failed run's staged trees are cleared when the next run starts.
- **Resuming a survey** walks the pages already surveyed *in this run* from their staged trees, with no requests, and asks Notion only for the rest. This is cheaper than memoria's resume, which repeated the whole traversal.
-- **Resuming a write** continues from the rows still `staged`. Each page's write is one transaction, so a page is written or it is not.
+- **Resuming a write** continues from the rows still `staged`. Each page's write is one transaction that also writes its map row (§14.1), so a page and its record in the map land together or not at all. A crash between two pages can never make a second copy on Resume.
- An interrupted run says so, with Resume. It never shows as finished.
### 8.4 Progress, and the scriptless floor
@@ -211,12 +219,12 @@ A run is started by an importer's `POST`, mounted inside the session and CSRF gr
- Survey: "Reading Notion: 412 pages so far." **The total is not known until the survey ends, and the page says so.** It never shows a total of 0 or a percentage (memoria §1.2).
- Write: "Writing pages: 120 of 1,930." Now the total is known.
- Interrupted: "Stopped at 412 pages. Resume." Failed: the code's own sentence, never Notion's message.
-- **Start, Resume, Disconnect and Finish** are form buttons, with estilo's busy rule. Disconnect and Finish have their own confirm pages.
+- **Start, Resume, Stop, Disconnect and Finish** are form buttons, with estilo's busy rule. Disconnect, Finish and Forget have their own confirm pages.
### 8.5 The report
The run's report is for importers only. It unseals titles to show them.
-- **Counts:** roots found (named), pages seen, created, updated, renamed, unchanged, **kept because edited in Mapa**, **deleted in Mapa** (not re-created), **not found in Notion this time**, failed (with codes), database rows left for Fichas, images imported, images left as links, images failed, blocks not imported (by type), links to pages not shared with the integration.
+- **Counts:** roots found (named), pages seen, created, updated, renamed, unchanged, **kept because edited in Mapa** (split into "edited" and "only links updated", read from the page's last event verb, so a teammate's "Update links" is visible as the reason), **deleted in Mapa** (not re-created), **not found in Notion this time**, **could not be determined** (pages beneath a page whose survey failed), failed (with codes), databases found, database rows shared directly, images imported, images left as links, images failed (by reason), blocks not imported (by type), blocks written as a fenced copy (§11.4), text neutralised (§11.4), links to pages not shared with the integration.
- **Lists,** each title a link to the Mapa page where there is one: titles changed to fit Mapa (§9.2), pages kept, pages failed, pages not found this time, pages holding a placeholder (§10).
- A count that could not be determined says so. It never renders as 0 (memoria AGENTS.md).
@@ -239,6 +247,7 @@ The run's report is for importers only. It unseals titles to show them.
- Its title is the Notion title, made to fit (§9.2).
- Its sealed record carries the Notion times (§14).
- The page's icon and cover are not imported. They are counted.
+- Notion returns at most 25 mentions inside a title on the page object. A title at that limit is read in full from the page property endpoint (`GET /v1/pages/{id}/properties/title`), which M4's path pin allows.
### 9.2 Titles
@@ -247,26 +256,28 @@ A Mapa title must be unique across titles and aliases after case and accent fold
**Making a title fit** (applied in this order, deterministic, and each change listed in the report):
1. `[` and `]` become `(` and `)`. `|` becomes `/`. `#` followed by a digit is removed (`Issue #42` → `Issue 42`); any other `#` becomes a space. `^` is removed. Runs of spaces collapse.
2. An empty title is `Untitled`.
-3. Over 120 characters: cut at the last word boundary before 119, then `…`.
+3. Over 120 characters: cut at the last word boundary that leaves room, then `…`.
4. Date-shaped (`2024-03-05`): §9.3.
+**Every comparison is on `Fold()`ed text** (case and accent folded, `namespace.go`), as the store's title print is: "free", "planned for another page" and "date-shaped" all fold first, and the date test runs on the fitted title.
+
**Collisions (D12).** Candidates in order, the first one free in the namespace and not planned for another page in this run:
1. the title;
2. the title, then the parent's (fitted) title in brackets: `Week 1 (Onboarding)`;
3. the same, then ` 2`, ` 3`, and on.
-A root page has no parent, so its second candidate is `Week 1 (Notion)`.
+A root page has no parent, so its second candidate is `Week 1 (Notion)`. **A candidate never exceeds 120 characters:** the base title is cut, with `…`, to leave room for the bracket and the number before they are added.
- **An existing Mapa page with the same title is never merged into.** Mapa's `Acme` is somebody's page. Notion's `Acme` becomes `Acme (Notion)` and the report lists it.
- **Assignment is deterministic.** Survey order is the roots sorted by Notion `created_time` then id, then block order inside each page. The same workspace gives the same titles.
-- **Titles already assigned are kept.** On a re-run, a mapped page keeps its Mapa title unless Notion's title changed (§13.3).
+- **Titles already assigned are kept.** The map stores the Notion title as Notion last gave it, sealed (§15). On a re-run a mapped page is renamed only when Notion's title differs from that stored one (§13.3). So `Acme (Notion)` never flips back to `Acme` because `Acme` has since become free.
- **The namespace check is the store's.** The import proposes a title and the create or rename verb decides, so a member who takes a title mid-run makes the verb refuse it, and the import takes the next candidate (§13.6).
### 9.3 Date-titled pages
A Notion journal often titles pages by date. Mapa reserves date-shaped text for daily notes (base §3.4), which are private to one person.
-**Proposed:** such a page becomes a team page titled `2024-03-05 (Notion)`, and its first line after the parent line is the date link `[[2024-03-05]]`. Every member's daily note for that day then lists it under its backlinks (base build note 14), which is where a person looking at that day would look. **Q3 asks Paul.**
+**Proposed:** such a page becomes a team page titled with the date and its parent's title, `2024-03-05 (Journal)`, or `2024-03-05 (Notion)` for a root, then numbered on collision as §9.2. Its first line after the parent line is the date link `[[2024-03-05]]`. Every member's daily note for that day then lists it under its backlinks (base build note 14), which is where a person looking at that day would look. **Q3 asks Paul.**
### 9.4 Parent and child (D11)
@@ -294,14 +305,14 @@ Mapa has no tree. Notion's tree becomes links, both ways:
| `bulleted_list_item` | `- ` item. Nested items indent two spaces per level | — |
| `numbered_list_item` | `1. ` item, numbered in sequence within each run of items at each depth | Notion's own start number, if it has one |
| `to_do` | `- [ ] ` or `- [x] ` | — |
-| a list item's non-list children (a paragraph, a code block) | a paragraph child becomes a continuation line of the item (a hard break). A code block, quote, heading, table or image child is written after the list, at top level | the nesting of those blocks (counted) |
+| a list item's children | nested list items and to-dos nest. A paragraph child becomes a continuation line of the item (a hard break). **Every other child** (code, quote, callout, heading, table, image, toggle, `child_page`, embed, equation, columns, anything) is written by its own row of this table **straight after that item**, which ends the list there; the next sibling item starts a new list. Q10 asks Paul | the nesting of those blocks (counted). Mapa draws an ordered list from 1, so a numbered list split this way shows its later steps from 1 again, though the stored numbers are right |
| a paragraph's children (Notion's indented blocks) | written after it, at top level | the indent (counted) |
| `toggle` | a paragraph of the summary in `**bold**`, then its children as ordinary blocks after it | the collapse (counted) |
-| `quote` | `> ` quote, one `>` line per line of text. Children's text follows as more `>` lines | the children's own block shapes (a list inside a quote is its text) |
-| `callout` | `> ` quote, the icon's emoji first if it is an emoji: `> 💡 Remember…`. Children's text follows as more `>` lines | the colour, a custom or file icon (counted) |
+| `quote` | `> ` quote, one `>` line per line of text. **Text children** (paragraphs, list items, to-dos) follow as more `>` lines, a list item as `> - item`. **Every other child** is written by its own row of this table straight after the quote | the children's block shapes inside the quote; hoisted children (counted) |
+| `callout` | as `quote`, the icon's emoji first if it is an emoji: `> 💡 Remember…` | the colour, a custom or file icon, hoisted children (counted) |
| `code` | a fence: ```` ``` ```` plus the language (lowercased, spaces to `-`; `plain text` gives none). If the code holds a line starting ```` ``` ````, the fence is `~~~`. If it holds both, the block is written as a placeholder with the code in it (counted). The caption, if any, follows as an `*italic*` paragraph | — |
| `divider` | `---` | — |
-| `table`, `table_row` | pipe-table text, one paragraph: a header row, a `\| --- \|` row when Notion marks a header, then one line per row. Mapa shows it as lines of text (level-up D10) and the vault export renders it as a table. A cell's line breaks become spaces; a `\|` inside a cell becomes `/` | layout, column and row header styling. A table that needs sorting or typed columns belongs in Fichas |
+| `table`, `table_row` | pipe-table text, one paragraph: a header row, a `\| --- \|` row when Notion marks a header, then one line per row. Mapa shows it as lines of text (level-up D10); a future vault export (base decision 15, not built) would render it as a table. A cell's line breaks become spaces; a `\|` inside a cell becomes `/` | layout, column and row header styling. A table that needs sorting or typed columns belongs in Fichas |
| `column_list`, `column` | each column's blocks in order, left to right | side-by-side layout (counted) |
| `tab` (a tabbed container) | each tab in order: its label as a `**bold**` paragraph, then its blocks | the tabs (counted) |
| `synced_block`, original | its children, in place | that it is synced (counted) |
@@ -349,13 +360,16 @@ Each placeholder's Notion id is recorded, sealed, on the ledger row, so phase 2
| colour, background colour | the text alone | the colour (counted) |
| link (`href`) | §11.3 | — |
+**A marked run holding a literal `*` is written without its mark** (counted). Mapa's strong and emphasis patterns exclude `*` inside (`markup/render.go`), so `**5*3**` would show raw stars. Where bold is only partly italic, the mapper writes the editor's form, `**a** ***b*** **c**` (level-up §6.3).
+
**Marks never cross a link, a mention or code** in Mapa (level-up §6.3). The mapper closes a mark before them and reopens it after. A bold link is a link. Whitespace at a mark's edge moves outside its delimiters, because a closing `*` needs a non-space before it.
### 11.2 Mentions
| Mention | Mapa |
|---|---|
-| page, imported | `[[Mapa title]]`, or `[[Mapa title\|shown]]` when Notion showed different text |
+| page, imported and live in Mapa | `[[Mapa title]]`, or `[[Mapa title\|shown]]` when Notion showed different text |
+| page mapped but not live: deleted in Mapa, or failed in this run | its text, plain, counted. A deleted page's title is free, and a link typed with it would bind to whatever page takes it next (base §3.4). A failed target heals on the run where it succeeds (§13.5, §13.6) |
| page, not shared with the integration | Notion returns only the id, with the text `Untitled`. Mapa writes `(a Notion page not shared with the import)`, plain, and counts it under "links to pages not shared". Its id is recorded sealed, so a later run can link it (§13.5) |
| page that is a database row | its text, plain, counted under "database rows" (§17) |
| database | its text, plain, counted. An unshared one reads `Untitled` from Notion and is written like an unshared page |
@@ -373,17 +387,28 @@ Each placeholder's Notion id is recorded, sealed, on the ledger row, so phase 2
- **A Notion page URL** (`notion.so/…`, `www.notion.so/…`, a workspace's `*.notion.site/…`, or a bare `/…`), whose last 32 hex digits are the id of an imported page, becomes a `[[link]]` with the run's text as shown text. A link to a block inside it (`#…`) becomes a link to the page, counted.
- **A Notion URL to a page that is not imported** stays a web link while it is `https`. It works for people with Notion access until switch-over, and the report lists it under "links still pointing at Notion".
- **Any other link** is `[text](url)` when `markup.SafeURL` accepts it, and the text alone otherwise (counted). Mapa never makes `javascript:` or `data:` clickable, and the import adds no way round that.
+- **Link syntax has limits, and the mapper writes inside them** (`markup/scan.go`): a web link's address may hold no `)` or whitespace, and its label no `]` or line break; a wiki link's shown text may hold no `[`, `]`, `|` or line break. So the mapper always writes the `[text](url)` form, never a bare URL; percent-encodes `(`, `)` and whitespace in the address; and in labels and shown text turns `[` `]` into `(` `)`, `|` into `/`, and line breaks into spaces. `https://en.wikipedia.org/wiki/Foo_(bar)` is written `…/Foo_%28bar%29`.
+
+### 11.4 Literal text Mapa would read as markup (D16)
-### 11.4 Literal text Mapa would read as markup
+Mapa has **no escapes** (level-up D11). The editor accepts that because a person typing `*word*` sees what it becomes. An import has nobody watching, and Notion text that discusses Markdown or code is ordinary. Left alone, a Notion line beginning ```` ``` ```` would open a fence that runs to the end of the page (`markup/blocks.go`: an unclosed fence has no end), and two stray backticks would pair up and swallow a link between them (`markup/spans.go`, `codeSpan`).
-Mapa has **no escapes** (level-up D11): a literal `*word*` becomes emphasis, as it would if typed. The import follows that rule, with three exceptions where Mapa's reading would write into the namespace, the embed rules or block anchors:
-- **`[[` and `![[`** in Notion's literal text would make a link or an embed reference. The mapper writes the run as inline code. A run that also holds a backtick has a space inserted between the brackets (`[ [`).
-- **A trailing ` ^word`** would make a block marker. Same treatment.
-- **A bare `http(s)://` in text** already becomes a link in Mapa, and stays one.
+**"Meant" is computed first.** Before writing a block, the mapper decides what it means: the block's kind and level, its lines, and its inline parts (literal text, marks, links, mentions, code spans). The check (D9) compares `markup.Parse` and `markup.Spans` of the written block with that, part for part. Literal text must parse as literal text.
+
+**Neutralising.** Mapa has no escape character, so the mapper uses one invisible character, **U+200B ZERO WIDTH SPACE**, at the single place that breaks each reading, and one look-alike for backticks. Each use is counted and the report lists the pages. Go's `TrimSpace` and JavaScript's `trim` both leave U+200B alone, and Go's `\s` does not match it, so the parser and the editor's port agree (level-up §6.4's parity hazards; a corpus case each).
+
+| Literal text that would be read as | Where it is checked | Written as |
+|---|---|---|
+| a block start at the beginning of any line of a block: a fence (```` ``` ````, `~~~` after any spaces), a heading (`# `), a list item (`- `, `* `, `+ `, `1. `, `1) `), a quote (`>`), a rule (`---`, `***`, `___`) | every line, the first and every hard-break continuation | U+200B before the line's first non-space character. The line looks the same and stays inside its block |
+| `[[` or `![[` | the block's joined literal text, **across run boundaries** (`[[Acme` in a bold run then `]]` in the next is caught) | U+200B between the two `[` |
+| a trailing ` ^word` (a block marker) | the block's last line | U+200B before the `^` |
+| a backtick | any literal text | U+02CB MODIFIER LETTER GRAVE ACCENT (ˋ), which looks like one. A code-annotated run is the only source of real code spans |
+| a bare `http(s)://` | — | left alone: Mapa links it, and Notion usually had |
+| `*` | — | left alone. A literal `*a*` becomes emphasis, as in the editor (D11). A marked run holding `*` loses its mark (§11.1) |
-Everything else Mapa reads differently is accepted and counted: a paragraph that starts `1. ` becomes a list item, `# ` a heading, `> ` a quote, and `*a*` emphasis. The report lists the pages. A Notion user who typed those meant, nine times out of ten, what Mapa shows.
+**Headings with line breaks.** A Mapa heading is one line. The mapper joins a heading's lines with a space.
-**The structure check (D9).** After a body is rendered, `markup.Parse` must give exactly the blocks the mapper meant, in kind, level and order, with the links and embeds it meant and no others. A body that fails is not written: its page fails with `render_failed`, and a gate (I1) fails on any fixture that produces one. A wrong body is worse than a failed page, because a failed page says so.
+**The fallback.** A block whose written form still fails the check, which means the mapper has a bug, is not dropped and does not fail the page. It is written as a placeholder line, `> From Notion: this block couldn't be copied exactly. Its text follows.`, then a fence holding the block's plain text. The fence is ```` ``` ````, or `~~~` if a line of the text starts with ```` ``` ````; a line starting with the chosen fence gets U+200B first, so the fence always closes. The report counts these, and I1 fails on any fixture that produces one. **A page fails with `render_failed` only if the fallback itself fails the check.**
## 12. Images
@@ -398,11 +423,15 @@ Everything else Mapa reads differently is accepted and counted: a paragraph that
- **A5, alt text.** An image carries alt text. The import uses the Notion caption.
- **A6, sealed.** Image bytes are sealed under their own purpose, and base §4's list gains whatever the images spec makes plaintext.
- **A7, lifetime.** An image is kept while any revision in the window references it, so an import update that replaces an image leaves the old one to retention.
+- **A8, scope.** The images spec says whether a reference is valid on any page or only on the page it was added to. If only that page, `notion_images` is keyed by (block, page), and a Notion block that moves to another page is downloaded again.
+- **A9, existence.** The store can say whether an image reference still resolves, so an image retention removed is fetched again rather than referenced dead.
+- **A10, caps beyond one image.** The images spec says whether there is a per-page or per-team total. An image over any cap becomes a placeholder, counted by reason.
+- **A11, the event.** The image verb's event name is the images spec's. It enters the plaintext log, so it goes in base §4's list there.
**What the import does:**
-- **When:** during Write, for each image block that is new or whose `last_edited_time` changed since its last import. Notion's file URLs are signed and expire after about an hour, and Survey may finish long after it read the block. So Write fetches the block again (`GET /v1/blocks/{id}`) for a fresh URL, then downloads it through the file transport.
+- **When:** during Write, before the page's transaction, for each image block that is new or whose `last_edited_time` changed since its last import. Notion's file URLs are signed and expire after about an hour, and Survey may finish long after it read the block. So Write fetches the block again (`GET /v1/blocks/{id}`) for a fresh URL and downloads it through the file transport **before** opening the page's transaction, holding the bytes in memory; the transaction then adds the images and writes the page (A2). No network call happens inside a transaction.
- **Unchanged images are not downloaded again.** `notion_images` maps a Notion block to the Mapa image it became (§15). An unchanged block reuses it.
-- **A failure is not the page's failure.** An image that fails (host refused, too big, a format the images spec refuses, a 403 from an expired URL) becomes a placeholder, and the page is written. The report counts it by reason.
+- **A failure is not the page's failure.** An image that fails (host refused, too big, a format the images spec refuses, a 403 from an expired URL) becomes a placeholder, and the page is written. The report counts it by reason. **A permanent failure is recorded** in `notion_images` with the block's edit time, and is not downloaded again until the block changes. A transient one (network, 429, 5xx) is tried again on the next run.
- **External images** stay links (D13). **Q2** asks Paul whether he wants a second, stricter fetcher for them: public addresses only, `https`, the same caps, no cookies. It would be the first fetch from a host a page chooses, and it is not proposed here.
## 13. Re-runs and idempotency
@@ -418,23 +447,24 @@ For each mapped page on a re-run:
| Mapa page | Notion page | What happens |
|---|---|---|
| revision is still the one the import wrote | rendered body and title equal what Mapa holds | nothing. No revision, no event |
-| revision is still the one the import wrote | changed | **updated**: a commit, and a rename if the title changed (§13.3), as the person running this run |
+| revision is still the one the import wrote | changed | **updated** by `ImportUpdate` (§14.1): body and title in one revision, as the person running this run |
| any later revision | anything | **kept**. Mapa's version stays whole. Listed in the report |
| deleted in Mapa | anything | **not re-created.** Deleting it was a decision in the app of record. Listed |
| restored as a new page | anything | the map still names the old, deleted page, so it is "deleted in Mapa". The restored page is an ordinary Mapa page |
- **"Changed" is decided by the rendered output**, not by Notion's edit time. Survey reads every block anyway (§8.1), so rendering again costs no requests. That makes a title change in a mentioned page, a page newly shared, a move, or a mapper fix all reach the pages they affect, which an edit-time comparison would miss (memoria §1.1: an ancestor's rename never moved a child's edit time).
- **Any later revision means edited**, a rename and "Update links" included. A rename leaves the body alone, but the person chose the page's Mapa name, and an import that renamed it back would undo a choice.
-- **A teammate's open draft does not stop an update.** Their draft's base is the import's revision, and their next commit merges against the update by base §5's block merge, as it would against a teammate's save.
+- **The check and the write are one transaction.** `ImportUpdate` reads the page's revision and `gone` inside its own `Store.write` and, if either has moved since the decision, writes nothing and records the page as kept. It never merges. Mapa's ordinary commit would merge Notion's change into a teammate's save that landed in between (`commit.go`, `merged`), which this table rejects.
+- **A teammate's open draft does not stop an update.** Their draft's base is the import's revision, and their next commit merges against the update by base §5's block merge, as it would against a teammate's save. The import never touches drafts.
- **Rejected: merging Notion's change into Mapa's edit.** Mapa has the three-way merge. But P6 says Mapa's version is kept where edited, and a merge that happens unseen in a run is a write nobody chose (base §5: "Nothing is committed that nobody chose").
### 13.3 Renames
-A Notion rename on an untouched page goes through Mapa's rename verb: the old title becomes an alias, so every link typed with it still resolves (base §3.4). The new title goes through §9.2's fitting and collision rules. Pages that link to it are re-rendered, and their links use the new title where those pages are untouched.
+A Notion rename on an untouched page is part of `ImportUpdate`'s one revision, using the same namespace code the rename verb uses: the old title becomes an alias, so every link typed with it still resolves (base §3.4). The new title goes through §9.2's fitting and collision rules. Pages that link to it are re-rendered, and their links use the new title where those pages are untouched.
### 13.4 Absence
-**Never delete on absence (P6).** A page that a complete survey does not find (unshared, moved out of the shared tree, trashed, deleted, or the token revoked) is left as it is in Mapa. Its row's `seen_run` stops moving, and the report lists it under "not found in Notion this time". Absence is reported only after a **complete** survey: an interrupted one proves nothing about what it did not reach.
+**Never delete on absence (P6).** A page that a complete survey does not find (unshared, moved out of the shared tree, trashed, deleted, or the token revoked) is left as it is in Mapa. Its row's `seen_run` stops moving, and the report lists it under "not found in Notion this time". Absence is reported only after a **complete** survey: an interrupted one proves nothing about what it did not reach. Pages beneath a page whose own survey failed are "could not be determined", never "not found".
### 13.5 Links that heal
@@ -442,15 +472,26 @@ A mention of a page that was not shared is plain text on the first run, and its
### 13.6 The fix-up pass
-Write commits pages one at a time while members may be using Mapa. If a member creates a page with a title the import had planned for another page, the create verb refuses it and the import takes the next candidate. Pages written earlier in the run that linked to the planned title would then point at the member's page. So after Write, the import re-renders every page it wrote in this run that links to a page whose title changed from its plan, and commits again where the page is still untouched. The report counts these. The race needs a member to type the exact title during a run, so this is expected to do nothing.
+Write commits pages one at a time while members may be using Mapa. If a member creates a page with a title the import had planned for another page, the create verb refuses it and the import takes the next candidate. Pages written earlier in the run that linked to the planned title would then point at the member's page. So after Write, the import re-renders, from the staged trees (§8.1), every page it wrote in this run that links to a page whose outcome differed from its plan (a different title, or a failure), and commits again through `ImportUpdate` where the page is still untouched. The report counts these. The race needs a member to type the exact title during a run, so this is expected to do nothing.
## 14. History and events
-- **Every import write is an ordinary Mapa write**, through `Store.write`, in one transaction with its event (gate 8). The verbs are Mapa's existing ones: `created`, `edited`, `renamed`. The actor is the person who pressed Start or Resume (P7). **Mapa is never an actor** (base §2).
-- **No new verb.** An `imported` verb would put "this page came from Notion" into the plaintext event log. The provenance goes in the sealed record instead.
+### 14.1 The two store methods (D15)
+
+The import writes pages only through two methods in package `mapa`, each **one `Store.write`**:
+- **`ImportCreate`** checks the lease (§8.3), claims the title through the same namespace code `CreateTeamPage` uses (refusing a taken or date-shaped title exactly as it does), creates the page with its record (`origin`, `imported`), adds its images (A2), writes the map row's coordinate, and logs `created`.
+- **`ImportUpdate`** checks the lease, re-reads the page, and writes nothing (outcome *kept*) if its revision is not the one the map holds or it is gone. Otherwise it writes title and body as **one revision**: a changed title goes through the rename verb's namespace code (old title to alias), and the event is `renamed` when the title changed, `edited` when only the body did. It adds images, updates the coordinate's revision, and never touches drafts.
+- Neither merges, and neither can be called from a handler: only the run calls them, and a gate (I17) fails if anything else does.
+- **A gate kills the run between every pair of statements** in both methods and in the run loop, resumes, and expects no second page, no false *kept*, and a map that agrees with the pages (I17).
+
+### 14.2 What history records
+
+- **Every import write is a Mapa write** in one transaction with its event (gate 8). The verbs are Mapa's existing ones: `created`, `edited`, `renamed`. The actor is the person who pressed Start or Resume (P7). **Mapa is never an actor** (base §2).
+- **No new verb.** An `imported` verb would add nothing the sealed record does not say. It would also not hide much: see §15 on what the plaintext already shows.
+- **Bookkeeping is a third named exemption from gate 8**, beside drafts and retention (base §5): run rows, heartbeats, progress, staging, clearing staged trees, and ledger state that changes no page. A page write is never bookkeeping. **The person's own acts on the connection do log events**, under a new object kind, `import`, naming the person: `connected`, `token_replaced`, `disconnected`, `finished`, `forgotten`, `started`, `stopped`. S1 and the index ignore object kind `import`. §21 records the exemption and the object kind as amendments to base §3.1 and §5.
- **The sealed record gains two optional fields** (base §3.1's `Record`, JSON, additive):
- - `origin`: `{source: "notion", created, edited}`, Notion's own created and last-edited times for the page. Set by the import, and carried forward unchanged by every later commit, so a page always knows where it came from, even after its imported revision ages out of the 90-day window.
- - `imported`: `true` on a revision the import wrote. Not carried forward.
+ - `origin`: `{source: "notion", created, edited}`, Notion's own created and last-edited times for the page. Set by the import, and carried forward by every later commit, so a page always knows where it came from, even after its imported revision ages out of the 90-day window. Every verb already opens the record, changes it and seals it again (`CommitFrom`, `Retitle`, `Revert`, `Restore`, relink, markers), so carrying `origin` needs nothing. A page restored from a deleted imported page keeps `origin`: its text did come from Notion. The map does not follow it (§13.2).
+ - `imported`: `true` on a revision the import wrote. **`tx.commit` clears it on every write unless the caller is `ImportCreate` or `ImportUpdate`.** The verbs carry the whole record forward by default, so without that one line a teammate's edit would read "imported from Notion". Gate I18 runs every verb on an imported page and checks it is cleared and `origin` kept.
- **History shows it** (level-up §4.5): a revision with `imported` reads "Paul imported this from Notion · edited there 12 Oct 2026". The page's kicker may show "From Notion, created there 3 Mar 2024". Both read sealed fields, at render, for people who may open the page.
- **S3 does not change.** S3 serves the title and body (base §8), not the record's other fields. memoria sees an imported page exactly as it sees any page.
- **Revision `at` is the import's time**, never Notion's. The history window, retention, S1's order and "Recently edited" all count from Mapa's clock (base build note 30). Notion's times are history's content, not its clock.
@@ -467,9 +508,10 @@ Write commits pages one at a time while members may be using Mapa. If a member c
|---|---|---|---|
| `notion_connections` (one row) | `id`, `created_by` (member id), `created_at`, `verified_at` | token, workspace name | that a Notion connection exists, who made it, when it was last checked |
| `notion_runs` | `id`, `actor`, `state`, `started_at`, `heartbeat_at`, `finished_at`, the counters, `error_code` | — | when imports ran, who ran them, how many pages each created, kept, failed |
-| `notion_pages` (the map) | `id`, `notion_print` (unique), `state`, `error_code`, `surveyed_run`, `seen_run`, `updated_at` | the coordinate record; the staged tree | how many Notion pages exist and their states. **Not which Mapa page each became**: the Mapa page id and revision are sealed, so the file does not mark which team pages came from Notion |
+| `notion_pages` (the map) | `id`, `notion_print` (unique), `state`, `error_code`, `surveyed_run`, `seen_run` | the coordinate record (Notion id, last Notion title, Mapa page id, last written revision, unresolved mention ids, placeholder ids); the staged tree | how many Notion pages exist and their states |
| `notion_images` | `id`, `block_print` (unique) | the image record | how many images were imported |
+- **What the file still shows, said plainly.** The coordinate is sealed, so no column joins a ledger row to a Mapa page. **But the plaintext event log does.** A run's `created` events, by the run's actor, inside the run's window in `notion_runs`, mark which team pages it made, and sequential `pages.id` and `notion_pages.id` in survey order line them up row for row. So the file shows **which team pages came from a Notion import, and roughly their order in Notion**. It does not show their titles, bodies or Notion ids. This goes in the leak list. `notion_pages` carries no `updated_at`, which would be a second join.
- **Prints are HMACs under the instance key**, equality only, as every print in Mapa (base §4).
- **The staged tree is content**, held sealed between Survey and Write, then cleared. Finish deletes any that remain.
- **No Notion content in any log line, error string or metric label** (gate I10, memoria N13). The fake's error bodies carry a canary title and id so the error path is exercised.
@@ -485,17 +527,18 @@ Write commits pages one at a time while members may be using Mapa. If a member c
4. **memoria is hooked up to Mapa**: Paul approves the hookup (open in memoria's follow-ups), and memoria's sibling list gains Mapa with a consumer token.
5. **memoria finds an imported page**: a phrase from an imported page answers in memoria's search, cited to Mapa.
-**What the retirement is:**
-- remove `/connectors/notion` and its handlers, `connector.go`, `sync.go`, `internal/memoria/notion/`, and the "Sources" entry where it leads only there;
-- **narrow memoria's egress gate back**: the `internal/memoria/notion` exemption is deleted, so the provider package is the only exemption left;
-- delete any Notion credential row and any `Source = "notion"` documents, through memoria's own delete;
-- leave the tables (memoria's migrations are additive-only), unused;
+**What the retirement is, in this order:**
+1. **Check live memoria**, signed in as an owner: `/connectors/notion` shows whether a connection exists and every run's counts. Also count documents with `Source = "notion"` through memoria's document list (or a one-off read-only query by the operator). Record what was found.
+2. **On live, with the code still deployed:** Disconnect (deletes the token row) and delete any Notion documents through memoria's own delete.
+3. **Verify zero:** no connection, no Notion documents.
+4. **Then one commit** removes `/connectors/notion` and its handlers, `connector.go`, `sync.go`, `internal/memoria/notion/`, and the "Sources" entry where it leads only there, and **narrows memoria's egress gate back**: the `internal/memoria/notion` exemption is deleted, so the provider package is the only exemption left;
+5. leave the tables (memoria's migrations are additive-only), unused;
- mark memoria's Notion spec **superseded by this one**, and amend its parent's §11 (slice 3) and §4.2 to say Notion arrives through Mapa;
- grep memoria for `notion` by name before calling it done (memoria AGENTS.md: "When you retire something, grep for it by name").
-**In what order (D14).** First check what memoria holds. Its Notion connector has never run against a real workspace, so it is expected to hold nothing.
-- **If live memoria holds no Notion documents and no token:** retire it as soon as step 1 is done. Nothing is lost, and the egress exemption goes sooner.
-- **If it holds any:** retire it only after step 5, so there is never a moment when that content is findable in neither app.
+**When (D14).** Step 1 decides. Its Notion connector has never run against a real workspace, so it is expected to hold nothing.
+- **If live memoria holds no Notion documents and no token:** retire it as soon as the module exists (dependency 1). Nothing is lost, and the egress exemption goes sooner.
+- **If it holds any:** retire it only after dependency 5, so there is never a moment when that content is findable in neither app.
**Until then, memoria's connector is not run.** Paul's real run goes to Mapa (§19).
@@ -519,7 +562,7 @@ Write commits pages one at a time while members may be using Mapa. If a member c
| `date` | Date | ranges and times need a decision |
| `checkbox` | a Yes / No Choice | — |
| `url`, `email`, `phone_number` | Web address, Email, Phone | — |
-| `people` | a Link to the seeded People type (type designer R5) | names need the user-information capability, which §6 does not ask for |
+| `people` | a Link to the seeded People type (type designer R5), matched by name | names come from the user-information capability §6 asks for; emails are never asked for, so matching is by name only |
| `relation` | Link to … the type the related database became | the property endpoint returns relations past the first 25 |
| `formula`, `rollup` | not imported as live values. Fichas has no formulas; a snapshot would be "a second calculator" (Fichas §2) | listed per type |
| `files` | not imported until Fichas has attachments | listed |
@@ -545,9 +588,9 @@ Write commits pages one at a time while members may be using Mapa. If a member c
### In the module (M)
- **M1, the total decoder.** A missing cursor, a repeated cursor, or retries past budget fail with `traversal_failed`, never a partial tree (memoria N1).
-- **M2, search is not an enumerator.** A fake whose search returns only roots still yields every child (memoria N2).
+- **M2, search is not an enumerator.** A fake whose search returns only roots still yields every child (memoria N2), and one whose search also leaks children still gives each its true parent.
- **M3, orphans after the walk.** A page under a `block_id` parent gets its true parent, not a root's place (memoria §1.3's blocker, now with a test).
-- **M4, the API pin.** Another host, another scheme, any redirect, any method but `GET`, and any `POST` path but `/v1/search` are refused before dialling. One mutation each.
+- **M4, the API pin.** Another host, another scheme, another port, userinfo, any redirect, any method but `GET`, and any `POST` path but `/v1/search` are refused before dialling. One mutation each. The production package exports no constructor that takes a host.
- **M5, the file pin.** A host outside the allowlist, any redirect and an over-cap body are refused. **No request to a file host carries an `Authorization` header.**
- **M6, one place dials.** Inside the module, only `client.go` and `files.go` build a client or transport.
- **M7, the version pin.** Every request carries the pinned `Notion-Version`.
@@ -555,22 +598,24 @@ Write commits pages one at a time while members may be using Mapa. If a member c
### In Mapa (I)
-- **I1, fidelity.** For every fixture, the mapper's body equals a committed golden file, passes the structure check (D9), and loses nothing outside §10–§11's tables: each loss is in the counts. **Each imported body opened in the editor and left alone serialises to the same bytes** (L1's rule, run over the import goldens, which join `markup/testdata/corpus/`).
+- **I1, fidelity.** For every fixture, the mapper's body equals a committed golden file, passes the structure check (D9) against the meaning computed first (§11.4), and loses nothing outside §10–§11's tables: each loss is in the counts. Fixtures include every row of §11.4's table, across run boundaries; fences and backticks in ordinary text; a heading with a line break; link addresses with `(`; labels with `]`; a marked run holding `*`; and partly-italic bold. No fixture may produce the fallback. **Each imported body opened in the editor and left alone serialises to the same bytes** (L1's rule, run over the import goldens, which join `markup/testdata/corpus/`).
- **I2, an idempotent re-run.** Run, then run again on the same fixtures: no revision, no event, no image download, every page `unchanged`.
- **I3, untouched and kept.** Change two pages in the fake. Edit one of them in Mapa, rename a third in Mapa. Re-run: the untouched page updates, as the runner, with one event; the edited and renamed pages are kept and listed.
- **I4, never delete on absence.** Two pages imported; the fake drops one; the run is `done` and both pages stand. An interrupted survey reports no absence.
- **I5, links.** Mentions resolve to final titles, collision-renamed ones included. An unshared target is plain text and counted; sharing it and re-running links it where the source is untouched. A Notion URL to an imported page becomes a `[[link]]`.
- **I6, titles.** Duplicates, `[ ] | # ^`, over-long, empty and date-shaped titles all fit by §9.2. The same fixtures give the same titles twice. An existing Mapa page with the title is never written to. A member taking a planned title mid-run is handled by the fix-up pass.
-- **I7, events.** Every import write logs an event naming the runner, inside gate 8. *Mutation: commit a page without its event.*
+- **I7, attribution.** Every import write logs an event naming the person who pressed Start or Resume, and a Resume by a second importer names the second. *Mutations: name the page's owner; name the connection's creator.*
- **I8, egress.** No `http.Client`, transport, request constructor, dialler or resolver anywhere in `internal/mapa/**` or `cmd/**`; the module imported only by `import_*.go`. *Mutations: add an `http.Get` to a handler; import the module from `notionmd`.*
- **I9, plaintext.** The new tables' plaintext columns are exactly §15's. The file scan runs a full import over fixtures carrying canary titles, bodies, a canary token and canary Notion ids, then reads every byte on disk, WAL included: none appears.
- **I10, no Notion content in logs**, observed over a run against the fake whose error bodies carry canaries (memoria N13).
- **I11, the token is never rendered**: no 8-character run of it in any response (memoria N14).
-- **I12, resuming.** A run left `surveying` becomes `interrupted` at boot and the next Start runs. A resumed survey makes no request for a page already surveyed in that run. A resumed write writes no page twice.
+- **I12, resuming.** A run left `surveying` becomes `interrupted` at boot and Resume runs. Stop ends a run `stopped`. Disconnect, Finish and Forget are refused during a run. A run with a live ticker and no progress for ten minutes is reclaimable. A resumed survey makes no request for a page already surveyed in that run. A resumed write writes no page twice.
- **I13, who sees Import.** With `MAPA_IMPORTERS` unset every import route 404s for everyone. With it set, a member not named gets 404 on every route, `GET` and `POST`. Nothing outside Import changes for them.
- **I14, images.** A Notion-hosted image becomes a Mapa image through the images verb; an external one stays a link; an unchanged image block is not downloaded again; an image failure leaves a placeholder and a written page. *Depends on the images spec (§12).*
- **I15, scriptless.** `make browser` connects, starts, watches the meta refresh, resumes and finishes with JavaScript off, then on.
-- **I16, no write to Notion.** Over a whole run against the fake, the fake records every request: only `GET`s and `POST /v1/search`.
+- **I16, the import never asks to write.** Built with M4's method pin removed (a test-only build tag), a whole run against the fake records every request: only `GET`s and `POST /v1/search`. With the pin in place the fake would never see a write, so this is the version that can go red for the callers.
+- **I17, crash safety** (§14.1). Killed between every pair of statements in `ImportCreate`, `ImportUpdate` and the run loop, then resumed: no second page, no false *kept*, the map agrees with the pages. And a reclaimed run's goroutine writes no page after the lease moves (§8.3). Nothing but the run calls the two methods.
+- **I18, provenance.** Every verb on an imported page (commit, rename, revert, restore, relink, mark) clears `imported` and keeps `origin`.
**And the run is looked at in a browser**, at 0%, mid-survey, mid-write, interrupted and finished, before the build is called done. A template test proves markup exists, not that a run reads sensibly at 40% (memoria §13).
@@ -616,7 +661,7 @@ Against Paul's workspace. **Read-only on Notion's side**, owned by Paul, and a s
## 21. Amendments that land with the build
Not made in this commit. Each lands in the same commit as the code it describes.
-- **Mapa base spec:** §12's "Import from Obsidian, Reflect, Notion" row is met for Notion; §4's plaintext list gains §15's rows; §3.1's record gains `origin` and `imported`; §11 lists I1–I16; the leak list gains §5's entries.
+- **Mapa base spec:** §12's "Import from Obsidian, Reflect, Notion" row is met for Notion; §4's plaintext list gains §15's rows; §3.1's record gains `origin` and `imported`, and its event row gains object kind `import`; §5 names bookkeeping as the third exemption from gate 8 (§14.2); §11 lists I1–I18; the leak list gains §5's and §15's entries.
- **Mapa AGENTS.md:** "Mapa reaches the network only through `amadan.net/oficina/notion.git`, only from `import_*.go`, only during a run" joins the rules Mapa holds hard. Layout gains `notionmd/` and the import files.
- **Mapa README:** the leak list and `MAPA_IMPORTERS`.
- **memoria:** §16's list, in the commit that retires the connector.
@@ -648,6 +693,38 @@ Recommended answers are written in. None is ruled.
8. **Q8, Notion user names:** *Recommended:* the integration may read people's names, never their email addresses, so `@Ana` stays `@Ana` instead of `@Anonymous`.
9. **Q9, memoria's connector:** *Recommended:* if live memoria holds no Notion content, which is expected because it never ran, remove it as soon as the shared module exists.
+10. **Q10, a code block (or image, or table) inside a numbered step:** *Recommended:* keep it right after its step, which splits the list there. Mapa then shows the later steps numbered from 1 again, though the numbers stored are right. The alternative, moving everything after the whole list, keeps the numbering and moves each code block away from its step.
+
## 24. Findings and what changed
-*(Filled in by each review round.)*
+### Round 1: Fable (`claude-fable-5-2`) on revision 1 (`bb9b30d`): CHANGES REQUIRED, answered in revision 2
+
+| Finding | Change | Where |
+|---|---|---|
+| **H1** Staged trees cleared before fix-up and rename re-renders need them | Kept until the run is `done`; fix-up renders from them | §8.1, §13.6 |
+| **H2** The write is not idempotent: `CommitFrom` merges on a stale base; the map row is outside the transaction; rename and body are two revisions; `CreateTeamPage` cannot carry `origin` | `ImportCreate` and `ImportUpdate` (D15): one `Store.write` each, re-check inside, never merge, title and body one revision, map row and images in the same transaction, drafts untouched; I17 kills between statements | §14.1, §13.2, §8.3, I17 |
+| **H3** Ordinary text parses as fences, code spans, links, split blocks; §11.4 contradicted D9; no fallback | "Meant" computed first; U+200B at the breaking position for line starts, `[[`, `![[` and ` ^id`, checked across runs; backticks become ˋ; headings joined; failed blocks fall back to a fenced copy; fixtures for each | §11.4, D16, I1 |
+| **M1** Link label and address limits | `[text](url)` always; addresses percent-encode `(`, `)`, whitespace; labels and shown text cleaned | §11.3, I1 |
+| **M2** Event log joins defeat the sealed coordinate | Said plainly in §15 and the leak list; `updated_at` dropped; §14's reason for no verb corrected | §15, §14.2 |
+| **M3** `imported` carried forward by every verb | `tx.commit` clears it except for the two import methods; `origin` carried, kept on restore; I18 | §14.2, I18 |
+| **M4** Ledger writes have no home under gate 8 | Bookkeeping named as a third exemption; the person's connection acts log events under object kind `import` | §14.2, §21 |
+| **M5** No Stop; Disconnect, Finish and Forget mid-run; wedged heartbeat; two goroutines | Lease checked in every page transaction; progress staleness; Stop; those three refused during a run; panics end `failed` | §8.3, I12 |
+| **M6** `NewForTest` in the production package | Arbitrary-base constructor only in `notiontest`; I8 forbids non-test imports of it | §4, §5, M4 |
+| **M7** Over-length suffixes, folding, title flip-back, date titles with a parent | Room left for suffixes; every comparison folded; last Notion title stored; date titles take the parent | §9.2, §9.3, §15 |
+| **M8** Links to mapped pages that are deleted or failed | Plain text, counted; failed targets heal through fix-up and later runs | §11.2, §13.6 |
+| **M9** Non-text children of quotes, callouts and list items vanished or moved far | Every child type has a rule: hoisted straight after its block, counted; Q10 asks Paul about split lists | §10.1, Q10 |
+| **M10** Row counts need a data source query; pages under rows | Rows inside databases "not counted until the databases move"; directly shared rows skipped and counted; pages under rows imported parentless, listed | §8.1, §8.5 |
+| **M11** A1–A7 insufficient | A8–A11 added; download before the transaction; permanent failures recorded | §12 |
+| **M12** Retirement deleted data after removing the code that deletes it | Check live, delete on live, verify zero, then the code commit | §16 |
+| **L1** `*` inside marked runs; partial-overlap form | Mark dropped for runs holding `*`; editor's form cited | §11.1 |
+| **L2** I7 duplicated gate 8 | I7 mutates the actor | I7 |
+| **L3** I16 could not go red | Run with the method pin removed under a test build tag | I16 |
+| **L4** Verify-on-save dials outside a run | Stated as the second thing that dials | §5 |
+| **L5** §17 contradicted §6 on user information | Fixed | §17 |
+| **L6** Port, userinfo, escaped path, timeout | Pinned in both transports | §5, M4 |
+| **L7** Roots wording | Reworded; leaking-search fixture | §3, M2 |
+| **L8** Descendants of a failed page | "Could not be determined" | §13.4, §8.5 |
+| **L9** Titles past 25 mentions | Read from the property endpoint | §9.1 |
+| **L10** Vault export is unbuilt | Said so | §10.1 |
+| **L11** "Update links" freezes imported pages | Report splits kept into edited and links-only | §8.5 |
+| **L12** Start after an interrupted run | Resume continues it; Start only after `done` or `failed` | §8.3 |