oficina / mapa Public

Import: images at Notion's real file host, keyed by their file, not the minute-rounded edit time

The first read-only run against Paul's workspace found every hosted file
at the virtual-hosted prod-files-secure bucket, which the module's pin
refused, and every last_edited_time rounded to the minute.

Re-pinned to notion main 169302d, which allows that bucket; an image at
the real shape is downloaded and attached end to end. Pages were already
decided on the rendered body; a test now holds an edit in the same
minute. Image reuse, copies and permanent refusals compared the block's
edit time; notion_images now keeps the file's key (notion.FileKey) of the
file actually downloaded, and they compare that. Unchanged images are
still not downloaded again. Spec §12, §15, §19 and §25 note 17 record it.
Fable: APPROVED after one round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from fix/real-workspace into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 2510b47a3d6191cf290694fb47523deac0926622 parent a769934
9 files changed, +333 −56
  • docs/superpowers/specs/2026-11-17-notion-import.md +55 −7
  • go.mod +1 −1
  • go.sum +2 −2
  • internal/mapa/import_images.go +43 −23
  • internal/mapa/import_images_place.go +19 −11
  • internal/mapa/import_images_test.go +141 −3
  • internal/mapa/import_lows_test.go +1 −1
  • internal/mapa/import_rerun_test.go +36 −1
  • scripts/mutate/mutations_import.go +35 −7

CI passed — run details

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

