Files
faunosteo/.claude/tasks/plans/2026-11-03-v1-2-6-editor.md

483 lines
51 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Plan: V1-2.6 editor level 1 (revised after challenge, 2026-11-03)
Contract `.claude/tasks/contracts/2026-11-03-v1-2-6-editor-1509.md` (criteria C1 to C34, CLARIFICATIONS [gated
2026-11-03] and [gated 2026-11-04]). Branch `feature/v1-2-anatomical-sheets`, worktree
`/home/bchanot/Documents/faunosteo-v1-2` (durable since 2026-11-04, LRN-114; execution ledger
`.claude/tasks/plans/2026-11-03-v1-2-6-execution.md`), base
7f618d0. Sandbox only (`pnpm db:sandbox`, containers `faunosteo_dbsandbox_*`); the `supabase_*_faunosteo`
containers are DEV: never touched, never a target. Every command runs with the worktree as an absolute,
verified cwd (LRN-110). One lot = one coherent change, committed and pushed by the orchestrator after its own
checks (`pnpm typecheck && pnpm lint && pnpm test:run`, plus the lot's checks).
Format note: the project's lot format (precedent `.claude/tasks/plans/2026-11-02-v1-2-5.md`), every choice closed
here; executors write the code and the tests. Reading list for every executor: the contract, this plan,
`docs/development/V1-2_ANATOMICAL_SHEETS.md` §6.2, §6.6, §8, §9.2-§9.4, §10, §11.1, `docs/design/v1-2-4/REVUE.md`
(ratified wordings), boards `04-editeur-desktop.png`, `05-lecture-seule-etroit.png`, `06-verification-etats.png`
(panel A only), the ts-rs types under `packages/core-wasm/types`.
## Architecture (closed decisions)
### Core and handle
- No Rust change (crates/** untouched): the core already offers `sheet.edit`, `sheet.dependents`, `sheet.empty`,
`clean_svg`, `PreviewSheet` with `replace_document` / `add_drawing`, `preview.state`, `view.canvas`. The wasm
module and its 600 000 B gzip budget are unchanged.
- The editor reuses `CataloguePreview` (`apps/app/src/catalogue/preview.ts`), extended, never duplicated: its kept
input (`document` text) and drawing list become mutable; `replaceDocument(text)` and `addDrawing(drawing)` call
the glue's `replace_document` / `add_drawing`. A new text is kept only after `replace_document`, the following
`preview.state` AND the optional `accept(state)` all succeed (`replaceDocument(text, accept?)`, ruling R2); when `state` fails without a trap, `replace_document(previous)` rolls the handle
back, so the handle, the kept input and the store never diverge. The rebuild after a trap (generation change)
uses the kept input, so a text or file that trapped is never kept and never re-read automatically (LRN-058).
Kept drawings are a map keyed by asset id (a re-added id replaces its entry; the builder counts entries), holding
only drawings the core accepted (16 at most; `caps: drawings` gets its own message, a reload frees them). Every
accepted `replaceDocument` / successful `addDrawing` bumps a store counter `handleVersion` (never a refused one).
- The draft handle is built with NO drawing (a draft builds with its drawings missing, §10; `add_drawing` works on
a draft and `view.canvas` looks drawings up live), then each downloaded drawing is added with `addDrawing`; a
refusal or a failed download becomes that drawing's state (`missing`, `hash mismatch`), never a load failure: one
bad drawing never blocks authoring (§9.3). A load dropped by the session token frees the preview it built;
`close()` frees the session's preview.
- Wrappers `apps/app/src/editor/core/editOps.ts`: `applyEdit(text, command)` (input text built as
`{"document":<text>,"command":<json>}`, output `{document}` serialised back with `JSON.stringify`),
`dependentsOf(text, key)`; `cleaning.ts`: `cleanSvg(bytes)`, `composeCleaningPreview(stored)` (a throwaway
`CataloguePreview`: `sheet.empty` → `sheet.edit insert` a detail view `view-<random>` under the main view with a
random uuid as its own drawing, the stored bytes added under that uuid, `canvas(<that view id>)`; the scope
`fv.view-<random>.` is unique in the page; freed when the dialog closes). The original file is never rendered.
- Content comparisons (recovery offer, unsaved flag) compare parsed JSON deeply (`sameDocument(a, b)`), never raw
strings: the server text is in jsonb key order, the core's in serde order.
### Ids
- `<prefix>-<10 chars a-z2-7>` from `crypto.getRandomValues`, prefixes `view`, `anno`, `cat`, `ref`, `zone`,
`fcat`, `node`; a `duplicate_key` answer regenerates once and retries; no document walk. Region codes are typed
at creation (the core checks the grammar), read-only afterwards.
### Store and sessions
- One Zustand store `editorStore`, module-level; `open(versionId, userId)` returns a session token, `close()`
invalidates it; EVERY async continuation (load, downloads, save, upload, conflict read, submit) checks the token
before writing and drops its result otherwise (StrictMode runs open → close → open in dev, the e2e and the
trial). DOM handlers read `getState()` (LRN-043).
- The page holds the document as ONE JSON text (`documentText`) and the saved pair (`savedText`, `savedRevision`)
taken from the SAME `get_sheet_version` answer (`revision` and `document` together; the admin read is never the
revision source). `catalogue/catalogue.ts` `readVersion` is exported and gains a draft mode that accepts
`draft`, returns `revision` and returns per-drawing settled results (`Promise.allSettled`, a failure kind per
asset id) instead of failing the load; the catalogue's all-or-nothing path is unchanged: no second loader.
- Every change is one `sheet.edit` command run on commit (blur with a changed value, Enter, a confirm button,
pointer-up), never per keystroke (BDR-050); field typing stays local; a field with a pending value commits it in
its unmount cleanup (mode switch). The new text is stored only after `replaceDocument` and `preview.state`
succeed; a refused command leaves everything unchanged and shows its closed kind next to the control.
- Undo/redo: arrays of texts; each entry's UTF-8 size measured once (`TextEncoder`); oldest undo entries dropped
while both stacks exceed 8 388 608 B; a new commit clears redo; save keeps both; a reload of the server draft
(« Recharger », discard after an older-copy restore) and « Annuler les modifications » clear both. Controls:
icon buttons « Annuler » / « Rétablir » in the tool column under the zoom; Ctrl+Z and Ctrl+Shift+Z outside text
fields (no Ctrl+Y).
### Creation of elements (no invented labels)
- No element is inserted with default labels. Each creation collects the fields the core requires, then one
`insert`:
- annotation (drawn or keyboard): the geometry is held as a pending outline in the overlay and the properties
panel opens in a « Nouveau point / Nouvelle zone / Nouvel accès » state with Nom (FR), Nom (EN), Catégorie
(first category preselected), Latéralité (no preselection, required), Vue ouverte (link, required), then
« Créer » inserts; « Annuler » drops the pending element. Zone de constats and Région vertébrale optional;
- annotation category: name FR/EN, colour optional; reference: type, citation, URL, DOI; region: code, name
FR/EN, count; detail view: name FR/EN, parent, own drawing or crop values; finding zone: name FR/EN; finding
category: kind, name FR/EN; node: name FR/EN.
- A blank optional field is sent as `null` where the type is nullable and omitted where it is an optional key
(`LocalizedOptionalText`); never "" (the core refuses empty strings).
### Rendering and canvas
- Only `view.canvas` trees are rendered, inserted with `DOMParser` + `importNode` through `buildView`, exported
from `CatalogueCanvas.tsx` and reused. Read-only modes mount `CatalogueCanvas` as is (board 05). The edit canvas
reuses `framing.ts` and `useFraming` with one added option `canPan(event)` (false when the press starts on a
selected marker or a drawing tool is active).
- A page-drawn overlay `<svg>` (numbers only: selection outline dashed dark, vertex circles, the tracing in
progress, the pending or dragged outline, the crop rectangle) sits over the drawing inside the same transformed
container, with the composed root's `viewBox` and `preserveAspectRatio`. Pointer → drawing coordinates through
the overlay's `getScreenCTM().inverse()`. `docs/ANNOTATION-RENDERING.md` gets an « Editor overlay (V1-2.6) »
section first, stating it draws no annotation and holds numbers only.
- Only the active tab panel is mounted, so one view's canvas is never twice in the DOM.
- Canvases follow the handle: the edit canvas rebuilds on `[viewId, handleVersion, attempt]`; the read-only
`CatalogueCanvas` is mounted with `key={handleVersion}`, so a restore, an upload or a drawing added after the
first paint is shown (no stale tree, no stuck `no_asset` notice).
- Pointer handling: `setPointerCapture` on press; `pointercancel` and `lostpointercapture` drop the drag with no
command; a switch to read-only mid-drag drops it.
### Tools (board 04)
- Sélectionner/déplacer, Point, Zone, Accès à une vue détaillée, separator, Zoom (−, +, Ajuster), separator,
Annuler, Rétablir. Select: a press on a marker selects it; a drag from a selected circle or polygon moves it as
a block (overlay preview; on pointer-up one `update` with coordinates translated by the drawing-unit delta,
rounded to 2 decimals); a drag on empty space pans. Point: one click holds a pending circle placed by the rule
« Default point and the frame » below. Zone and link: clicks add vertices;
Enter, a click on the first vertex or « Fermer le tracé » closes (3 vertices at least); Escape or « Annuler le
tracé » drops it. A detail-view link opens a direct child of its own view (core rule
`annotation.opens_view.invalid`): the link tool is enabled only while the current view has a direct detail
child (hint otherwise), and « Vue ouverte » lists only those children, in creation and in properties; every drawing tool
is disabled with « Créez d'abord une catégorie d'annotation (onglet Général). » while there is none.
- Default point and the frame (owner 2026-11-03, C26). The frame F = (x, y, w, h) is the composed root's `viewBox`
read from the core's `view.canvas` output (the view's `view_box`, else its drawing's `viewBox`; origin offsets
kept; drawing units), parsed from the attribute TEXT with `Number` (never `viewBox.baseVal`, held in f32).
Measured views only (re-check F1): F is read, and creation or geometry edits are possible, only while the view's
drawing state is `ok` AND the core's report carries no `view.frame.unknown` for that view. The core skips every
other view (no drawing held, missing, hash mismatch, rejected: `frame_faults` frame.rs:281-284; no usable frame:
only `view.frame.unknown`, frame.rs:285-288; the canvas then shows the fallback `0 0 100 100`, compose.rs:43), so
its silence there proves nothing: on such a view the drawing tools, the keyboard « Ajouter … » buttons and the
numeric geometry fields are disabled with the hint « Ce dessin n'est pas mesurable : ajoutez ou corrigez son
illustration (onglet Vues et illustrations) avant de placer ou de déplacer des éléments. », and `accept` refuses
any creation or geometry commit whose view is not measured (checked on the post-commit state, so a commit
cannot rely on a view that the same commit made unmeasurable). Default radius `r0 = min(12 + 0.03 × max(w, h), min(w, h) / 2)`, floored to 0.01. The
page only PROPOSES geometry (arithmetic); the core decides. TypeScript carries no copy of the core's frame or size
rules: no 4 px constant, no preview sizes, no twin radius, no edge tolerance.
- Proposal at click (c = the clicked point, rounded to 0.01; d = its distance to the nearest edge of F): d ≥ r0 →
candidate A (c, r0); d < r0 → candidate B (c, floor₀.₀₁(d)), the clicked position kept with a smaller
radius, only when that radius is at least 0.01 (otherwise straight to C below; the edge is inclusive in the
core, so no extra margin). A click outside F proposes nothing (hint « Cliquez à l'intérieur du dessin. »). Keyboard
« Ajouter un point »: the centre of F with r0 (fits by construction).
- The core decides at « Créer »: the insert runs through `commit(command, { accept })`: `sheet.edit` →
`replaceDocument` → `preview.state`, then `accept(report)` reads the geometry issues whose path names the new
annotation (`editor/issues.ts`); a refusal rolls the handle back with `replaceDocument(previous)` before
anything is kept (no store change, no `handleVersion` bump, no copy write). A new point is refused on
`annotation.geometry.out_of_frame` and `annotation.geometry.too_small`.
- Correction, never silent: when B is refused, or A is refused `out_of_frame` (float edge), the page computes
candidate C (radius r0, centre clamped per axis into [x + r0, x + w − r0] and [y + r0, y + h − r0], rounded
inward to 0.01; when that rounding leaves an empty interval, r0 = min(w, h)/2 with an origin off the 0.01
grid, the exact clamped value is used: the core accepts any decimals) and shows it in the overlay with the original click marked apart (a hollow cross) and the
message « Le point ne tient pas à l'endroit choisi. Position corrigée proposée : x = …, y = …. » with
« Utiliser cette position » / « Annuler ». Confirm → C is inserted through the same `accept`; the numeric
fields and the properties show C's values only (nothing refers to the click afterwards). « Annuler » keeps the
pending point at the click so the user can change its radius or position, or drop it. A refusal of C, or
`too_small` on A or C (r0 already capped: an extremely elongated frame), creates nothing and shows the core's
issue message beside the creation panel.
- Geometry errors (owner 2026-11-04, C33): an annotation's geometry errors are the core's Error issues at
`annotations[i].geometry` (`annotation.geometry.missing`, `out_of_frame`, `too_small`, `interior_too_small`),
mapped to the annotation's id through the document of the same state (an insert, a delete or a reorder shifts
the index); « before » is the report of the last accepted state the store holds, « after » the report of the
candidate state. One rule for every geometry commit (creation insert, move by drag, numeric cx, cy, r or
vertex, vertex added or removed, polygon replacing a path): `accept` refuses it unless the changed annotation
carries no geometry error after it, whether it was new, valid or already invalid before (owner rules 1, 2
and 5). A refusal rolls the handle back (no store change, no `handleVersion` bump, no copy write); the message
is the core's issue (« L'élément sortirait du cadre. » for `out_of_frame`). A radius the user types that the
core reports `too_small` is therefore refused, never committed (rule 2). Zones and links: the creation insert
is refused the same way (tracing kept for numeric correction or cancel).
- Repair through a temporary form (owner rules 3 to 5): the geometry fields of the properties panel (cx, cy, r;
the vertex rows; « Ajouter un sommet » / « Retirer ») form one group held in component state. Enter or leaving
a field proposes the WHOLE group as one `update`; accepted → committed; refused → nothing changes in the
document, the fields keep the typed values marked « non appliqué » with the core's issue message and a
« Revenir aux valeurs enregistrées » action. So an annotation already invalid (inherited, restored) is
repaired by typing a coherent set (e.g. cx then cy) applied once it satisfies the core, never through an
invalid intermediate document; its error stays in Vérification and on the properties panel until the fix is
applied (rule 6: no diagnostic hidden, an invalid annotation never shown as valid). Selecting another element
drops an unapplied group (it was never in the document). Drag on an already-invalid annotation follows the
same rule: a drop that leaves it invalid is rolled back with the message. The save path and the server's
verdict are unchanged: a draft that already holds geometry errors saves as before (the core's rules are never
weakened, nothing is added to them) and the submit stays the server's decision.
- Frame changes (a view's `view_box` update, a drawing set or replaced on a view, rule 7) use `accept` too:
refused when any annotation that had no geometry error before has one after, the refusal listing those
annotations; an annotation already invalid does not block it. Refused too when a measured view holding
annotations becomes unmeasured (the core then goes silent on them: their validity would vanish unseen).
- No move without intent: numeric fields show the stored number exactly (no display rounding; the equine draft
holds values such as 743.0451049804688) and commit only when the typed number differs from it; a drag starts
only after the pointer travelled 4 CSS px from the press, so a click with jitter on a selected marker never
moves it (owner 2026-11-04: a plain click still selects, the keyboard path is untouched, pointer events serve
mouse, pen and touch alike; the canvas sets `touch-action: none` only while a drawing tool or a drag is
active, so a touch scroll of the page still works otherwise).
- Unmeasured views, read-only geometry (owner 2026-11-04, C32): existing annotations of such a view stay shown
when the canvas can draw them and stay selectable; their properties show geometry as read-only text, drag is
off, and the hint names the « Vues et illustrations » tab where the drawing is fixed. The fallback frame
`0 0 100 100` is never read as a frame: no proposal, no `accept` verdict, no message relies on it.
- Unit tests on the Node core (C26): frames 40×30, 20×20, 100×300 (detail crops), 500×380, 640×480, 200×150, very
elongated 1000×30 and 4000×200, non-zero origins (e.g. `-50 20 40 30`); clicks on each edge, each corner, at
distance exactly r0 and r0 − 0.005 from an edge; coordinates near 2^20; r0 = min(w, h)/2 exactly; a non-grid
origin with r0 = min(w, h)/2; unmeasured views (a crop of span 0.5, a drawing without `viewBox`, a missing
drawing: every creation and geometry commit refused); repair (C33): an inherited out-of-frame point, then
polygon, whose intermediate values (cx only) are refused with the document unchanged and whose coherent set
is applied, a restored copy holding an invalid point repaired the same way; a valid point given a typed
radius the core reports `too_small` refused; a drag dropping a valid point half out rolled back; a `view_box`
change refused when it pushes a point out or makes it `too_small`, accepted when only an already-invalid
point is affected; each case asserts the proposal, the core's verdict on it and that no page action ever
leaves an annotation with a geometry error it did not already have.
- Keyboard path (C7): under the canvas, « Ajouter un point », « Ajouter une zone », « Ajouter un accès » hold a
pending element at the frame centre (zone and link: a triangle of 10 % of the smaller side) and open the
creation panel; then every coordinate is edited in numeric fields (cx, cy, r; rows « n | x | y »; « Ajouter un
sommet » after the selected row or the last; « Retirer » while more than 3 remain).
- A `path` annotation: shown and selectable; « Remplacer par un polygone » starts a tracing whose result replaces
its geometry; never moved; its path data never shown as editable.
- Selection also from the annotation list of the view (name, kind, review badge; keyboard reachable); the tag
« Sélection : <type> « <nom> » » over the drawing (board 04).
### Panels and tabs
- Properties panel (board 04): Nom (FR), Nom (EN), Catégorie, Couleur (« de la catégorie » or a hex value),
Latéralité, Région vertébrale, Zone de constats (point, zone), Vue ouverte (link), coordinates, review badge
(« À confirmer », « Relu », « Hérité, non relu »), « Marquer comme relu » (`set_status reviewed`, while not
`reviewed`), « Remettre à confirmer » (`set_status to_confirm`, while `reviewed`), « Supprimer » (confirmation;
a refusal lists the dependents).
- Général: names, description and scope disclaimer FR/EN, attribution (authors add/remove, licence, notes); section
« Catégories d'annotation » (list, add, rename, colour, delete with dependents).
- Vues et illustrations: main view (name, drawing state ok / missing / rejected with its detail, « Choisir une
illustration »), detail views (add, parent, own drawing or crop: four numeric `view_box` fields with the parent's
canvas beside them and the crop rectangle in the overlay; rename; delete with dependents).
- Constats: tree zones → categories → nodes (depth ≤ 8), `role="tree"` / `treeitem`, arrow keys; categories and
nodes carry a review badge, zones none (FindingZone has no status); actions: add zone, add category, add node
(disabled at depth 8), ↑ / ↓ (`move`), « Marquer comme relu » (zone and category: `mark_reviewed`; node:
`set_status reviewed`), « Remettre à confirmer » (categories and nodes only), delete with a confirmation listing
the descendants and, on refusal, the dependents.
- Références: list + form (type, citation, URL http/https checked by the core, DOI). Vertèbres: list (code, name,
count, optional range), add, edit, ↑ / ↓, delete.
- Read-only renders through shared field components that show their value as text when `readOnly` (action buttons
hidden by the same flag): each tab stays one component.
- Vérification (board 06 A): badges « N erreurs bloquantes » / « N éléments à confirmer »; one notice per error
issue with its FR/EN message and « Aller à … » when the path names an element; warnings apart; the info notice on
`to_confirm` elements; completeness; statuses per group; size « <n> o sur 2 097 152 o » from
`report.document_bytes`, caps exceeded named; « Note de soumission (obligatoire) » (trimmed 1 to 1 000
characters); « Soumettre à la revue » disabled with its hint while errors exist (« Corrigez les N erreurs
bloquantes pour soumettre. »), while unsaved (« Enregistrez le brouillon avant de le soumettre. ») or while the
note is empty. Submit → `submit_sheet_review(version_id, savedRevision, note)`; success → the admin read and the
version are reloaded, the page shows the `frozen` read-only state. No « Prévisualiser », no withdrawal (V1-2.7).
### Save, conflict, recovery
- Save: « Enregistrer » sends `sentText` with `expected_revision = savedRevision`, no change note; the answer is
parsed as `{revision: number}` (`unavailable` otherwise). Success: `savedText = sentText`, `savedRevision =
answer`, unsaved = `!sameDocument(current, sentText)`; the recovery copy is removed when unsaved is off, else
rewritten on the new revision. `draft.unchanged` sets the saved pair to (`sentText`, the `expected_revision`
sent). Other kinds → header notice, document and copy kept.
- Conflict (`draft_conflict`, owner 2026-11-03, C29): the page reads `get_official_sheet_admin` and opens a
dialog. N = `draft_version.revision` of that read; the author and date come from M8 `draft_last_save` only when
its `revision` equals N, otherwise they are omitted (never invented): « Une autre session a enregistré la
révision N » + « par <nom>, le <date heure Paris> » when known (a neutral « depuis une autre session de votre
compte » when `saved_by` is the caller). When that read fails, answers without `draft_version`, or the answer
does not parse, the dialog says « Une autre session a enregistré une version plus récente de ce brouillon. » and
offers « Recharger » and « Réessayer » (repeats the read) only; « Garder ma version » is disabled with the hint
« Révision du serveur inconnue : rechargez ou réessayez. »; no revision number or author is shown. « Recharger » → a confirmation
« Abandonner vos modifications et recharger la révision N ? » → reload of the server draft (text and revision
from one `get_sheet_version`, the listed drawings the handle lacks downloaded and added), both stacks cleared,
copy removed; « Garder ma version » → a confirmation
« Remplacer la révision N (<nom>, <date>) par votre version ? » (author and date only when known) → save with
`expected_revision = N`; the server's atomic revision check decides at write time; a new conflict re-reads and
re-opens the dialog with the new N, never writes; « Annuler » changes nothing.
- Local recovery copy (C13, C27, C28): a TEMPORARY copy in this tab's sessionStorage (the report editor's pattern),
never a server save and never called one. Key `osteo:sheet-draft:<userId>:<versionId>`, value
`{"v":1,"user_id","version_id","sheet_id","sheet_name","revision","written_at","document":<text>,
"drawings":[{"asset_id","sha256"}]}` (revision = the saved revision the edits started from; `sheet_name` is a
display label taken at write time). Written SYNCHRONOUSLY by a store subscription on each committed change while
unsaved and no offer is pending, through `writeOrRemove` exported from `state/persistence.ts`; its boolean is
kept in the store.
- Removal, only by an explicit outcome: a successful save that leaves nothing unsaved; « Annuler les
modifications » confirmed; « Ignorer la copie » confirmed; « Recharger » confirmed (conflict); « Abandonner
cette copie » confirmed (cap list below). Never on undo back to the saved content (the copy keeps the last
unsaved document), never by automatic eviction, never while an offer is pending.
- Offer on opening, blocking (owner 2026-11-03): a copy of this account and version whose document differs
(`sameDocument`) from the server's opens the store state `recovery = pending`. While pending (and while
`refused` and `restoring`, below) the STORE refuses every commit, undo, redo, save and submit and every action
that would remove the copy other than « Ignorer la copie » (« Annuler les modifications » included) (kind
`recovery.pending`, not only disabled buttons, keyboard shortcuts included) and the copy subscription neither
writes nor removes. A stored copy that cannot be read (malformed JSON, `v` ≠ 1, `user_id` or `version_id` not
matching its key) is never overwritten: it opens `recovery = refused` with « Ignorer la copie » only (the report
editor's quarantine pattern) and a notice that names the loss (owner 2026-11-04): « Une copie locale de ce
brouillon existe dans cet onglet mais ne peut pas être lue. Elle n'est pas enregistrée sur le serveur.
L'ignorer la supprime de cet onglet : son contenu sera perdu. » (label proposal); kept until that explicit
abandonment, never replaced or removed otherwise; editing stays blocked until then. The leave guard is armed while unsaved OR while `recovery` is not `none`.
Consultation stays: tabs, selection, list, zoom, pan, properties as text (the read-only field components).
Notice under the header: « Une copie locale temporaire de ce brouillon existe dans cet onglet (révision R,
<heure>). Elle n'est pas enregistrée sur le serveur. Choisissez avant de modifier le brouillon. » (+ « Elle est
basée sur la révision R ; le serveur est à la révision M. » when R < M) with « Restaurer la copie » and
« Ignorer la copie ».
- « Restaurer la copie »: `recovery = restoring` (both buttons disabled) while the copy's document goes through
the core (`replaceDocument` + `preview.state`) and the copy's drawings the page does not hold are downloaded
(`downloadSheetDrawing`) and added (`addDrawing`; a failed one becomes that drawing's state); the continuation
checks the session token and that `recovery` is still `restoring`, then applies the result in ONE store update
(`documentText`, `savedRevision = R`, `staleBase`, unsaved, `recovery = none`) so the synchronous copy
subscription never sees a mixed state; `savedText` stays the server text (it drives « unsaved » and submit).
Unit test: the copy rewritten after an R < M restore still carries R. The expected revision stays the
copy's base R (`savedRevision = R`), never converted to the server's M; when R < M the store flag `staleBase`
is set, so the first save meets `draft_conflict` and its dialog (author and time when known) and needs the
« Garder ma version » confirmation; « Annuler les modifications » with `staleBase` takes the « Recharger » path
(server text and revision M). A copy the core refuses (or that traps) is reported (« La copie locale ne passe
pas le contrôle du document : <kind>. Elle est conservée. »), kept, never applied, never re-read automatically
(LRN-058): `recovery = refused`, « Restaurer la copie » disabled, editing stays blocked until « Ignorer la
copie ».
- « Ignorer la copie »: a confirmation « Abandonner la copie locale non enregistrée (révision R, <heure>) ? Elle
sera supprimée de cet onglet. » with « Abandonner la copie » / « Annuler »; confirmed → copy removed,
`recovery = none`, editing resumes from the server version.
- Conflict read checks (re-check G): N is used only when `draft_version.version_id` is the edited version, else
the failed-read variant. A `draft_conflict` answered by `submit_sheet_review` opens the same dialog and never
re-submits automatically; submit is refused while `staleBase` is set (hint « Enregistrez le brouillon avant de
le soumettre. »).
- The offer shows only in edit mode or `narrow`. In a mode that cannot save (`rights`, `frozen`, `historical`,
`inactive`) the copy is left untouched (never offered, written or removed) and the mode notice adds « Une copie
locale non enregistrée de ce brouillon existe dans cet onglet ; elle ne peut pas être utilisée dans cet état. »
- Cap and quota: at most two copies of OTHER versions of the account are kept beside the current one; nothing is
ever evicted automatically (every stored copy is pending or live; resolved copies are removed at resolution).
When writing the current copy is impossible because the cap is reached, or `writeOrRemove` fails (quota), the
write flag is false and a notice lists the account's other copies (« <sheet_name> · révision R · <heure> »,
each with « Ouvrir ce brouillon » and « Abandonner cette copie », the latter confirmed as above); after an
abandonment the current copy is written again at once. Copies of another account are never listed, offered or
removed. Unit tests: cap reached (third version refused, both others kept), quota exceeded (`setItem` throws),
a pending copy kept through commit, undo, redo and save attempts, removal cases, another account's copies
untouched, abandon then retry.
- Header status: failure variants only (board 04 keeps « Révision N · modifications non enregistrées »):
« Copie locale impossible (stockage plein) » and « Copie locale impossible : deux autres brouillons ont déjà une
copie dans cet onglet ». Every message that promises kept work reads the real write flag and says the copy is
temporary and limited to this tab: session or MFA lost (`session_expired`, `rights.mfa`) and an unsaveable draft
(`draft.frozen`, `sheet.inactive`, `rights.capability`) say « une copie locale temporaire existe dans cet onglet »
only when the last write succeeded, otherwise that the unsaved changes cannot be kept.
- Leave guard (`useLeaveGuard`) armed while unsaved or while a recovery offer is not answered (`recovery` ≠ `none`),
disarmed as soon as both are off (a confirmed save, an explicit abandonment); never kept armed otherwise. Its
limits are written in the owner trial guide and BROWSER_TESTS.md (owner 2026-11-04): `beforeunload` is not
reliable on mobile browsers (iOS Safari, a tab killed in the background) and its text is the browser's own; the
sessionStorage copy is the only fallback there and dies with the tab.
### Upload (§9.2-§9.3)
- File input (`.svg`, `image/svg+xml`), size ≤ 2 MiB checked before reading; bytes → `clean_svg`. `rejected` →
message per reason, nothing else. `cleanable` → dialog with the core-composed cleaned drawing, the removed names
(the `<style>` element named when `style_removed`), « Nettoyer et utiliser cette version » / « Annuler ».
`clean` → no dialog.
- Then: `register_sheet_asset(sheet_id, sha256, byte_size, file_name)` with the core's sha256 and size of
`stored`; read the row (`listSheetAssets(sheetId)`: id, sha256, byte_size, uploaded_at); if `uploaded_at` is set,
nothing is uploaded or confirmed (§9.3 step 2); if pending, upload `stored` at `<sha256>.svg` (`image/svg+xml`,
no upsert): ok → confirm; already present (HTTP 409, or 400 with `statusCode` "409") → confirm; refused by the
policy (403, or 400 with `statusCode` "403": a pending row registered by another account) → `confirm` once (the
other account's object may already be there); `upload_missing` then → closed code `upload.pending_other`; then `confirm_sheet_asset_upload(asset_id)` (`upload_missing`, `size_mismatch`). Then the
stored object is downloaded and added with `addDrawing`: `drawing_hash_mismatch` → `object_conflict`; `caps` →
its message. Then the view the upload started from gets the drawing (`update` view with `svg_asset_id`).
- Codes with FR/EN messages: `size_mismatch`, `hash_mismatch`, `svg_rejected` with the reason, `svg_active_content`,
`svg_not_canonical`, `too_large`, `upload_missing`, `object_conflict`, `upload.pending_other`, `caps`, and the
server kinds through `failureMessage` (allowlist extended).
### Modes, permissions, layout
- Edit mode needs, as a display rule only: an active `sheet_editor` own grant AND the admin or owner platform role
(`grant_active` needs both), a viewport ≥ 1 024 px, no freezing round, not the historical sheet, an active sheet.
Otherwise read-only with the reason's notice: `narrow` (board 05: badge « Lecture seule » with the lock icon,
notice title alone « L'édition nécessite une largeur d'écran d'au moins 1 024 px. », L15), `rights`, `frozen`
(« Revue n° N · vérification en cours » for `verifying`, the round status label otherwise, link to the
overview), `historical`, `inactive`. Unsaved work in memory survives a switch to narrow and back.
- Permission states on the route (BDR-099 order): own grants `loading` → waiting; a `rights.*` answer from the admin
read → « Accès non autorisé »; own grants `failed` → `PermissionsUnavailable` with « Réessayer »; `not_found` →
`SheetNotFound` (exported from `AdminSheetRoute.tsx`); no draft → notice + link to the overview.
- Tabs: wide, all seven (board 04); narrow (board 05), static lists: 640 to 1 023 px « Général, Annotations,
Constats, Vérification » + « Plus »; below 640 px « Annotations, Vérification » + « Plus »; « Plus » is a
disclosure (`aria-expanded`) listing the others; no width measurement.
- Layout: `AppLayout` drops `max-w-4xl` for `/app/admin/sheets/:sheetId/draft` (`matchPath`). From 1 280 px board
04's three columns; from 1 024 to 1 279 px the properties card goes under the canvas (tools + canvas columns),
the tab row scrolls within itself and the header wraps; no page horizontal scroll at 1 024 px.
- Links: the overview shows « Ouvrir le brouillon » (edit possible) or « Consulter le brouillon » when a draft
exists; A1 creation and W1 working copy navigate to `/app/admin/sheets/<id>/draft`.
### i18n
- Keys `editor.*` in fr.ts and en.ts (parity tests); ratified wordings verbatim (REVUE.md, contract §17.9, §17.11,
L15); every new label listed in `.claude/audits/2026-11-03-v1-2-6-label-proposals.md` for the owner's separate
review, none declared approved.
## Lots
| Lot | Content | Criteria | Checks |
|---|---|---|---|
| A | M8 `supabase/migrations/20261103100000_sheet_draft_last_save.sql`: redefines `public.get_official_sheet_admin` only (the list and the summary helper untouched) adding `draft_last_save` = `{revision, saved_at, saved_by: private.sheet_admin_person(actor)}` from the newest `audit.audit_logs` row with `resource_type = 'anatomical_sheet_version'`, `resource_id` = the draft, `action = 'anatomical_sheet_version.saved'`, `metadata->>'revision'` = the draft's revision, else null; body otherwise identical to M7; privileges restated as M7 has them. pgTAP `supabase/tests/023_sheet_draft_last_save.sql`: null on a fresh draft, actor and time after a save, the second editor after a second save, null after a non-save content write, same refusals as M7, no new privilege. `packages/supabase` schema `draft_last_save` (nullable). Sandbox fresh + upgrade from M7; `db:types --check`. Contract §12.3 and §16.7 amended (read migration, owner 2026-11-03) | C12, C18 | PGlite, `db:sandbox test-db`, types |
| B | `packages/supabase/src/sheets.ts`: `registerSheetAsset`, `listSheetAssets(sheetId)`, `uploadSheetDrawing` (→ `'uploaded' \| 'present'`, `upload.pending_other` on a policy refusal, Storage errors read on HTTP status and body `statusCode`, checked against the installed storage-js error type), `confirmSheetAssetUpload`, `parseSaveAnswer`; new kind `upload.pending_other`; exports; unit tests; sandbox test `packages/supabase/tests/sandbox/sheet-editor-assets.sandbox.ts` with bytes unique per run (pattern of `sheet-fixtures.ts`): register, upload, confirm, row read, second register of a confirmed hash (no upload), second editor on a pending row (`upload.pending_other` with its own statusCode) | C6 | unit, sandbox |
| C | `CataloguePreview` extension (mutators, kept input on ok only, accepted drawings only); `editor/core/editOps.ts`, `cleaning.ts`, `editor/ids.ts`, `sameDocument`; `CatalogueCanvas` exports `buildView`; `useFraming` option `canPan`; unit tests on the Node core: rebuild after a forced generation change keeps the replaced text and the added drawing, a refused text is not kept, a bad drawing refused alone, the cleaning preview's scope | C2, C3, C15, C17 | unit |
| D | `editor/state/editorStore.ts`, `undo.ts`, `recovery.ts`, `editor/issues.ts`; `persistence.ts` exports `writeOrRemove`; unit tests: session token drops late answers, commit, refusal unchanged, undo bound, redo cleared, save with commits in flight (sent text kept), save unchanged, conflict paths (reload clears stacks, keep mine with confirmation), recovery write flag, removal cases (none on undo back to saved), restore round trip through the core, older-revision restore keeps R and `staleBase`, pending offer refuses commit/undo/redo/save/submit and never writes or removes the copy, refused copy kept and blocking until ignored, ignore needs confirmation, cap and quota with explicit abandonment and no eviction, other account untouched; `commit(command, { accept })` with rollback before anything is kept; `readVersion` draft mode (export, `draft` accepted, `revision`, per-drawing settled results; ruling R1, moved from E); conflict read: N from `draft_version.revision`, author only when `draft_last_save.revision` = N, failed read → no « Garder ma version » | C11-C14, C27-C29 | unit |
| E | Route `AdminSheetDraftRoute.tsx`, App.tsx, AppLayout width, header, tabs (wide and narrow), modes and permission states, blocking recovery offer (« Restaurer la copie » / « Ignorer la copie », consultation only while pending), cap/quota notice with the other copies, conflict dialog (known N and author, failed read with « Recharger » / « Réessayer »), leave guard, overview links, A1/W1 landing, shared read-only field components; `failureMessage` allowlist; i18n | C1, C11-C13, C16, C27-C29 | unit |
| F | Général (+ annotation categories), Références, Vertèbres; shared delete-with-dependents dialog | C4, C5 | unit |
| G | Vues et illustrations + upload flow | C6, C17 | unit |
| H | `docs/ANNOTATION-RENDERING.md` overlay section first; Annotations: canvas, overlay, tools, list, creation panel, properties panel (geometry group applied whole, « non appliqué » state), keyboard creation, undo/redo controls; default point rule with the corrected-position confirmation and the `accept` hook on every geometry commit (« Default point and the frame »: measured views only, read-only geometry elsewhere, repair rules) with its Node-core unit tests | C7, C8, C14, C17, C26, C32-C34 | unit |
| I | Constats tree | C9 | unit |
| J | Vérification panel + submission | C10 | unit |
| K | e2e `apps/app/e2e/shell/editor-*.spec.ts` reusing `createAccount`, `assignRole`, `seedGrant`, `enrolVerifiedFactor`, `stepUpAdmin`, `seedOfficialSheet`, `expectAccessible`, `expectNoHorizontalOverflow`, `dropLateReplays`; adds editor-only helpers. A2 (hostile refused, Inkscape export cleaned, attach, detail view by crop; both upload outcomes accepted), A3 (points, zones, links by clicks and by keyboard, move, numeric edits), A4 (zones, categories, nodes, refs, regions, reorder, mark reviewed, delete with dependents), journey (the brief's §3 steps 1-12 with two editor accounts: creation, upload, detail view, points/zones/links, categories and findings, save, reload with the beforeunload dialog accepted and the recovery offer, conflict, submit, round `verifying` read back in SQL, no error shown while elements are `to_confirm`), access (reviewer-only read-only, editor grant without admin role read-only, account without capability refused), narrow (320, 375, 800 px read-only, no horizontal scroll; 1 024 px edit without horizontal scroll), axe on editor and read-only, the equine working copy opening (sets aside an active copy first, as `sheets-concurrency.sandbox.ts` does); owner tests (C30): concurrent save between two sessions, older-copy restore then save → conflict dialog then « Garder ma version » confirmation, a pending recovery offer blocks editing until answered, permission changes during an open editing session (grant revoked, grant expired, admin role removed: the next save is refused with its message, the copy wording true), a click near the edge of a detail crop (corrected position shown, confirmed, cancelled), hostile and valid drawing imports, keyboard-only creation and numeric edits; commit latency measured on the equine copy and on a synthetic document near 2 MiB (reported; budget 500 ms per commit on the equine copy); `docs/development/BROWSER_TESTS.md` | C16, C20, C21, C26-C30 | `e2e:shell` on a fresh sandbox |
| L | Owner trial: `scripts/db-sandbox.sh` subcommands `trial` (its own gateway container `faunosteo_dbsandbox_trial_gateway` on its own loopback port, refusing to start when that container exists, + Vite dev server on 127.0.0.1:5193 whose proxy forwards `/auth/v1`, `/rest/v1` and `/storage/v1` to that gateway so the browser stays same-origin (no CORS change), proven by the manual run; foreground, Ctrl+C stops both), `trial-account <email>` (password at a hidden prompt, confirmed account, nothing secret printed), `trial-grant <email> <kind>` (email and kind checked against fixed patterns and passed as psql variables; for `sheet_editor` / `sheet_publisher` also `private.assign_platform_role(null, <id>, 'admin')`, the same SQL as the e2e helpers); `docs/development/V1-2-6_OWNER_TRIAL.md` (commands, URL, account, TOTP enrolment, journey, operations, expected results, the freeze after a submission with no worker and no withdrawal, teardown); label proposals file | C23 | script review, manual run on the sandbox |
| M | Gates: fresh sandbox → `test-db` → `e2e:shell` → `test`; `check:all`; `r5:import-equine --check`; fresh verifier + security; docs (contract §16.7 state, TODO, design README pointer); memory (registry ids checked against develop first: LRN-095 and BLK-013 collide, no renumbering in V1-2.6); checkpoint report | C18, C22, C24, C31 | all |
Dependencies: A, B, C independent; D needs A, C; E needs A, B, D; F-J need E; K needs A-J; L needs E; M last.
## Edge cases (all lots)
- Core trap mid-edit: the store keeps `documentText`; the handle rebuilds from its kept input; the canvas shows the
engine notice with retry (BDR-054); a command or file that trapped is not retried automatically.
- A drawing missing or refused: that view shows its state and the canvas notice; edits continue.
- Two tabs on the same draft: each its own copy; the server revision decides (conflict dialog).
- A save answer lost (`network`): the next save meets the conflict dialog with the neutral own-account wording.
- Permission lost or draft state changed during an open session (grant revoked or expired, admin role removed,
session or aal2 lost, round opened, sheet archived): the server refuses the next write with its kind; the page
shows the message (copy wording bound to the write flag), never retries or auto-sends, and switches to the
matching read-only mode on `draft.frozen` / `sheet.inactive` / `rights.*`. Residual risk recorded, not fixed
(C31): catalogue RPCs check the token's `aal2` claim (`private.has_mfa()`), not the live session, so a token
issued at `aal2` keeps passing them after a factor removal until it expires.
- Escape in a native dialog closes it (LRN-082); e2e waits for a closed dialog before typing (LRN-111) and accepts
the beforeunload dialog before a reload.
## Disposition of memory (in force)
Honors BDR-043 (no rule in TS: translation and defaults are UI arithmetic, every check is the core's), BDR-050,
BDR-054/055/056 (failure states, honest unsaved wording, restore through the core), BDR-076, BDR-078, BDR-082,
BDR-084 (M8 reads through the RPC, no grant widening), BDR-085, BDR-086, BDR-087 (stored form; unique scope for
the cleaning preview; one canvas per view in the DOM), BDR-088/090 (Inkscape 1.4.3 fixture), BDR-091/092,
BDR-094, BDR-096 (boards followed; deviations listed), BDR-097, BDR-099; LRN-010, -017, -043, -055, -057, -058,
-060, -082, -085, -087, -088, -089, -094, -097, -101, -103, -104, -110, -111, -112, -113.
## Visible choices taken in this plan (for the owner at the validation gate)
1. Annotation categories edited in the Général tab.
2. Creation panels collect the required fields (names FR/EN, laterality with no preselection, category, opened
view) before the element exists; no default labels.
3. Keyboard creation buttons under the canvas, then numeric fields.
4. Read-only notices per reason (rights, frozen, historical, archived) besides board 05's narrow notice.
5. From 1 024 to 1 279 px the properties card goes under the canvas.
6. Overview links « Ouvrir le brouillon » / « Consulter le brouillon »; A1 and W1 land on the editor (§11.2).
7. Owner trial commands `pnpm db:sandbox trial`, `trial-account`, `trial-grant` and the doc
`docs/development/V1-2-6_OWNER_TRIAL.md`.
8. New closed code `upload.pending_other` (another account's unfinished upload of the same drawing).
All eight approved by the owner 2026-11-03 (« GO propriétaire V1-2.6 »), with: no JSON export or import of the
recovery copy in V1-2.6; exact messages on the copy's state and limits. Owner arbitrations 2026-11-03 on the
re-check (« arbitrages propriétaire sur REMAINING(2) »): default point rule with a confirmed correction, never a
silent move (C26); editing blocked while a recovery offer is unanswered, actions « Restaurer la copie » /
« Ignorer la copie » (C27); no automatic eviction, explicit abandonment on cap or quota (C28); conflict dialog
sources and failed-read variant (C29).
Recorded deviations from board 06 A (owner answer): no « Prévisualiser », no withdrawal before V1-2.7.
## Challenge record (2026-11-03, three lenses, each CONCERNS(4), no BLOCKER tag)
Accepted and integrated: simplicity 1-11 (CataloguePreview extended, canvas and framing reused, static narrow
tabs, synchronous copy writes, one key per account and version, id retry on `duplicate_key`, recovery drawings in
the copy, loader and failure map reused, failure-only copy status, no Ctrl+Y, shared read-only fields, e2e
helpers reused); robustness 1-3 and 5-17 (sent text kept on save, session token, drawings added one by one and
the stored object re-read, removal cases, no pending write, account in the key, trapping input not kept, edit mode
needs the admin role, 16-drawing cap, two-step reload and neutral own-account wording, pointer capture, unique
test bytes and working-copy slot, trial gateway and SQL variables, admin role in trial-grant, M8 in
`get_official_sheet_admin` only with `resource_type`, 2 MiB latency); correctness 1-14 (confirmed row skips the
upload and a policy refusal is named, creation fields, discard removes the copy, deep comparison, saved revision
from the version answer, save answer parsed, zones without status, A before D and E, 1 024 px layout, older-copy
restore, stacks cleared on reload, one canvas per view, beforeunload in e2e).
Confirmation pass (one fresh correctness challenger on the revision): FATAL(6) → all 12 integrated: [BLOCKER] an
older restored copy saved over a newer revision → `savedRevision` stays the copy's base with `staleBase`, the
first save meets the conflict dialog; state failure after replace → rollback, kept input only after `state`;
draft `readVersion` per-drawing settled results; `handleVersion` drives canvas rebuilds and the read-only `key`;
link tool and « Vue ouverte » limited to direct detail children; default radius 12 + 3 %; drawings keyed by
asset id; `draft.unchanged` sets the saved pair; policy refusal tries `confirm` once; trial through a Vite proxy
(same origin); dropped loads and `close()` free the preview; recovery offer only where saving is possible. The
procedure allows one confirmation pass: these fixes go to the gate unchallenged again. Robustness 4: messages read the
write flag (integrated); a downloadable rescue copy (BDR-055 pattern) is a visible choice asked at the gate (owner:
no export button in V1-2.6).
Owner-ordered targeted re-check (fresh verifier, 2026-11-03): REMAINING(2): fixes 1-5 closed, invariants I1-I5
hold; [MAJOR] the 12 + 3 % radius made points `out_of_frame` on frames under about 25.5 units → « Default point
and the frame » (owner formula, core-decided placement, confirmed correction); [MAJOR] I6 broken, a pending copy
overwritten by the first commit → blocking offer, no write while pending; [MINOR] N source on a failed read →
conflict dialog sources and failed-read variant; [MINOR] two-copy cap evicting copies → no eviction, explicit
abandonment. Second targeted re-check ordered by the owner on these two corrections and their interaction with
the five validated invariants.
Second owner-ordered re-check (fresh verifier, 2026-11-03): REMAINING(1), no BLOCKER; confirmations 2-6 confirmed,
I1-I5 hold; confirmation 1 NOT confirmed: [MAJOR] F1 `accept` read the core's silence as acceptance on views the
core does not measure (no accepted drawing, no usable frame) → measured views only, tools and numeric geometry
disabled elsewhere, `accept` refuses there. MINORs integrated: A (B = floor(d), exact clamp on an empty interval,
F parsed from the attribute text), B (kept input and `handleVersion` only after `accept`), C (exact numeric display,
4 px drag threshold), D (frame changes under `accept`; edits allowed on an annotation already out, owner approval
pending as it refines C26), E (`restoring` state, one store update, `savedText` stays the server's), F (removal
actions refused while pending, unreadable copy kept as refused, leave guard while an offer is open), G
(`version_id` checked, submit conflict uses the dialog, submit refused under `staleBase`). STOP for the owner.
Owner GO 2026-11-04 (« GO propriétaire après REMAINING(1) »): F1 fix approved (C32); C26 refined by the owner's
seven repair rules (C33: one rule, the changed annotation carries no geometry error after a commit; a typed
`too_small` radius is now refused; repair through a temporary form group applied whole; frame changes refused when
they give an error-free annotation a geometry error or leave a view with annotations unmeasured); minor effects
approved (C34: 4 px threshold with click, keyboard and touch kept, unreadable copy with the loss named, leave
guard disarmed after a confirmed save or an explicit abandonment, mobile limits documented). Execution of lots A-M
authorised without a third plan review; stop and present any blocking defect or contractual impossibility.