Files
faunosteo/.claude/tasks/plans/2026-10-17-r3-final-checks-0900.md

144 lines
13 KiB
Markdown

# Plan — R3 final checks: rescue copy import, trapping draft, replace confirmation, app-wide guard
Branch feature/rust-r3-anatomy-core (commit in place; no merge, no R4, no release, no deploy). Base 9464651.
Owner brief 2026-10-16 + choices (AskUserQuestion 2026-10-16/17).
## Diagnosis (evidence)
- Rescue copy = `JSON.stringify(report)` = byte format of `osteo:draft` (persistence.writeOrRemove). Proven: 3 golden
reports (v2full, demo, v2unresolved) round trip identical through `restoreDraft` (draft slot) and through the
core import (bare v3). No app path accepts it today (Home picker: PDF only) → not restorable without devtools.
The copy lacks the imported archive envelope (snapshot/branding/labels): the original PDF keeps it; report data
complete.
- Trapping draft: fuzz 37k `draft.restore` calls on the shipped core, 0 `internal`; OOM trap only from ~50 MB drafts
(sessionStorage ≤ ~5-10 MB). Real risk = low-memory device on a pathological 5 MB draft (0.4-0.8 GB wasm). If it
traps: restore() maps `internal` to `core_unavailable` → CoreUnavailable "Réessayer" = reload → same trap each load;
New report / Import FAILED (releaseUnreadSession). Tab stuck, draft kept, no in-app exit (closing the tab loses it).
- Work loss paths: beforeunload guard only in EditorRoute (`unsaved`): reload / close / OAuth full-page redirect from
Home, New report, /app, /login lose an unsaved report silently. New report (initReport) and Import (hydrateImport)
replace the bilan in progress (memory or draft slot) without confirmation, saved or not.
- GC finalizer: harmless (dead instance only, live instance 50/50 correct, no app handler); retained memory bounded
to 3 dead instances (~13.5 MB typical), freed on reload. Mitigations rely on glue internals or run code on a dead
instance, no memory gain → record only (no code).
- Side finding (record only): a raw lone surrogate in the stored archive text fails the whole `draft.restore` with
`lone_surrogate` → readable draft quarantined; unreachable (the app escapes surrogates; session.rs change needs
owner ask per CLAUDE.md).
RELATED MEMORY: honors BDR-052 (no user data removed/overwritten implicitly; held panel = resolution UI), BDR-054/055
(stopped notice, copy, guard), BLK-011 (census of every failure surface), LRN-055 (refuse, never alter), LRN-057.
## Fix plan (rev 2, after 3 challengers)
RELATED MEMORY correction: this plan SUPERSEDES BDR-055's clause "core failure reading unread draft → FAILED, never
held" for `internal` only (a trap reading the draft): it becomes the held engine_failure row; `core_unavailable` and
other core kinds stay FAILED. New BDR-056 records it; CHANGELOG R3 line amended; state.quarantine.test.ts updated.
1. Rescue copy import (owner choice 1) — no new store action
- apps/app/src/pdf/import.ts: pure `readRescueCopy(text, index): RebaseOutcome` beside importAttachment:
`index.ops.restoreDraft(text, null)`; ok → `outcome.value.rebase`; kinds in the store's UNREADABLE_DRAFT_KINDS
(export it from reportStore, or move the set to a shared module) → ImportError `invalid_copy`; every other kind
(core_unavailable, internal, rebase_failed, invalid_sheet, invalid_shape…) → ImportError `core_unavailable`.
- HomeRoute.importFile: route by content from `file.slice(0, 1024)` only (never read a whole oversized file):
starts with `%PDF-` → PDF path (its existing MAX_PDF_BYTES check); else first non-whitespace byte (after an
optional UTF-8 BOM) is `{`, or the name ends `.json` / type `application/json` → copy path; else PDF path
(existing invalid_pdf). [rev 3] Copy cap = MAX_ATTACHMENT_BYTES (16 MiB, exported by @faunosteo/pdf: the same
bound the PDF path puts on the JSON that reaches the core), checked on `file.size` before any read; over →
invalid_copy.
Copy path: decode with `new TextDecoder('utf-8', { fatal: true })` (failure → invalid_copy, LRN-055: refuse,
never alter); `loadSheetIndex`; `readRescueCopy`; THEN the existing `hydrateImport({ report: rebase.report,
archive: null }, index)` branch (held / FAILED handling unchanged). Copy read before any session change.
- After open: `rebase.rebased` → alert `editor.draft_rebased` (reused); navigate /editor.
- Picker accept adds `application/json,.json`. i18n: home.import.title / cta reworded, new
home.import.error_invalid_copy (exact texts below). ImportErrorKind + `invalid_copy`.
2. Trapping draft (owner choice 2) — no re-read of a known-trapping draft
- reportStore closure `trapped: { draft: string; archive: string | null } | null` [rev 3: keyed on the PAIR the
trapping call read]. `restore()` and `releaseUnreadSession`: when the slot pair equals `trapped` → answer held
engine_failure / HELD WITHOUT calling the core. Otherwise call restoreDraft;
`internal` → `trappedDraft = draft`, answer held engine_failure (rows: draft `engine_failure` + archive
`companion` when present) / HELD; draft and archive stay in place (no copy, no removal).
- Only the panel's explicit "Réessayer" re-reads it: `RestoreOptions.retryTrapped` (or equivalent) clears
trappedDraft before the read. Any discard (draft or archive row) clears it [rev 3]. A test seam clears it between tests (the closure
survives `useReportStore.setState`).
- HELD result tells its cause (e.g. `{ ok: false, reason: 'held', engine: true }`); NewReportRoute / HomeRoute
pick `session.held_blocked_engine` for it, `session.held_blocked` otherwise; both then navigate /editor (unchanged).
- EditorRoute: a restore answering held keeps the panel; restoreFailed (CoreUnavailable) only for
`core_unavailable` as today. With the memory, the editor read after New report / Import costs no trap.
- HeldText reason + `engine_failure`; HeldSessionPanel: row label `session.held.draft_engine_failure`; notice
`session.held.notice_engine` when a row is engine_failure.
3. Replace confirmation (owner choice 3)
- One component `components/report/ReplaceSessionDialog.tsx` (props open, onCancel, onOpen, onConfirm), used by
HomeRoute and NewReportRoute. Body: named (`session.replace.body`, `{animal}` substituted with a FUNCTION
replacement `() => name`, never a string pattern) when the report is in memory; `session.replace.body_unloaded`
otherwise; when `isUnsaved`: `session.replace.unsaved` + CopyReportButton. Buttons common.cancel /
session.replace.open (→ navigate /editor) / session.replace.confirm.
- `sessionInProgress()` = report in memory || `readSessionText('draft') !== null`.
- NewReportRoute submit: in progress → dialog; Remplacer → the existing submit continues.
- HomeRoute "Choisir un fichier": in progress → dialog; Remplacer calls `fileRef.current.click()` SYNCHRONOUSLY in
its onClick (user activation; WebKit), then the import runs as today.
4. App-wide guard (owner choice 4): `src/app/useUnsavedGuard.ts` (beforeunload while `isUnsaved`), called once in
App.tsx (inside the providers, outside the route tree); removed from EditorRoute.
5. Docs: RUST.md §8.3 (guard now app-wide), §8.7 item 3 (held reasons + engine_failure; New report / Import confirm
replacement), §9.4 (rescue copy import via draft.restore; trapping draft → panel, no re-read); CHANGELOG R3 lines
amended (line 15 statement on held corrected for `internal`); CLAUDE.md folder list adds ReplaceSessionDialog and
app/useUnsavedGuard.ts.
## Tests
- New: copy round trip through Home (JSON File, content-sniffed, also without .json name) equals the in-memory report
for the 3 golden reports; rebased copy alert; invalid JSON / v1 / lone surrogate / invalid UTF-8 / > cap →
error_invalid_copy, store and slots untouched, no held side effect (copy read before session start); core kinds →
coreFailureMessage path; PDF still routed by `%PDF-`.
- New: trapping draft on a REAL poisoning runtime [rev 3: a CoreSource wrapping the real glue whose
`SheetHandle.call` throws `WebAssembly.RuntimeError` for `draft.restore`; pkg-proofs has no trapping op]: mount editor →
panel engine_failure; New report and Import → engine held alert + panel, total traps = 1 across mount + New report +
Import + remount; panel Retry re-reads (trap 2); discard (confirmed) removes only the draft and clears the memory;
never CoreUnavailable while the engine is not stopped.
- New: ReplaceSessionDialog on New report submit and Home pick (memory and slot-only cases), named / unloaded / unsaved
variants, Annuler keeps everything, Ouvrir → /editor, Remplacer proceeds (Home: picker click called in the same
handler); `$&` in the animal name rendered literally; no dialog when nothing in progress.
- New: useUnsavedGuard via renderHook (saved → not prevented, unsaved → prevented, recovered → not) + App mounts it;
EditorRoute no longer registers its own.
- Adapted (assertions kept, a "Remplacer" click added where a report/draft is present): routes.coreStopped.test.tsx
(New report tests, beforeEach report; guard test moved to the hook test), routes.heldSession.test.tsx (New report
over a draft), state.quarantine.test.ts (internal → held engine_failure), any HomeRoute import test with a session.
- `pnpm typecheck && pnpm test:run && pnpm lint`; then `pnpm check:all`.
## Known residuals (record, no code)
- Importing the rescue copy of a trapping draft re-runs the trapping input (copy path is pure): likely a new trap
with the engine message; a copy near the 16 MiB cap may OOM on a low-memory device (same exposure as a PDF).
- `internal` can come from a handle rebuild, not the draft: the row may blame a sound draft (Retry reopens it).
- The held panel's archive copy (envelope JSON) is not importable as a rescue copy (draft.restore reads reports); the
draft copy is; the archive came from a PDF the practitioner has.
- Storage full + confirmed replace + reload: the slot still holds the replaced report's draft (pre-existing mirror
semantics: a refused write keeps the previous value).
- iOS/iPadOS Safari likely ignores beforeunload: the replace dialog and the copy button are the protection there
(LAN test on the owner's devices).
- restore(): `invalid_shape` / `rebase_failed` (sheet defects) still map to core_unavailable (CoreUnavailable).
- GC finalizer throw after a stack-overflow trap (console only), 3 dead instances retained (~13.5 MB) until reload.
- Raw lone surrogate in archive text quarantines a readable draft (unreachable; session.rs contract).
- Copy lacks the archive envelope (original PDF keeps it).
## Owner wording (pass B, gated 2026-10-17) — exact texts
- home.import.title « Importer un PDF ou une copie de secours » / "Import a PDF or a rescue copy"; home.import.cta
« Choisir un fichier » / "Choose a file"; home.import.description unchanged.
- home.import.error_invalid_copy « Ce fichier n'est pas une copie de secours Faunosteo lisible par cette version.
Import refusé ; le fichier n'a pas été modifié. » / "This file is not a Faunosteo rescue copy this version can
read. Import refused; the file was not changed."
- Rebased copy → existing editor.draft_rebased alert.
- session.held.notice_engine « Le moteur de calcul n'arrive pas à ouvrir un brouillon de cet onglet. Il est
conservé tel quel ; rien n'a été supprimé. Téléchargez-en une copie, réessayez, ou supprimez-le pour commencer un
nouveau bilan. » / "Faunosteo's computation engine cannot open a draft of this tab. It is kept as is; nothing was
deleted. Download a copy, try again, or delete it to start a new report."
- session.held.draft_engine_failure « Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size}) » / EN
"Draft the computation engine cannot open ({size})".
- session.held_blocked_engine « Un brouillon de cet onglet fait échouer le moteur de calcul : il doit d'abord être
récupéré ou supprimé. L'éditeur va s'ouvrir pour le résoudre. » / "A draft of this tab makes the computation
engine fail: recover or delete it first. The editor will open to resolve it." [gated 2026-10-17]
- session.replace.title « Remplacer le bilan en cours ? » / "Replace the report in progress?"
- session.replace.body « Le bilan de {animal} sera remplacé dans cet onglet. Exportez-le en PDF pour le garder. » /
"The report of {animal} will be replaced in this tab. Export it as a PDF to keep it."
- session.replace.body_unloaded « Le bilan en cours dans cet onglet sera remplacé. Ouvrez-le et exportez-le en PDF
pour le garder. » / "The report in progress in this tab will be replaced. Open it and export it as a PDF to keep it."
- session.replace.unsaved « Ses dernières modifications ne sont pas enregistrées dans l'onglet. » / "Its latest
changes are not saved in this tab." + CopyReportButton.
- Buttons: common.cancel « Annuler »; session.replace.open « Ouvrir le bilan en cours » / "Open the report in
progress"; session.replace.confirm « Remplacer » / "Replace".