added 16 packages in 310ms
cd editor && node build-bundles.mjs
wrote internal/mapa/static/editor.115ddee5d3f54787.js (354112 bytes, 111.2KB gzipped; L12 budget 120KB)
cd editor && node --test
✔ a badge is named for what it does, starting with its visible word (2.336883ms)
✔ first words stop at five words or forty characters (0.183701ms)
✔ the field keeps one trimmed line, without brackets (0.337326ms)
✔ the field holds at most MaxAlt bytes, cut at a character (0.886367ms)
✔ days and weeks move across months and years (1.331213ms)
✔ a month keeps the day, or takes the month's last (0.274751ms)
✔ the grid is six weeks from Monday, as the month calendar draws it (0.741588ms)
✔ the grid starts the week where the locale does (0.701384ms)
✔ the keys move a day, a week, a month and a year (0.335153ms)
✔ the picked day is the chip [[ makes for a date (17.441381ms)
✔ Insert → Today's date still puts today in at once (2.248499ms)
✔ / offers Date, the picker, and Today's date beside it (0.290951ms)
✔ after a ! the chip goes in after a space, never as an embed (3.291426ms)
✔ where the Markdown would read the chip differently, it is refused (2.512268ms)
✔ over a selection the chip goes after it and the words stay (2.743698ms)
✔ today is the day in the viewer's zone (17.523886ms)
✔ every offered locale has cases (0.821667ms)
✔ dates.mjs writes every date Go writes, byte for byte (2.702604ms)
✔ a chip, the month and the week, in three locales (0.360069ms)
✔ dates.json is what ICU gives, byte for byte (460.237919ms)
✔ L1: mounting then serialising gives cleanBody(body), byte for byte (77.026547ms)
ℹ 871 bodies
✔ L1: mounting a stored body adds nothing, and saving it writes nothing new (68.31625ms)
✔ L2: one edited block changes only that block's bytes; undo gives the body back (114.304621ms)
ℹ 858 single-block edits
✔ L2: inserting or deleting a block changes bytes only at the new seams, by Join (121.917807ms)
ℹ 866 inserts, 817 deletes
✔ L3: seeded edits keep the document and its Markdown saying the same thing (4202.784367ms)
ℹ 20904 edits over 871 bodies
✔ L3: Link to a page makes exactly one chip, and changes nothing else (1082.552446ms)
ℹ 4532 links over 871 bodies; refused: {"A page link can’t hold another link or a line break. Select plain words.":918,"A page link can’t show [ or ]]. Select words without them.":404,"Select some words to link them to a page.":174,"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.":18}
✔ L3: a picked date is one more date chip, or refused where a letter would be too (1106.780861ms)
ℹ over 871 bodies: {"inserted":5158,"spaced":23,"refused":45,"unstable":9}
✔ linear: trailing spaces (31.473156ms)
✔ linear: trailing whitespace (19.995337ms)
✔ linear: unclosed web links (24.494918ms)
✔ linear: web links with no address (28.845613ms)
✔ linear: unclosed wiki links (24.270652ms)
✔ linear: unclosed embeds (14.161756ms)
✔ linear: closes only (5.504098ms)
✔ the selected words become the chip's shown text (8.633744ms)
✔ words that are the title make a plain [[Title]] (2.599551ms)
✔ spaces at the selection's edges stay outside the chip (0.975592ms)
✔ a date makes a date link, in a heading, an item and a quote (7.844959ms)
✔ bold words lose their bold: a chip carries no marks in Mapa's Markdown (1.260693ms)
✔ only the linked block's bytes change, and undo gives the body back (2.657178ms)
✔ a selection across blocks, over a chip or a break, or of brackets is refused (1.466906ms)
✔ a target the words cannot be linked to as typed is refused (0.288607ms)
✔ ⌘L: over a selection it opens Page link; with none it types [[; in code it does nothing (2.385122ms)
✔ web-linked words are refused: the address would be lost (review M4) (1.312349ms)
✔ words whose Markdown would read otherwise are refused (review M3) (1.488927ms)
✔ ⌘A then ⌘L says why, instead of doing nothing (review low 1) (0.358646ms)
✔ linkCheck says why it refuses (review low 2) (1.754641ms)
✔ golden file has bodies (0.938054ms)
✔ markup.mjs parses every body into Go's blocks, byte offsets and all (37.900018ms)
✔ markup.mjs strips and spans every block as Go does (50.501846ms)
✔ the schema's toDOM draws every body as Go renders it (61.088229ms)
✔ emphasis draws the four pinned outputs (14.913033ms)
✔ a body ends in the editor's empty paragraph (0.177831ms)
✔ the editor labels date chips as Go does, in every locale L4 holds (10.743645ms)
✔ a POST that never answers is aborted after the timeout (21.891361ms)
✔ a keepalive POST carries no signal, and an answer clears the timer (1.17278ms)
✔ autosave sends only what differs, and the tab owns the draft it wrote (10.470576ms)
✔ an offered draft never commits by itself; Save commits it (1.370096ms)
✔ reload, then close: sessionStorage says the draft is this tab's own (0.598613ms)
✔ closing carries text not yet sent, and the cap leaves it out (26.660232ms)
✔ clean rebase: applied, the caret survives, the base moves by the rebase POST (5.700845ms)
✔ the block under the caret is the teammate's too, and undo brings back yours (2.853712ms)
✔ typing mid-flight: the merge is not applied and the base does not move (1.199979ms)
✔ a merge the editor cannot represent stops after three tries (3.975527ms)
✔ a conflict is shown, locks the editor's own commits, and Resolve settles it (1.728722ms)
✔ leaving: a conflict stays with the choice; a failed flush offers Leave anyway; a stored draft leaves (1.417254ms)
✔ a stale tab shows the newer draft, offered, and never overwrites it (0.728704ms)
✔ the first scratch commit: empty creates nothing, then one page, then drafts on it (0.705832ms)
✔ noBase and gone lead to the existing choices (0.853777ms)
✔ a commit that merged is applied when nothing was typed since (0.870357ms)
✔ back from the cache: nothing unsaved reloads, unsaved text autosaves at once (7.93805ms)
✔ an own draft committed meanwhile goes on as a new draft (1.579745ms)
✔ a reload keeps a stored draft; unsent text still commits (0.568397ms)
✔ a page deleted mid-edit: what is typed is still stored as the draft, and nothing commits (H1) (1.112688ms)
✔ an offered draft committed in another tab: typing goes on as a new draft (H1) (9.678115ms)
✔ a commit reply without a revision is not a commit; an emptied day starts afresh (H2) (1.121514ms)
✔ Resolve stores what was typed first, and takes no typing until its answer is applied (M1) (4.278861ms)
✔ closing with a choice open, or commits held, still writes the text, never commits (M2) (0.978438ms)
✔ closing inside the settling window sends the loaded version with settling=1 (M3) (0.296992ms)
✔ a clean merge not applied because of typing still ends the choice on show (M4) (0.819744ms)
✔ settling finds the draft committed with a teammate's text: a close still writes (M-A) (0.408409ms)
✔ settling finds another tab's newer draft: the tab shows it before any typing (0.581491ms)
✔ a page deleted before the first autosave: the text is offered as a scratch page, and a close makes one (M-B) (0.552507ms)
✔ an autosave that never answered but landed: its 409 keeps the typing since (L3) (0.601157ms)
✔ marks: em outside strong, bold reopened around italics, edges outside (6.700992ms)
✔ marks close before code, links and atoms, and reopen after (0.459174ms)
✔ untouched blocks and atoms re-emit their source; edited atoms are written from attributes (6.463803ms)
✔ empty blocks are written as nothing (2.682475ms)
✔ an unclosed fence that is no longer last gets its closing fence (1.887838ms)
✔ the structure check puts Join's seam where a kept one would merge two blocks (2.501849ms)
✔ prepareSave adopts the parse when no seam or rewrite can save the document (4.622319ms)
✔ reparse: typed emphasis becomes a mark, "- " after a break becomes an item (2.839678ms)
✔ a trailing hard break stays on screen and is written as nothing (1.276111ms)
✔ the reparse waits while an IME is composing (0.784067ms)
✔ copied blocks paste with their bytes and seams; a cut and paste gives the body back (5.39236ms)
✔ a forged x-mapa slice is refused, and text from outside is read as Markdown (0.732532ms)
✔ rebuild changes origins only, outside undo history (1.961315ms)
✔ applyBody takes a teammate's block, keeps the caret, and ends untouched (1.384453ms)
✔ a block whose context changed is written again: a task toggled, a bullet, a quote (1.924716ms)
✔ a duplicate ^id typed above its holder never takes the id from it (1.682827ms)
✔ a copy-dragged block is reparsed, and says what its Markdown says (1.093993ms)
✔ a history command that throws is refused, never thrown (4.911577ms)
✔ an image re-emits its source, and an edited alt changes only its span (1.097068ms)
✔ a paste whose image copy is refused says why and pastes nothing (15.916287ms)
✔ a line of image openers reads in linear time (110.263742ms)
✔ a line of shared link address reads in linear time (8.445063ms)
✔ a line of shared web address reads in linear time (39.195026ms)
✔ one rename at a time, from either field (1.701492ms)
✔ an empty or unchanged title sends nothing (0.151502ms)
✔ a refusal keeps what was typed, and the title (0.209499ms)
✔ the pending state holds for the busy rule (5.446031ms)
✔ a failed POST says so and keeps the title (0.88273ms)
✔ Update links posts the confirm page's POST (0.247931ms)
✔ clean is CleanTitle's whitespace rule (0.246799ms)
✔ the saver's base follows a rename made over it, and only that (0.285771ms)
✔ closing sends the rename as one keepalive POST (2.111714ms)
✔ the port answers every shared case as typeddate.go does (4.8693ms)
✔ numbers follow the locale: 12/11 is November in en-IE, December in en-US (0.250856ms)
✔ M6: several files land in the order they were chosen (44.408994ms)
✔ M5: one Backspace before the box keeps the image where the box is (11.634942ms)
✔ M5: undoing text typed just before the box keeps the upload (12.391537ms)
✔ L12: a failed upload an undo takes away does not stall the next (12.359448ms)
✔ M4: Replace… keeps the old image until the new one is in, and its alt (13.561622ms)
✔ M3 and N1: text wins, except over a picture copied from a page (1.733502ms)
✔ N2: a JPEG over 10 MB is scaled before its size is checked (5.806419ms)
✔ a drag whose anchor the document no longer reaches selects to its end (8.078153ms)
ℹ tests 126
ℹ suites 0
ℹ pass 126
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 6929.070552
=== 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	3.247s
?   	amadan.net/oficina/mapa/internal/mapa/icons	[no test files]
ok  	amadan.net/oficina/mapa/internal/mapa/imagefile	0.190s
ok  	amadan.net/oficina/mapa/internal/mapa/locale	0.007s
ok  	amadan.net/oficina/mapa/internal/mapa/markup	0.112s
ok  	amadan.net/oficina/mapa/internal/mapa/notionmd	0.288s
ok  	amadan.net/oficina/mapa/internal/mapa/seal	(cached)
ok  	amadan.net/oficina/mapa/internal/mapatest	12.965s
?   	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 dc85a39..95097d6 100644
--- a/docs/superpowers/specs/2026-11-17-notion-import.md
+++ b/docs/superpowers/specs/2026-11-17-notion-import.md
@@ -442,12 +442,12 @@ Mapa has **no escapes** (level-up D11). The editor accepts that because a person
- **Leaks:** the `images` table shows how many images each page holds, who uploaded each and when, and its size to within 64 KiB (§1.3). The import adds nothing to that row.
**What the import does:**
-- **When:** during Write, **before** the page's transaction, for each image block that is new to this page 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, downloads it through the file transport (§5), and hands the bytes to `AddImage` as the run's person. No network call and no `AddImage` happens inside a page transaction.
+- **When:** during Write, **before** the page's transaction, for each image block that is new to this page or whose file changed since its last import: its file's key (host and path, which hold the file's own id) differs from the one kept, never its `last_edited_time`, which Notion rounds to the minute (§25 note 17). 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, downloads it through the file transport (§5), and hands the bytes to `AddImage` as the run's person. No network call and no `AddImage` happens inside a page transaction.
- **Then** `ImportCreate` or `ImportUpdate` writes the body holding `image.Markdown(caption)` (the Notion caption as plain text; empty when there is none) and its commit attaches the image.
- **Commit as it goes** (images §7). Images are downloaded and added only for the page about to be written, and that page is committed before the next page's images are added. So pending images never pile up against the runner's own allowance. **If the page's write returns *kept* or fails, the run deletes that page's pending images at once**, through the images spec's removal (one transaction, `removed`, the runner as actor, §3.2 item 3's shape), so nothing holds quota for seven days.
- **The lease is checked just before each `AddImage` and `CopyImage`.** Those are their own writes, outside the page transaction. The one gap left: a lease that moves between the check and the call lets one pending image be added by a run that no longer holds it. It is never attached, and the sweep removes it after seven days. That is the named exception to §8.3's "changes nothing".
- **Reuse.** `notion_images` maps (Notion block, Mapa page) to the Mapa image's public id, sealed. An unchanged block on the same page reuses it, after the run checks, in its own read, that the image row still exists and is attached to that page; one the sweep or a member's "Remove from Mapa" took away is fetched again. **A block that moves to another page**, or a synced block that shows one Notion file on several pages, is found by its block alone (`block_print`, §15), and gets `CopyImage` from the existing Mapa image where the runner may read it, and a fresh download otherwise.
-- **A failure is not the page's failure.** A refused or failed image becomes the images spec's text line, `(Image not imported: <file name>, <reason>)`, the file name taken from the last segment of Notion's file URL path, decoded (or the caption when the path has none),, in its place, and the page is written. The report counts images by reason. **A permanent refusal** (type, size, dimensions, host not allowed) is recorded on its `notion_images` row with the block's edit time and is not downloaded again until the block changes. **A transient one** (network, 429, 5xx, an expired URL) is tried again on the next run.
+- **A failure is not the page's failure.** A refused or failed image becomes the images spec's text line, `(Image not imported: <file name>, <reason>)`, the file name taken from the last segment of Notion's file URL path, decoded (or the caption when the path has none),, in its place, and the page is written. The report counts images by reason. **A permanent refusal** (type, size, dimensions; a host the pin refuses is transient, since §19 step 4 may yet add it: build round 3, L5) is recorded on its `notion_images` row with the file's key and is not downloaded again until the block shows another file (§25 note 17). **A transient one** (network, 429, 5xx, an expired URL, a host not allowed) is tried again on the next run.
- **Quota.** Notion's block objects carry no file size, so the run cannot total the images before it starts. Instead, the Start page shows **both** allowances the images spec checks: the team's (`MAPA_IMAGE_QUOTA_TEAM`) and the runner's own (`MAPA_IMAGE_QUOTA_PERSON`, which counts their pending and private images). `ErrImageQuota` can come from either. On the first one, the run reads both figures to say which, and stops downloading for the rest of that run: every later image becomes the text line, and the report says at the top which allowance is full. Raising that allowance, or freeing the runner's own, and running again fills them in, because those pages render differently and are still untouched (§13.2). `ErrNoImageStore` does the same from the first image: "images aren't set up on this Mapa yet".
- **External images** stay links (D13). The images spec leaves fetching them to this spec (its §7), and this spec does not propose it. **Q2** asks Paul.
- **Literal image syntax.** Notion text that happens to read `![…](/i/…)` would become an image reference once the images spec is built. §11.4 neutralises it.
@@ -524,7 +524,7 @@ The import writes pages only through two methods in package `mapa`, each **one `
## 15. Sealing
-**New purposes:** `notion.token`, `notion.workspace` (its name and id), `notion.coordinate` (a row's Notion id, its Mapa page id, the revision the import last wrote, the ids it mentioned that were not imported, its placeholders' ids), `notion.staged` (a surveyed tree), `notion.image` (an image block's id, edit time and Mapa image). Print keys are derived apart, as base build note 21 does: `oficina/mapa:print:notion.page` and `…:notion.image`.
+**New purposes:** `notion.token`, `notion.workspace` (its name and id), `notion.coordinate` (a row's Notion id, its Mapa page id, the revision the import last wrote, the ids it mentioned that were not imported, its placeholders' ids), `notion.staged` (a surveyed tree), `notion.image` (an image block's id, its file's key (§25 note 17) and Mapa image). Print keys are derived apart, as base build note 21 does: `oficina/mapa:print:notion.page` and `…:notion.image`.
**New tables and their plaintext,** to be added to base §4's list and to `plaintext_test.go` with the build:
@@ -533,7 +533,7 @@ The import writes pages only through two methods in package `mapa`, each **one `
| `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`, `lease` (random, redrawn on start, resume and Stop), `started_at`, `heartbeat_at`, `progress_at`, `finished_at`, the counters, `error_code` | — | when imports ran, who ran them, how many pages each created, kept, failed. The lease is random and says nothing |
| `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`, `place_print` (unique: an HMAC of the Notion block id and the **Notion** page id together, which the map pins to one Mapa page; §25.7), `block_print` (an HMAC of the block id alone, not unique, to find a block that moved or is shown on several pages), `state` (`imported`, `refused`; a transient failure keeps no row, so the next run tries again) | the image record (block id, block edit time, Mapa page id, public id, refusal reason) | how many images were imported, refused and failed, and, through equal `block_print`s, how many Notion images appear on more than one page. The images spec's own `images` table holds the rest (§12) |
+| `notion_images` | `id`, `place_print` (unique: an HMAC of the Notion block id and the **Notion** page id together, which the map pins to one Mapa page; §25.7), `block_print` (an HMAC of the block id alone, not unique, to find a block that moved or is shown on several pages), `state` (`imported`, `refused`; a transient failure keeps no row, so the next run tries again) | the image record (block id, the file's key (§25 note 17), Mapa page id, public id, refusal reason) | how many images were imported, refused and failed, and, through equal `block_print`s, how many Notion images appear on more than one page. The images spec's own `images` table holds the rest (§12) |
- **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).
@@ -654,8 +654,8 @@ Against Paul's workspace. **Read-only on Notion's side**, owned by Paul, and a s
1. Paul makes an internal integration, "Oficina import": **Read content** only; no update, no insert, no comments; user information **without email addresses**. He checks the capabilities page shows exactly that.
2. He shares a small set of top-level pages with it, a few hundred pages at most for the first run, not the workspace root.
3. `cmd/notion-record` records that set, from Paul's machine, into a directory outside every repository. Scrub it, commit the scrubbed fixtures to the module, delete the raw recording. Compare its block types with §10.1: any type not in the table is added to the table before the run.
-4. Check the image file URLs in the recording against the file transport's (host, path prefix) pairs. Fix the allowlist from what Notion actually sends, not from the documentation's one example. **Expect a virtual-hosted bucket**, for example `prod-files-secure.s3.us-west-2.amazonaws.com` with the workspace id as the first path segment: it is its own pair, host and prefix both, never the host alone.
-5. Check whether Notion rounds `last_edited_time` to the minute: image reuse and copies compare a block's edit time (§12), so two edits within a minute would look like one. Check that user mentions carry names (§11.2), what a synced block's copy returns for its children (§10.1), and whether `GET /v1/users/me` carries a workspace id (§8.3). **If it carries none, the map's workspace is matched by name** (§25.8): two workspaces with one name pass as one, and a workspace renamed in Notion is refused as another until the import is forgotten. Record which it is in the build notes before the run on `paulca`.
+4. Check the image file URLs in the recording against the file transport's (host, path prefix) pairs. Fix the allowlist from what Notion actually sends, not from the documentation's one example. **Expect a virtual-hosted bucket**, for example `prod-files-secure.s3.us-west-2.amazonaws.com` with the workspace id as the first path segment: it is its own pair, host and prefix both, never the host alone. **Done, by the first read-only run** (831 objects, 158 pages): all 144 hosted files were at `https://prod-files-secure.s3.us-west-2.amazonaws.com/<workspace id>/<file id>/<name>`, which the documented pair refused. That host is now its own pair, prefix `/` (§25 note 17).
+5. Check whether Notion rounds `last_edited_time` to the minute. **Done, by the first read-only run: it does**, all 3,815 edit times ended in `:00`. Image reuse and copies, which compared a block's edit time, now compare the file's key; pages were already decided on the rendered body (§13.2), now gated for an edit in the same minute (§25 note 17). **Still to check, before the run on `paulca`:** the file key's two premises. Record the same set twice and diff the keys (an unchanged file's path must be the same on every read, or every run fetches every image again); then replace one image in Notion, record again, and see its key move (a replaced file must get a new file id, or the import keeps the old picture). User mentions came back `@Anonymous`: the integration lacked step 1's user information, which Paul turns on; with it the import writes the name (§11.2; I1's `@Ana`, notionmd's `mentions-other`). Check that user mentions carry names (§11.2), what a synced block's copy returns for its children (§10.1), and whether `GET /v1/users/me` carries a workspace id (§8.3). **If it carries none, the map's workspace is matched by name** (§25.8): two workspaces with one name pass as one, and a workspace renamed in Notion is refused as another until the import is forgotten. Record which it is in the build notes before the run on `paulca`.
**The run, on the `test` team first** (`test.mapa.oficina.works`, disposable)
6. Connect, run, and watch the status page through to the end.
@@ -815,7 +815,8 @@ Where the build chose, or departed:
move to §19 step 3, with the recording made against the new pin.
2. **The file allowlist is the documented pair only**
(`s3.us-west-2.amazonaws.com`, `/secure.notion-static.com/`). §19 step
- 4 adds what a recording shows Notion sends.
+ 4 adds what a recording shows Notion sends. *Superseded by note 17:*
+ the virtual-hosted pair is added.
3. **notionmd has its own copy of the typed tree**, filled by
`import_convert.go`. §4 has the mapper map "the block tree"; I8 forbids
notionmd importing the module, so the tree the mapper reads, and the
@@ -893,6 +894,53 @@ Where the build chose, or departed:
import's migration is `0007_notion_import`, after the locale's
`0006_alter_members`.
+17. **Found by the first real run** (read-only, `notion-record`, 831
+ objects and 158 pages of Paul's workspace; §19 steps 4 and 5), fixed
+ before he imports (branch `fix/real-workspace`, module and Mapa):
+ - **Every Notion-hosted file was refused.** All 144 were at the
+ virtual-hosted `https://prod-files-secure.s3.us-west-2.amazonaws.com/
+ <workspace id>/<file id>/<name>?…`; the allowlist held only the
+ documented path-style pair. The module adds
+ (`prod-files-secure.s3.us-west-2.amazonaws.com`, `/`): the host,
+ matched exactly, names the bucket, so it pins as much as the old
+ host and prefix did. The old pair stays, and every other pin
+ (https, no userinfo, the port, the escaped-path prefix, no
+ redirects, no token, the `..` refusal) is unchanged. The fake builds
+ the real shape (`Host`) and still the old one (`PathStyle`), and
+ production's own pin is checked against both. M5 refuses
+ look-alikes (`…amazonaws.com.evil.example`,
+ `evil.s3.us-west-2.amazonaws.com`, another region, a trailing dot),
+ with mutations for a suffix or prefix host match and the missing
+ pair; I14 downloads and attaches an image at the real shape.
+ - **`last_edited_time` is rounded to the minute** (all 3,815 ended in
+ `:00`), so nothing may decide "unchanged" from it alone. Pages
+ never did: Survey reads every page, and Write compares the rendered
+ title and body with what Mapa holds (§13.2); there is no survey
+ shortcut. `TestI2AnEditInTheSameMinuteIsPickedUp` now holds it,
+ with a mutation that adds the edit-time shortcut. **Images did:**
+ reuse (`prior.Edited == block.Edited`) and copies compared the
+ block's edit time, so a file replaced in the same minute as the
+ last run kept the old picture. `notion_images` now keeps the file's
+ key, `notion.FileKey` (host and escaped path, the signature
+ dropped), which changes when the file is replaced; reuse, copies
+ and permanent refusals compare it. An unchanged image is still not
+ downloaded again (I2). A row from before keys has none, matches
+ nothing, and is fetched once more. Gate
+ `TestI14AnImageReplacedInTheSameMinuteIsFetched`, and the copy's
+ `TestI14AChangedSharedImageIsFetchedOnce`, now replace the file
+ without moving the edit time; each has a mutation.
+ - **Fable's review of this change: CHANGES REQUIRED, answered.** M1:
+ the fake signed every file URL alike, so no gate could tell a key
+ that kept the signature; the fake now signs every read afresh, as
+ Notion does (module test and mutation), and Mapa's mutation "the
+ file key is the signed URL" turns I14 red. L1: a file replaced
+ between Survey and Write is kept under the key of what was
+ downloaded, not the staged one
+ (`TestI14AFileReplacedMidRunIsKeyedAsDownloaded`). L3: the key drops
+ the port. L5: a permanent refusal is retried once the file is
+ replaced, gated. L2: §19 step 5 now checks the key's premises. L6:
+ §12's permanent refusals corrected (a refused host is transient).
+
### Fable's review of the build (2026-11-17): CHANGES REQUIRED, answered
No egress, credential, sealing or scope hole, and no path that
diff --git a/go.mod b/go.mod
index 897ff0c..7c11c8c 100644
--- a/go.mod
+++ b/go.mod
@@ -6,7 +6,7 @@ toolchain go1.26.11
require (
amadan.net/oficina/estilo.git v0.0.0-20261118055615-d004805f40f2
- amadan.net/oficina/notion.git v0.0.0-20261117112255-7eb9a9e888cb
+ amadan.net/oficina/notion.git v0.0.0-20261122111155-169302d88bbe
amadan.net/rastrillo/rastrillo v0.35.1-0.20261116213651-96812beacacc
github.com/chromedp/cdproto v0.158.6
github.com/chromedp/chromedp v0.21.0
diff --git a/go.sum b/go.sum
index 1947ca5..1ba473a 100644
--- a/go.sum
+++ b/go.sum
@@ -1,7 +1,7 @@
amadan.net/oficina/estilo.git v0.0.0-20261118055615-d004805f40f2 h1:E2+IhBdGcjhX3IX8UgQj5t6Bu+4zkGG0J+W1CIeoTAo=
amadan.net/oficina/estilo.git v0.0.0-20261118055615-d004805f40f2/go.mod h1:2UFIFrbTrhew8EFM0C94WmTo2OASM2pHEgT4jzeE/s8=
-amadan.net/oficina/notion.git v0.0.0-20261117112255-7eb9a9e888cb h1:P1KhTWoKSfvm+v2rwcEqnfwsftrrpZRjEe1zoJvwceQ=
-amadan.net/oficina/notion.git v0.0.0-20261117112255-7eb9a9e888cb/go.mod h1:2WuyjBTLHwurTGri00zfPxSKc9b3pomdT6wSs/UIvA4=
+amadan.net/oficina/notion.git v0.0.0-20261122111155-169302d88bbe h1:rTQZz9FJ7tQ7p5adMGNzjFLg6hpplF2NQewgtaQs3ac=
+amadan.net/oficina/notion.git v0.0.0-20261122111155-169302d88bbe/go.mod h1:2WuyjBTLHwurTGri00zfPxSKc9b3pomdT6wSs/UIvA4=
amadan.net/rastrillo/fiesta v1.3.0 h1:7SsHw4aeWPLStR3RHFEEtX4CwqKu+Ig3PgNX8FvD8WM=
amadan.net/rastrillo/fiesta v1.3.0/go.mod h1:LpO391W1dIRUxOIKklHm+bGyWXtlFyBRRPQCysb9LjY=
amadan.net/rastrillo/rastrillo v0.35.1-0.20261116213651-96812beacacc h1:QakboVkj9nqA6ZaKXeDVXWLPobQSVvd80ic521aA8/U=
diff --git a/internal/mapa/import_images.go b/internal/mapa/import_images.go
index 1ceb74d..9ca36fe 100644
--- a/internal/mapa/import_images.go
+++ b/internal/mapa/import_images.go
@@ -144,18 +144,24 @@ type gotImage struct {
placed placedImage
}
-// imageFor is a block's image: its last place reused where the block is
-// unchanged and the page still holds the image, a permanent refusal
-// remembered, or a copy or a fresh download (spec §12).
+// imageFor is a block's image: its last place reused where the block
+// still shows the same file and the page still holds the image, a
+// permanent refusal remembered, or a copy or a fresh download (spec
+// §12).
+//
+// "The same file" is the file's key (notion.FileKey: its host and path,
+// which hold the file's own id), never the block's last_edited_time:
+// Notion rounds that to the minute (§25 note 17), so a file replaced
+// within a minute of the last run would carry the time the run saw.
func (job *importJob) imageFor(ctx context.Context, entry *importEntry,
block notionmd.Block, alt string) (gotImage, error) {
- placed := placedImage{block: block.ID, edited: block.Edited,
+ placed := placedImage{block: block.ID, key: notion.FileKey(block.File.URL),
page: entry.staged.ID}
prior, found, err := job.priorPlace(ctx, entry.staged.ID, block.ID)
if err != nil {
return gotImage{}, err
}
- if found && prior.Edited == block.Edited {
+ if found && sameFile(prior.Key, placed.key) {
if prior.Reason != "" {
placed.reason, placed.permanent = prior.Reason, true
return gotImage{reason: prior.Reason, placed: placed}, nil
@@ -170,15 +176,27 @@ func (job *importJob) imageFor(ctx context.Context, entry *importEntry,
return job.freshImage(ctx, entry, block, alt, placed)
}
+// sameFile is whether two file keys name one file. A key that is empty
+// (a row from before keys, or a URL that names no file) matches nothing,
+// so the file is fetched again once rather than reused on a guess.
+func sameFile(kept, now string) bool {
+ return kept != "" && kept == now
+}
+
// freshImage copies the block's image from another page that holds it,
// or downloads it and adds it.
func (job *importJob) freshImage(ctx context.Context, entry *importEntry,
block notionmd.Block, alt string, placed placedImage) (gotImage,
error) {
- added, reason, err := job.addImage(ctx, entry, block)
+ added, fetched, reason, err := job.addImage(ctx, entry, block)
if err != nil {
return gotImage{}, err
}
+ if fetched != "" {
+ // The file downloaded is the one kept: a file replaced since
+ // Survey read the block is keyed as the bytes are (Fable L1).
+ placed.key = fetched
+ }
if reason.text != "" {
placed.reason, placed.permanent = reason.text, reason.permanent
return gotImage{reason: reason.text, placed: placed}, nil
@@ -194,12 +212,12 @@ type refusal struct {
permanent bool
}
-// addImage copies or downloads one image and adds it. A refusal is a
-// reason, not an error: the image becomes its line and the page is
-// written. Only what stops the run (a lost lease, the token refused) is
-// an error.
+// addImage copies or downloads one image and adds it, and answers the
+// key of the file it downloaded, if it did. A refusal is a reason, not
+// an error: the image becomes its line and the page is written. Only
+// what stops the run (a lost lease, the token refused) is an error.
func (job *importJob) addImage(ctx context.Context, entry *importEntry,
- block notionmd.Block) (AddedImage, refusal, error) {
+ block notionmd.Block) (AddedImage, string, refusal, error) {
id := block.ID
if job.imagesStopped == "" {
if err := job.images.Ready(ctx); err != nil {
@@ -207,42 +225,44 @@ func (job *importJob) addImage(ctx context.Context, entry *importEntry,
}
}
if job.imagesStopped != "" {
- return nil, refusal{text: job.imagesStopped}, nil
+ return nil, "", refusal{text: job.imagesStopped}, nil
}
// The lease is checked just before each of the store's own writes
// (§12): a copy, or an add after the download.
if err := job.store.bookkeep(ctx, job.lease, noChange); err != nil {
- return nil, refusal{}, err
+ return nil, "", refusal{}, err
}
if added, ok := job.copyImage(ctx, entry, block); ok {
- return added, refusal{}, nil
+ return added, "", refusal{}, nil
}
- data, why, err := job.download(ctx, id)
+ data, key, why, err := job.download(ctx, id)
if err != nil || why.text != "" {
- return nil, why, err
+ return nil, key, why, err
}
if err := job.store.bookkeep(ctx, job.lease, noChange); err != nil {
- return nil, refusal{}, err
+ return nil, "", refusal{}, err
}
added, err := job.images.Add(ctx, job.who, data)
- return added, job.storeRefusal(err), nil
+ return added, key, job.storeRefusal(err), nil
}
-// download reads the block again for a fresh signed URL and fetches it.
+// download reads the block again for a fresh signed URL and fetches it,
+// and answers that file's key.
func (job *importJob) download(ctx context.Context, id string) ([]byte,
- refusal, error) {
+ string, refusal, error) {
fresh, err := job.client.Block(ctx, id)
if err != nil || fresh.File == nil {
- return nil, refusal{text: fetchReason(err)}, finalOnly(err)
+ return nil, "", refusal{text: fetchReason(err)}, finalOnly(err)
}
+ key := notion.FileKey(fresh.File.URL)
data, err := job.files.Fetch(ctx, fresh.File.URL, imageCap)
if err != nil {
// Only size is permanent: a host the pin refuses may be one
// §19 step 4 has yet to add, so it is tried again (round 3, L5).
- return nil, refusal{text: fetchReason(err),
+ return nil, key, refusal{text: fetchReason(err),
permanent: notion.CodeOf(err) == notion.CodeTooLarge}, nil
}
- return data, refusal{}, nil
+ return data, key, refusal{}, nil
}
// storeRefusal is what Mapa images' answer means for the run: the first
diff --git a/internal/mapa/import_images_place.go b/internal/mapa/import_images_place.go
index ee289fa..4f5ee8a 100644
--- a/internal/mapa/import_images_place.go
+++ b/internal/mapa/import_images_place.go
@@ -8,6 +8,7 @@ import (
"amadan.net/oficina/mapa/internal/mapa/notionmd"
"amadan.net/oficina/mapa/internal/mapa/seal"
+ "amadan.net/oficina/notion.git/notion"
)
// notion_images (Notion import spec §12, §15): where each Notion-hosted
@@ -18,15 +19,19 @@ import (
// placedImage is one block's outcome on one page, before it is kept.
type placedImage struct {
- page, block, edited string
- publicID, reason string
- permanent bool
+ page, block, key string
+ publicID, reason string
+ permanent bool
}
-// imagePlace is a notion_images row's sealed record.
+// imagePlace is a notion_images row's sealed record. Key is the file's
+// notion.FileKey when the place was made. A row written before keys
+// carries "edited" instead, the block's minute-rounded edit time, which
+// nothing reads now: its empty Key matches nothing, so its file is
+// fetched once more and the row rewritten with a key.
type imagePlace struct {
Block string `json:"block"`
- Edited string `json:"edited,omitempty"`
+ Key string `json:"key,omitempty"`
Page int64 `json:"page,omitempty"`
PublicID string `json:"image,omitempty"`
Reason string `json:"reason,omitempty"`
@@ -78,21 +83,23 @@ func (job *importJob) priorPlace(ctx context.Context, page,
// copyImage copies the block's image from another page that still holds
// it, where the runner may read it (spec §12: one image, one place),
-// and only from a place made of the block as it is now: a block changed
-// since is downloaded afresh, once, and the other page copies that
-// (Fable round 3, M2).
+// and only from a place made of the file the block shows now: a file
+// replaced since is downloaded afresh, once, and the other page copies
+// that (Fable round 3, M2). The file's key decides, not the block's
+// minute-rounded edit time (§25 note 17).
func (job *importJob) copyImage(ctx context.Context, entry *importEntry,
block notionmd.Block) (AddedImage, bool) {
_, alone, err := job.store.imagePrints(entry.staged.ID, block.ID)
if err != nil {
return nil, false
}
+ key := notion.FileKey(block.File.URL)
var rows []NotionImage
job.store.database.WithContext(ctx).Where("block_print = ? AND "+
"state = ?", alone, imageImported).Find(&rows)
for _, row := range rows {
other, err := job.store.openPlace(row)
- if err != nil || other.Page == 0 || other.Edited != block.Edited ||
+ if err != nil || other.Page == 0 || !sameFile(other.Key, key) ||
other.Page == entry.place.PageID ||
!job.images.Held(ctx, other.PublicID, other.Page) {
continue
@@ -119,7 +126,8 @@ func (job *importJob) recordImages(ctx context.Context, entry *importEntry,
// keepPlaces keeps where each image went. A transient refusal keeps
// nothing, so the next run tries again; a permanent one is kept with the
-// block's edit time, and not tried again until the block changes (§12).
+// file's key, and not tried again until the block shows another file
+// (§12).
func keepPlaces(db *gorm.DB, store *Store, pageID int64,
placed []placedImage) error {
for _, each := range placed {
@@ -137,7 +145,7 @@ func keepPlace(db *gorm.DB, store *Store, pageID int64,
return err
}
row, found := notionImageOf(db, place)
- record := imagePlace{Block: placed.block, Edited: placed.edited}
+ record := imagePlace{Block: placed.block, Key: placed.key}
switch {
case placed.publicID != "":
row.State = imageImported
diff --git a/internal/mapa/import_images_test.go b/internal/mapa/import_images_test.go
index 846d0b4..e9c55be 100644
--- a/internal/mapa/import_images_test.go
+++ b/internal/mapa/import_images_test.go
@@ -9,6 +9,7 @@ import (
"amadan.net/rastrillo/rastrillo/blobs"
+ "amadan.net/oficina/notion.git/notion"
"amadan.net/oficina/notion.git/notiontest"
)
@@ -137,7 +138,7 @@ func TestI14ABlockOnASecondPageIsCopied(t *testing.T) {
// not remembered.
func TestI14ARefusalIsALineAndRemembered(t *testing.T) {
ws := newSmall()
- ws.Add(ws.handbook, notiontest.Image(ws.Host("notes.png",
+ ids := ws.Add(ws.handbook, notiontest.Image(ws.Host("notes.png",
[]byte("not a picture at all"))))
world := newImportWorld(t, ws.Workspace)
world.useImages()
@@ -153,6 +154,42 @@ func TestI14ARefusalIsALineAndRemembered(t *testing.T) {
if world.fileRequests() != 0 {
t.Errorf("a permanent refusal was fetched again")
}
+ // The file replaced with a picture in the same minute: the refusal
+ // was the old file's, so the new one is fetched (Fable L5).
+ changeImage(t, ws, ids[0], 10)
+ world.server.Reset()
+ world.importAs(ana)
+ _, record, _ = world.pageTitled("Handbook")
+ if world.fileRequests() != 1 || !strings.Contains(record.Body, "](/i/") {
+ t.Errorf("a refused file replaced: %d fetched, body %q",
+ world.fileRequests(), record.Body)
+ }
+}
+
+// Fable L1: a file replaced between Survey and Write is downloaded as
+// it is now, and kept under the key of what was downloaded, so the next
+// run fetches nothing.
+//
+// Mutation (make mutate, first red 2026-11-22): the key kept is the
+// staged file's.
+func TestI14AFileReplacedMidRunIsKeyedAsDownloaded(t *testing.T) {
+ ws, block := imagePage(t)
+ world := newImportWorld(t, ws.Workspace)
+ world.useImages()
+ world.connect(ana)
+ atPoint(t, "survey:walked", 1, func() {
+ world.server.Lock()
+ defer world.server.Unlock()
+ changeImage(t, ws, block, 11)
+ })
+ world.importAs(ana)
+ importCrash = nil
+ world.server.Reset()
+ // (The page itself updates: changeImage drops the caption.)
+ world.importAs(ana)
+ if world.fileRequests() != 0 {
+ t.Errorf("the run after fetched %d", world.fileRequests())
+ }
}
// I14: the first quota refusal stops downloads for the run and names
@@ -216,16 +253,117 @@ func (world *importWorld) notWritten(act string, page Page) {
}
// changeImage replaces an image block's file, as an edit in Notion does:
-// a new file and a later edit time, the same block.
+// a new file (a new file id in its URL), the same block. Its
+// last_edited_time does not move: Notion rounds it to the minute (spec
+// §25 note 17), so a replacement in the minute the last run read it
+// carries the time that run saw, and only the file's key tells.
func changeImage(t *testing.T, ws *small, block string, seed int) {
t.Helper()
changed, ok := ws.Block(block)
if !ok {
t.Fatal("no such block")
}
+ minute := changed["last_edited_time"]
fresh := notiontest.Image(ws.Host("changed.png", picture(t, seed)))
changed["image"] = fresh["image"]
- changed["last_edited_time"] = "2026-12-01T10:00:00.000Z"
+ if changed["last_edited_time"] != minute {
+ t.Fatal("the replacement moved the edit time")
+ }
+}
+
+// hostedURL is an image block's file URL, as the workspace holds it.
+func hostedURL(t *testing.T, ws *small, block string) string {
+ t.Helper()
+ found, ok := ws.Block(block)
+ if !ok {
+ t.Fatal("no such block")
+ }
+ image, _ := found["image"].(map[string]any)
+ file, _ := image["file"].(map[string]any)
+ url, _ := file["url"].(string)
+ return url
+}
+
+// I14 at the shape a real workspace sends (spec §19 step 4, §25 note
+// 17): every hosted file in the first real run was at the virtual-hosted
+// prod-files-secure bucket, which the documented pair alone refused. The
+// fixture is that shape, production's own pin takes it, and it is
+// downloaded and attached through the fake; the documentation's
+// path-style shape still is too.
+//
+// Its mutation is the module's (M5, "no virtual-hosted pair, the
+// fixtures"): Mapa's make mutate cannot edit a dependency. Red by hand
+// on 2026-11-22, against the module with that pair removed through a
+// replace.
+func TestI14TheRealFileShapeIsDownloadedAndAttached(t *testing.T) {
+ ws, block := imagePage(t)
+ path := ws.PathStyle("old.png", picture(t, 7))
+ ws.Add(ws.onboarding, notiontest.Image(path, notiontest.Text("Old")))
+ url := hostedURL(t, ws, block)
+ if !strings.HasPrefix(url, "https://prod-files-secure.s3."+
+ "us-west-2.amazonaws.com/"+notiontest.FileWorkspace+"/") {
+ t.Fatalf("the fixture's file is not the real shape: %s", url)
+ }
+ files := notion.NewFiles()
+ if !files.Allowed(url) || !files.Allowed(path) {
+ t.Fatal("production's file pin refuses a shape Notion sends")
+ }
+ world := newImportWorld(t, ws.Workspace)
+ world.useImages()
+ world.connect(ana)
+ world.importAs(ana)
+ for _, title := range []string{"Handbook", "Onboarding"} {
+ page, record, _ := world.pageTitled(title)
+ attached, _ := world.imagesOf(page.ID)
+ if attached != 1 || !strings.Contains(record.Body, "](/i/") ||
+ strings.Contains(record.Body, "Image not imported") {
+ t.Errorf("%s: %d attached, body %q", title, attached,
+ record.Body)
+ }
+ }
+ if world.fileRequests() != 2 {
+ t.Errorf("%d files fetched, want 2", world.fileRequests())
+ }
+}
+
+// I14 against the minute-rounded edit time: an image replaced in Notion
+// within the minute the last run read it (so its block's edit time is
+// the one that run kept) is downloaded on the next run and the page
+// updated, twice in a row; a run after that downloads nothing.
+//
+// Mutation (make mutate, first red 2026-11-22): reuse ignores the
+// file's key, which is what comparing the unchanged edit time did.
+func TestI14AnImageReplacedInTheSameMinuteIsFetched(t *testing.T) {
+ ws, block := imagePage(t)
+ world := newImportWorld(t, ws.Workspace)
+ world.useImages()
+ world.connect(ana)
+ world.importAs(ana)
+ _, before, _ := world.pageTitled("Handbook")
+ for seed := 8; seed <= 9; seed++ {
+ changeImage(t, ws, block, seed)
+ world.server.Reset()
+ run := world.importAs(ana)
+ _, after, _ := world.pageTitled("Handbook")
+ if world.fileRequests() != 1 || run.Updated != 1 ||
+ after.Body == before.Body {
+ t.Fatalf("a replacement in the same minute: %d fetched, %+v",
+ world.fileRequests(), run)
+ }
+ before = after
+ }
+ world.server.Reset()
+ if run := world.importAs(ana); world.fileRequests() != 0 ||
+ run.Updated != 0 {
+ t.Errorf("the run after: %d fetched, %+v", world.fileRequests(), run)
+ }
+}
+
+// sameFile: an empty key, a row's from before keys, matches nothing.
+func TestAnEmptyFileKeyMatchesNothing(t *testing.T) {
+ if sameFile("", "") || sameFile("", "h/a") || !sameFile("h/a", "h/a") {
+ t.Error("sameFile")
+ }
}
// L15 and round 2's M2: a kept page is decided before its images, so a
diff --git a/internal/mapa/import_lows_test.go b/internal/mapa/import_lows_test.go
index 4877b31..03c415a 100644
--- a/internal/mapa/import_lows_test.go
+++ b/internal/mapa/import_lows_test.go
@@ -18,7 +18,7 @@ import (
func (world *importWorld) fileRequests() int {
count := 0
for _, request := range world.server.Requests() {
- if strings.HasPrefix(request.Path, "/secure.notion-static.com/") {
+ if request.File {
count++
}
}
diff --git a/internal/mapa/import_rerun_test.go b/internal/mapa/import_rerun_test.go
index fd710b8..5eae49f 100644
--- a/internal/mapa/import_rerun_test.go
+++ b/internal/mapa/import_rerun_test.go
@@ -64,12 +64,47 @@ func TestI2ARerunWritesNothing(t *testing.T) {
t.Error("a re-run of an unchanged workspace wrote a revision")
}
for _, request := range world.server.Requests() {
- if strings.HasPrefix(request.Path, "/secure.notion-static.com/") {
+ if request.File {
t.Errorf("a re-run downloaded %s", request.Path)
}
}
}
+// I2's other half, from the first real run: Notion rounds
+// last_edited_time to the minute (spec §25 note 17), so an edit made in
+// the same minute as the last run's survey carries the time that run
+// saw, on the page and on the block. It is picked up anyway: "changed"
+// is the rendered body against what Mapa holds (§13.2), never the edit
+// time. Two such edits in a row, each in that minute, are each picked
+// up, and a run after them writes nothing.
+//
+// Mutation (make mutate, first red 2026-11-22): a page whose Notion edit
+// time is the one last written is read as unchanged.
+func TestI2AnEditInTheSameMinuteIsPickedUp(t *testing.T) {
+ ws := newSmall()
+ world := newImportWorld(t, ws.Workspace)
+ world.connect(ana)
+ world.importAs(ana)
+ minute := ws.Objects[ws.handbook]["last_edited_time"]
+ for _, words := range []string{"Hello.", "Hello again."} {
+ ws.set(ws.handbook, 1, notiontest.Para(notiontest.Text(words)))
+ if ws.Objects[ws.handbook]["last_edited_time"] != minute ||
+ ws.Children[ws.handbook][1]["last_edited_time"] != minute {
+ t.Fatal("the edit moved an edit time: the test needs it held")
+ }
+ run := world.importAs(ana)
+ _, record, _ := world.pageTitled("Handbook")
+ if run.Updated != 1 || !strings.Contains(record.Body, words) {
+ t.Fatalf("an edit in the same minute: %+v, body %q", run,
+ record.Body)
+ }
+ }
+ if run := world.importAs(ana); run.Unchanged != 3 ||
+ run.Updated != 0 {
+ t.Errorf("the run after: %+v", run)
+ }
+}
+
// I3, untouched and kept (spec §13.2, D8). Two pages change in Notion,
// one of them renamed; one of those is edited in Mapa, and a third is
// renamed in Mapa. The untouched one updates as the runner, renamed
diff --git a/scripts/mutate/mutations_import.go b/scripts/mutate/mutations_import.go
index b2ba42e..99056b4 100644
--- a/scripts/mutate/mutations_import.go
+++ b/scripts/mutate/mutations_import.go
@@ -280,9 +280,37 @@ var importMutations = []mutation{
"TestI14AnImageGoneOrChangedIsFetchedAgain", edit{importImages,
"job.images.Held(ctx, prior.PublicID, entry.place.PageID) {",
"true {"}),
- inMapa("I14", "reuse ignores the block's edit time",
+ inMapa("I14", "reuse ignores the file's key",
"TestI14AnImageGoneOrChangedIsFetchedAgain", edit{importImages,
- "if found && prior.Edited == block.Edited {", "if found {"}),
+ "if found && sameFile(prior.Key, placed.key) {", "if found {"}),
+ // What comparing the minute-rounded edit time did, for a file
+ // replaced in that minute (§25 note 17).
+ inMapa("I14", "reuse ignores the file's key, the same minute",
+ "TestI14AnImageReplacedInTheSameMinuteIsFetched", edit{importImages,
+ "if found && sameFile(prior.Key, placed.key) {", "if found {"}),
+ inMapa("I14", "a permanent refusal outlives its file",
+ "TestI14ARefusalIsALineAndRemembered", edit{importImages,
+ "if found && sameFile(prior.Key, placed.key) {", "if found {"}),
+ inMapa("I14", "the key kept is the staged file's",
+ "TestI14AFileReplacedMidRunIsKeyedAsDownloaded", edit{importImages,
+ "\t\tplaced.key = fetched\n", "\t\t_ = fetched\n"}),
+ // Fable M1: the fake signs every read afresh, as Notion does, so a
+ // key that keeps the signature fetches every image on every run.
+ inMapa("I14", "the file key is the signed URL",
+ "TestI14AnImageIsAddedAndAttached", edit{importImages,
+ "key: notion.FileKey(block.File.URL),",
+ "key: block.File.URL,"},
+ edit{importImages, "\tkey := notion.FileKey(fresh.File.URL)\n",
+ "\tkey := fresh.File.URL\n"}),
+ inMapa("I14", "an empty file key matches",
+ "TestAnEmptyFileKeyMatchesNothing", edit{importImages,
+ "return kept != \"\" && kept == now", "return kept == now"}),
+ inMapa("I2", "an unchanged Notion edit time read as an unchanged page",
+ "TestI2AnEditInTheSameMinuteIsPickedUp", edit{importWrite,
+ "\tif entry.current.Title == entry.title &&\n",
+ "\tif entry.current.Origin != nil &&\n" +
+ "\t\tentry.current.Origin.Edited == entry.staged.Edited ||\n" +
+ "\t\tentry.current.Title == entry.title &&\n"}),
inMapa("I14", "no copy is tried", "TestI14ABlockOnASecondPageIsCopied",
edit{importImages,
"if added, ok := job.copyImage(ctx, entry, block); ok {",
@@ -307,10 +335,10 @@ var importMutations = []mutation{
inMapa("Low5", "the fix-up renders with no image lines",
"TestLow5TheFixUpKeepsImagesAfterAResume", edit{importJob,
"\t\timages = storedImages(entry)", "\t\timages = &pageImages{}"}),
- inMapa("R3M2", "a copy ignores the block's edit time",
+ inMapa("R3M2", "a copy ignores the file's key",
"TestI14AChangedSharedImageIsFetchedOnce", edit{importPlace,
- "other.Page == 0 || other.Edited != block.Edited ||",
- "other.Page == 0 ||"}),
+ "other.Page == 0 || !sameFile(other.Key, key) ||",
+ "other.Page == 0 || !sameFile(key, key) ||"}),
inMapa("R3M3", "Forget leaves notion_images", "TestM6ForgetDeletes",
edit{importCredential,
"err = tx.db.Where(\"1 = 1\").Delete(&NotionImage{}).Error",
@@ -345,13 +373,13 @@ var importMutations = []mutation{
inMapa("R3L7", "no lease check before a copy",
"TestL7BothImageWritesHoldTheLease", edit{importImages,
"\tif err := job.store.bookkeep(ctx, job.lease, noChange); " +
- "err != nil {\n\t\treturn nil, refusal{}, err\n\t}\n" +
+ "err != nil {\n\t\treturn nil, \"\", refusal{}, err\n\t}\n" +
"\tif added, ok := job.copyImage",
"\tif added, ok := job.copyImage"}),
inMapa("R3L7", "no lease check before an add",
"TestL7BothImageWritesHoldTheLease", edit{importImages,
"\tif err := job.store.bookkeep(ctx, job.lease, noChange); " +
- "err != nil {\n\t\treturn nil, refusal{}, err\n\t}\n" +
+ "err != nil {\n\t\treturn nil, \"\", refusal{}, err\n\t}\n" +
"\tadded, err := job.images.Add",
"\tadded, err := job.images.Add"}),
inMapa("R3L7", "quotaReason always names the person's",