diff --git a/.claude/memory/blockers.md b/.claude/memory/blockers.md index d1fe9e1c..b029719e 100644 --- a/.claude/memory/blockers.md +++ b/.claude/memory/blockers.md @@ -95,3 +95,10 @@ Friction: 0279953 picked `core.stopped` from `CoreRuntime.stopped` alone: with s Root cause: terminal-state message not bound to persistence status (`saveFailed` existed, unread); retry labels audited only on the 8 alerts + canvas the patch touched, not every failure surface; runtime exit from `unavailable` only via explicit `retry()` called by useSheet alone. Solution: 6371523 (BDR-055): `isUnsaved` selector drives variant + copy; CoreStoppedNotice on all core pages; runtime self-restart below cap; FAILED not held; ESLint census. Verifier CONFORME 12/12 (pass 2), security PASS 2 LOW. Status: resolved 2026-10-16. Residuals: saveFailed also on refused archive (over-warns); offline restart never stops (copy on banner); beforeunload only in editor; trap-every-load draft → reload loop; GC finalizer of trapped-instance SheetHandle throws "memory access out of bounds" later (harmless, tests retain handles). + +## BLK-012 | 2026-10-17 | Rescue copy not restorable; trapping draft stuck tab; work loss outside editor + +Friction: JSON copy (6371523) had no in-app restore (Home picker PDF only; devtools only). Draft trapping `draft.restore` → CoreUnavailable reload each load, New report/Import FAILED, every re-read spent a recovery. beforeunload only in editor; New report / Import replaced bilan in progress (memory or slot) silently. +Root cause: copy shipped without restore path (round trip never tested in app); `internal` from draft read treated as transient core failure, no memory of trapping input; guard scoped to one route; session replacement unguarded since MVP. +Solution: 9bd9aca (BDR-056). Evidence: round trip identical (3 golden reports, slot + import); fuzz 37k draft.restore 0 traps, OOM only ~50 MB drafts (5 MB worst = 0.4-0.8 GB wasm). Verifier CONFORME 10/10, security PASS 2 LOW, check:all green. +Status: resolved 2026-10-17. Residuals: GC finalizer throws "memory access out of bounds" after stack-overflow trap (console only, live instance unaffected 50/50), ≤ 3 dead instances retained (~13.5 MB typical, ~4.5 MB each) until reload; raw lone surrogate in archive text quarantines readable draft (unreachable, session.rs); copy lacks archive envelope; iOS Safari likely ignores beforeunload (dialog + copy are protection there); Retry clicked during ms-long recovery → reload screen; re-importing copy of trapping draft re-traps (spends recovery); copy near 16 MiB may OOM low-memory device; storage full + confirmed replace + reload restores replaced draft; `internal` may come from handle rebuild (Retry reopens). diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index c162707e..3bfa4c10 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -430,3 +430,9 @@ Status: closed (decisions); R3 still awaiting owner LAN confirmation, not merged Owner audit of 0279953 (stopped state) not satisfactory → owner choices (AskUserQuestion 2026-10-15): stopped + `isUnsaved` (saveFailed && report) → `core.stopped_unsaved` + "Télécharger une copie" (in-memory report JSON, `lib/download.ts`, no core); save fine → `core.stopped` + `core.reload` button; copy button also on `editor.save_failed` banner (any engine state); `beforeunload` guard in editor while unsaved; "plusieurs erreurs" (counter = page lifetime, not successive). One `CoreStoppedNotice`: editor banner slot, top of Home / New report, CoreUnavailable full page; canvas stopped text without button. Runtime: failed recovery below cap restarted by next call / `ready()` (`restartable` = unavailable && !stopped && generation > 0), compiled module kept, restart not counted (cap = traps); deferred status listeners. Core failure reading unread draft → FAILED, never held. ESLint census on failure keys. Commit 6371523. Alt rejected: counting failed restarts toward cap (offline → stopped, reload offline fails too); retry button on every page (new UI, owner already removed dead retries); copy only once stopped (offline restart loop never reaches stopped, no rescue). Status: closed; R3 still awaiting owner LAN confirmation, not merged, R4 not started. + +## BDR-056 | 2026-10-17 | R3 final checks: rescue copy importable, trapping draft held, replace confirmed, guard app-wide + +Owner brief 2026-10-16 + AskUserQuestion: (1) Home import also takes JSON rescue copy: sniff first KiB (`%PDF-` → PDF; `{` / .json → copy), cap MAX_ATTACHMENT_BYTES 16 MiB before read, fatal UTF-8, pure `readRescueCopy` → core `draft.restore` (no JS parse), then existing hydrateImport branch; UNREADABLE_DRAFT_KINDS → `invalid_copy`. (2) `internal` reading draft → held `engine_failure` row (+ archive companion), `TrapMemory` keyed on (draft, archive) pair: no re-read by mount / New report / Import, only panel Retry (`retryTrapped`); any discard clears; `held_blocked_engine` alert. SUPERSEDES BDR-055 "never held" for `internal` only (`core_unavailable` etc. stay FAILED). (3) ReplaceSessionDialog (Annuler / Ouvrir le bilan en cours / Remplacer, copy when unsaved) on New report submit + Home pick when report in memory or draft slot; Home picker clicked synchronously. (4) `useUnsavedGuard` once in App. Commit 9bd9aca. +Alt rejected: new store action openCopy (dup of hydrateImport, session change before validation); JS JSON.parse of copy (depth; core reads raw text); copy cap MAX_PDF_BYTES (50 MiB file cap, not JSON bound); trapped memory on draft text only (archive parsed in same call); fixing GC finalizer via glue internals. +Status: closed; R3 awaiting owner LAN validation, not merged, no R4, release 0.2.0 untouched. diff --git a/.claude/memory/evals.md b/.claude/memory/evals.md index bce2bb89..9ae5a134 100644 --- a/.claude/memory/evals.md +++ b/.claude/memory/evals.md @@ -178,3 +178,10 @@ Method: fresh general-purpose auditor on commit only (5 owner axes); claims re-r Result: audit NOT satisfactory (3 defects: unsaved promise, 4 dead retries, recovery dead end) — all fixed 6371523; app 374 tests, core-wasm 37; verifier pass 1 ECARTS(3) (2 untested surfaces, helper out of scope) → pass 2 CONFORME 12/12; security PASS 2 LOW; docs NONE. Anomalies: previous session's commit + CHANGELOG claimed "never a retry that cannot work" without surface census; challengers converged on dead end the plan fixed only on canvas; confirm pass found offline restart never reaching stopped → copy moved to save banner (owner choice). Executor found latent GC finalizer throw (not fixed). Action: R3 stays unmerged until owner LAN confirmation; R4 not started. + +## EVAL-024 | 2026-10-17 | R3 final checks — measurements, challengers ×3 + confirm, verifier, security, check:all + +Method: scratch round-trip test (3 golden reports); fuzz agent (37k draft.restore on shipped wasm + 40 worst cases, OOM threshold); GC agent (Node --expose-gc, 50 recoveries, WeakRef probes, mitigations in scratch); owner AskUserQuestion ×3; plan → 3 blind challengers → rev 2 → confirm → rev 3; bugfixer with negative controls; gates.sh 4/4; verifier; security; check:all; doc-syncer. +Result: copy restorable in app; loop impossible with real drafts, defended anyway; work-loss paths closed; app 405 tests, check:all green (~75 s cached); verifier CONFORME 10/10 (1 floor ASSERT_DROP = guard test moved, authorized by plan); security PASS 2 LOW; docs NONE. +Anomalies: challengers caught trap re-read spending recoveries (2 lenses), BDR-055 contradiction, wrong "parity" cap (50 MiB file vs 16 MiB JSON) only on confirm pass; executor found Retry-during-recovery edge. +Action: owner LAN validation, then merge on owner go; no R4, no release, no deploy. diff --git a/.claude/memory/journal.md b/.claude/memory/journal.md index 6f96685e..988a0a48 100644 --- a/.claude/memory/journal.md +++ b/.claude/memory/journal.md @@ -268,3 +268,7 @@ feature/rust-r3-anatomy-core: plan rev 2 after 3 challengers (32 findings; block - 2026-10-15 owner UX decisions on R3: unnamed trigger names per language (contract doc first, Rust layer, declared change applied to frozen oracles, goldens untouched); canvas engine failure (retry) vs view failure (own message, no retry). check:all green, Chromium 30/30 identical + DOM = O1 (declared), verifier CONFORME 8/8, security PASS 0 findings. Owner LAN tests in progress; no merge, no R4. - 2026-10-15 owner validated both UX fixes + retry on internal; asked 3-attempt cap then clear failure state: found canvas + 8 alerts would still offer retry after cap → `CoreRuntime.stopped` + `core.stopped` message, no retry. BDR-054. R3 not merged (LAN tests pending). - 2026-10-16 owner asked final independent audit of 0279953 (stopped state): not satisfactory (unsaved draft promise false, 4 dead retries, recovery dead end). Owner choices: unsaved variant + core-free copy, reload button, copy on save banner, beforeunload, "plusieurs erreurs". Fixed 6371523 (runtime self-restart below cap, CoreStoppedNotice on core pages, FAILED not held, ESLint census); verifier CONFORME 12/12, security PASS. BDR-055, BLK-011, LRN-057, EVAL-023. R3 not merged (LAN pending), no R4. + +## 2026-10-17 (R3 final checks) + +Owner brief: 5 checks before R3 close. Copy round trip proven, no in-app restore → Home import reads copy via draft.restore. Loop: fuzz 37k 0 traps (OOM ~50 MB only) → defended: trapping pair held in panel, re-read only on Retry. Work loss: guard app-wide, replace dialog on New report / Import. GC finalizer harmless, bounded, recorded. 9bd9aca; verifier 10/10, security PASS, check:all green. BDR-056, BLK-012, LRN-058, EVAL-024. R3 not merged (LAN pending), no R4, no release, no deploy. diff --git a/.claude/memory/learnings.md b/.claude/memory/learnings.md index c926e5ee..ae4ed225 100644 --- a/.claude/memory/learnings.md +++ b/.claude/memory/learnings.md @@ -445,3 +445,12 @@ Apply: R4 PDF reader/writer (byte scanners, inflate), Step 13 uploads (reader in - Rescue must exist in every non-ready state, not only terminal one: a restart loop offline never reaches "stopped". - Status listeners from a state machine: notify via microtask, try/catch per listener, never inside load/recover try blocks; stable module-scope subscribe for useSyncExternalStore. Apply: R4 PDF worker failure states, Step 8 avatar upload errors, any capped retry or offline mode. + +## LRN-058 | 2026-10-17 | Rescue paths need proven restore; remember trapping inputs; sniff and cap before read + +- "Download a copy" is no rescue until an in-app restore exists and a round-trip test proves equality; reuse the reader that already parses that format (here core `draft.restore`) instead of a new parser. +- Input that trapped a recoverable engine must be remembered (key = every input of the trapping call, e.g. draft + archive) and re-read only on explicit Retry: each re-read spends a capped recovery and pins dead-instance memory. +- Untrusted file pick: route by content from first KiB, apply that path's cap on `file.size` before any full read, decode UTF-8 with `fatal: true` (refuse, never alter). +- User text into i18n templates: `.replace(re, () => value)`; string replacement expands `$&`/`$'`. +- Picker opened from a confirm dialog: call `input.click()` synchronously in the confirm handler (user activation, WebKit). +Apply: any export/backup feature, R4 PDF reader worker failures, Step 13 uploads. diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index d159f353..61522c59 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -201,6 +201,7 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo - [x] R3 owner decisions 2026-10-15: unnamed trigger names per language (6882c6d, contract d8e9bd3); canvas engine failure (retry) vs view failure (no retry) (c0a5c8c) - [x] R3 owner follow-up 2026-10-15: retry kept for `internal`; after the 3 recoveries a clear final state (`core.stopped`) in the canvas and the action alerts, no retry (BDR-054) - [x] R3 owner-requested audit of 0279953 (2026-10-15/16): not satisfactory (unsaved draft promise, 4 dead retries, recovery dead end) → fixed 6371523 (BDR-055, BLK-011); verifier CONFORME 12/12, security PASS; residuals in BLK-011 + - [x] R3 final checks 2026-10-17 (owner brief 2026-10-16): rescue copy importable from Home, trapping draft held (no reload loop), replace confirmation, guard app-wide → 9bd9aca (BDR-056, BLK-012); verifier CONFORME 10/10, security PASS, check:all green; residuals in BLK-012 - [ ] R3 follow-ups kept by the owner (2026-10-15): worker TLS exercised against a real HTTPS endpoint before the deployment that needs it; roxmltree limits + SVG prescan (pin the iterative release when published); Firefox/WebKit check; SVG references across drawings scoped per view before community uploads (Step 13); WASM size margin (396 of 600 KB) before R4; TypeScript PDF sanitiser still present until R4 - [ ] R4 pdf core: reader (Web Worker, BLK-009 browser measurements) + writer (`pdf-writer`, Std14 AFM, draw log; lines/rects/colours golden frozen with the TS engine first, D-R2) + `report-compare` tool; `packages/pdf` deleted; N-1 scanner reads R4 PDFs - [ ] R5 curation pipeline + importer + upload tool: seed golden regenerated once (new `documentSha256`, D-R5), `packages/anatomy` + `packages/domain` deleted, docs map; all before Step 13 diff --git a/.claude/tasks/contracts/2026-10-17-r3-final-checks-1000.md b/.claude/tasks/contracts/2026-10-17-r3-final-checks-1000.md new file mode 100644 index 00000000..8d045818 --- /dev/null +++ b/.claude/tasks/contracts/2026-10-17-r3-final-checks-1000.md @@ -0,0 +1,76 @@ +# CONTRACT — r3-final-checks +- date: 2026-10-17 | flow: bugfix | branch: feature/rust-r3-anatomy-core +- status: active +- plan: .claude/tasks/plans/2026-10-17-r3-final-checks-0900.md (rev 2 + owner wording; owner-approved 2026-10-17) +- base: 9464651 (run every CHECK from the repository root) + +## REQUEST (verbatim — IMMUTABLE) +# Faunosteo — Derniers contrôles R3 avant validation humaine + +J'approuve les corrections apportées après l'audit indépendant, notamment la protection des bilans non enregistrés, les messages d'erreur communs, le téléchargement de secours et la gestion des reprises du moteur. + +Avant de clôturer R3, vérifie les points suivants : + +1. **Copie JSON de secours** : prouve qu'elle conserve toutes les données nécessaires du bilan, qu'elle est exploitable et qu'une procédure réelle permet de restaurer le travail. Si aucun import compatible n'existe, ne présente pas ce téléchargement comme une restauration complète : identifie la solution minimale nécessaire ou le blocage. + +2. **Boucle de rechargement** : reproduis ou écarte le cas d'un brouillon qui provoque systématiquement un plantage du moteur. Si la boucle est réelle, empêche les rechargements sans fin tout en préservant le brouillon original. Pas de suppression silencieuse. + +3. **Modifications non enregistrées** : vérifie les changements de page, les retours à l'accueil et les autres actions susceptibles de perdre du travail. La protection actuelle limitée à l'éditeur est acceptable seulement si aucun autre parcours exposé ne permet cette perte. + +4. **Erreur de nettoyage mémoire** : détermine si elle est réellement sans conséquence, sans fuite ou accumulation après les reprises. Conserve-la dans le suivi si elle est non bloquante. + +5. **Tests finaux** : exécute `pnpm check:all`, les tests de récupération concernés et les vérifications utiles. Si tu modifies le code, soumets le delta à un contrôle indépendant ciblé. + +Ne lance pas de refonte générale. Privilégie les corrections minimales et cohérentes avec l'architecture validée. + +À la fin, présente : +- Le résultat de ces vérifications. +- Les éventuels blocages réels. +- La méthode de restauration d'une copie JSON. +- Le résultat de `check:all`. +- La procédure finale de test LAN. + +**R3 reste non fusionnée jusqu'à ma validation manuelle.** + +Ne commence pas R4, ne publie pas la release 0.2.0 et ne déploie rien sur faunosteo.com. + +## CLARIFICATIONS +Q: restore the JSON copy? / A: Home import also accepts the copy (.json, content-sniffed), read by the core's existing `draft.restore`. [gated 2026-10-17] +Q: trapping draft? / A: existing resolution panel, row « Brouillon que le moteur de calcul n'arrive pas à ouvrir ({size}) », download / retry / discard after confirmation. [gated 2026-10-17] +Q: replace confirmation? / A: always when a bilan is in progress (memory or draft slot); Annuler / Ouvrir le bilan en cours / Remplacer; copy button when unsaved. [gated 2026-10-17] +Q: beforeunload guard? / A: every page while unsaved. [gated 2026-10-17] +Q: exact wording? / A: the plan's "Owner wording" section, verbatim (import labels, error_invalid_copy, notice_engine, draft_engine_failure, held_blocked_engine, replace dialog texts and buttons). [gated 2026-10-17] +Q: (internal, orchestrator, after confirm challenger) copy cap MAX_ATTACHMENT_BYTES, sniff first KiB, memory keyed on (draft, archive), test seam, wrapped-glue trap source? / A: adopted (rev 3). [gated 2026-10-17] +Q: (internal, orchestrator, after verifier) floor ASSERT_DROP routes.coreStopped.test.tsx beforeunload test? / A: authorized: guard moved app-wide (owner choice 4), its 4 assertions moved to app.useUnsavedGuard.test.tsx (plan Tests 'guard test moved to the hook test'). [gated 2026-10-17] +Q: plan approved? / A: yes. [gated 2026-10-17] + +## ACCEPTANCE CRITERIA +1. The new FR/EN keys exist in both dictionaries with the owner's FR text, and the import labels are reworded. + CHECK: f=apps/app/src/i18n/fr.ts; e=apps/app/src/i18n/en.ts; for k in home.import.error_invalid_copy session.held.notice_engine session.held.draft_engine_failure session.held_blocked_engine session.replace.title session.replace.body session.replace.body_unloaded session.replace.unsaved session.replace.open session.replace.confirm; do grep -q "'$k'" $f && grep -q "'$k'" $e || exit 1; done; grep -q "Importer un PDF ou une copie de secours" $f && grep -q "Choisir un fichier" $f && grep -q "Brouillon que le moteur de calcul n'arrive pas à ouvrir" $f && grep -q "Ouvrir le bilan en cours" $f && echo I18N_OK + EXPECT: I18N_OK + EVIDENCE: MET exit=0 marker-found :: I18N_OK +2. The beforeunload guard lives in one app-level hook, no longer in EditorRoute. + CHECK: test -f apps/app/src/app/useUnsavedGuard.ts && grep -q "useUnsavedGuard" apps/app/src/app/App.tsx && ! grep -q "beforeunload" apps/app/src/app/routes/EditorRoute.tsx && [ "$(grep -rl beforeunload apps/app/src | wc -l)" = 1 ] && echo GUARD_OK + EXPECT: GUARD_OK + EVIDENCE: MET exit=0 marker-found :: GUARD_OK +3. App suites, typecheck and lint pass. + CHECK: ./node_modules/.bin/pnpm typecheck > /tmp/fc-tc.log 2>&1 && ./node_modules/.bin/pnpm test:run > /tmp/fc-test.log 2>&1 && ./node_modules/.bin/pnpm lint > /tmp/fc-lint.log 2>&1 && echo SUITES_OK + EXPECT: SUITES_OK + EVIDENCE: MET exit=0 marker-found :: SUITES_OK +4. No golden, oracle, seed, Rust crate, frozen package or core-wasm source changed since the base. + CHECK: n=$(git status --porcelain -- apps/app/tests/fixtures crates supabase packages | wc -l); m=$(git diff --stat 9464651 -- apps/app/tests/fixtures crates supabase packages | wc -l); [ "$n" = 0 ] && [ "$m" = 0 ] && echo FROZEN_OK + EXPECT: FROZEN_OK + EVIDENCE: MET exit=0 marker-found :: FROZEN_OK +5. Rescue copy: a JSON copy (downloaded format, `JSON.stringify(report)`) imported from Home reopens a report deep-equal to the original for the three golden reports, routed by content from the first KiB (also without a .json name; never reading a whole over-cap file); a PDF still goes the PDF path; invalid JSON, unsupported version, lone surrogate, invalid UTF-8 and over-cap (> MAX_ATTACHMENT_BYTES) files → `home.import.error_invalid_copy` with store and session slots untouched and no held side effect; non-content core kinds → the engine message path. Tested. +6. Trapping draft: with a real poisoning runtime, the editor shows the resolution panel (engine_failure row + engine notice, never CoreUnavailable while the engine is not stopped); New report and Import show `session.held_blocked_engine` then the panel; the trapping (draft, archive) pair is not re-read by mount, New report, Import or remount (one trap total) — only the panel's Retry re-reads it; discard after confirmation removes only that text and clears the memory (draft or archive row); draft and archive are otherwise untouched. Tested. +7. Replace confirmation: New report submit and Home file pick show ReplaceSessionDialog when a report is in memory or a draft is in the slot (named / unloaded / unsaved-with-copy variants); Annuler changes nothing; Ouvrir le bilan en cours → /editor; Remplacer proceeds (Home: picker opened inside the same click handler); an animal name containing `$&` renders literally; no dialog when nothing is in progress. Tested. +8. Guard: unsaved → beforeunload prevented on every page (hook test + App mounts it), saved → not prevented. Tested. +9. Existing suites adapted without weakening assertions (coreStopped New report tests, heldSession New report over a draft, state.quarantine `internal` → engine_failure); BDR-055's `internal` clause superseded consistently in code, tests, RUST.md §8.3 / §8.7 / §9.4, CHANGELOG and CLAUDE.md folder list. +10. No merge, no R4, no release, no deploy, no change outside FILE SCOPE. + +## FILE SCOPE +apps/app/src/app/{App.tsx,useUnsavedGuard.ts (new)}, apps/app/src/app/routes/{HomeRoute,NewReportRoute,EditorRoute}.tsx, +apps/app/src/state/reportStore.ts, apps/app/src/pdf/import.ts, +apps/app/src/components/report/{HeldSessionPanel.tsx,CoreStoppedNotice.tsx,ReplaceSessionDialog.tsx (new)}, +apps/app/src/i18n/{fr,en}.ts, apps/app/tests/unit/** , apps/app/tests/helpers/**, +docs/development/RUST.md, CHANGELOG.md, CLAUDE.md (folder list only) diff --git a/.claude/tasks/plans/2026-10-17-r3-final-checks-0900.md b/.claude/tasks/plans/2026-10-17-r3-final-checks-0900.md new file mode 100644 index 00000000..9dfb4cf8 --- /dev/null +++ b/.claude/tasks/plans/2026-10-17-r3-final-checks-0900.md @@ -0,0 +1,143 @@ +# 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".