Merge feature/rust-r4-pdf-core into develop
ci / rust (push) Canceled after 0s
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s

This commit is contained in:
bchanot committed 2026-10-21 22:23:51 +02:00
commit 96ae75e025
715 files changed
+252890 -8254

No files matched your search

+6 -1
View File
@@ -3,7 +3,12 @@
[target.wasm32-unknown-unknown]
# The shadow stack of the browser module, set explicitly (the toolchain default is also
# 1 MiB). packages/core-wasm/tests/panic.test.ts proves that exhausting it traps.
rustflags = ["-C", "link-arg=-zstack-size=1048576"]
# Linear memory ceiling (R4, OD-3 (a)): a runaway allocation traps at 1 GiB (the instance is
# poisoned and re-created by CoreRuntime) instead of growing until the OS kills the tab. Far
# above the needs measured in RUST.md §10 (import worst case under the value cap, the export
# of a report at the collection caps); packages/core-wasm/tests/pdf-import.budget.test.ts
# proves the trap on the proofs build.
rustflags = ["-C", "link-arg=-zstack-size=1048576", "-C", "link-arg=--max-memory=1073741824"]
[env]
# ts-rs writes the TypeScript types of the contracts here on `cargo test -p faunosteo-core --features ts`.
+29
View File
@@ -0,0 +1,29 @@
# Context7 documentation review, 2026-10-21 (branch feature/rust-r4-pdf-core, c9243b5)
Read-only, `ctx7` CLI, three tracks (Rust crates, frontend libraries, tooling + backend). Nothing changed in the code.
Not covered by Context7: miniz_oxide (Rust), libwebp-sys, rlimit, @vitejs/plugin-react-swc, supabase-js locale sync.
## Findings, by priority
| # | Area | Location | Doc statement | Class |
|---|---|---|---|---|
| 1 | Worker base image | crates/worker/Dockerfile:35 `distroless/static-debian12:nonroot` | distroless README: only `-debian13` tags are published and updated, others are deprecated | security maintenance |
| 2 | Tailwind v4 `outline-none` | 13 files (ui/Input, Button, Chip, Select, Textarea, auth/*, brand/*, shell/*, ObservationCard) | v4 `outline-none` sets `outline-style: none`; `outline-hidden` keeps v3's forced-colors outline | accessibility, visible |
| 3 | `safeNextPath` dot segments (security gate, not Context7) | apps/app/src/auth/redirects.ts:28 | `/..//evil.com` → `//evil.com`; neutralised today by react-router 7.18.4 `resolvePath` | latent open redirect |
| 4 | vitest coverage block | apps/app/vitest.config.ts:20-23 | provider v8 needs `@vitest/coverage-v8`, not installed, no script uses it | dead config |
| 5 | jest-dom entry | apps/app/tests/setup.ts:1 | Vitest entry is `@testing-library/jest-dom/vitest` | test config |
| 6 | `tseslint.config` | apps/app/eslint.config.js:21 | deprecated for ESLint core `defineConfig` | deprecation |
| 7 | `forwardRef` | ui/Input, Select, Textarea | React 19: ref as a prop, forwardRef to be deprecated | deprecation |
| 8 | supabase-js comment | apps/app/src/state/authStore.ts:95-97 | reentry deadlock reason outdated; the deferral itself is still the documented advice | stale comment |
| 9 | `auth.initialize()` without catch | apps/app/src/state/authStore.ts:164-166 | storage errors may propagate unwrapped (snippet); not settled for 2.117 | to check against source |
| 10 | Motion reduced motion | Dialog.tsx, ObservationCard.tsx | `MotionConfig reducedMotion` default "never" | accessibility, visible |
| 11 | DEPLOY.md runbook | DEPLOY.md:401 `listen 443 ssl http2;` | deprecated since nginx 1.25.1: `http2 on;` | runbook text |
| 12 | seccomp arg width | crates/worker/src/sandbox.rs:189-208 | `Dword` documented for 4-byte args; current `Qword` fails closed | low, no bug claimed |
## Upgrade notes (no action now)
react-router 8 (drop react-router-dom, react ≥19.2.7, node ≥22.22); zod 4 (frozen readers must stay on `zod/v3`; `.default` and `.strict` semantics change); TypeScript 7 (`baseUrl` removed); vite 8 coupled with vitest ≥4 and plugin-react-swc 4; vitest 5 needs `@types/node ^22 || >=24`; ESLint 10 blocked by eslint-plugin-react 7.37.5; PGlite 0.5 moves pgTAP to `@electric-sql/pglite-pgtap`; image and rcgen `main` change the APIs the worker and its TLS test use; pnpm 11 config changes.
## Confirmed as documented
ureq TLS defaults (WebPki roots, verification on) and the worker's config; rustls 0.23 server builder; roxmltree untrusted-input options; wasm-bindgen CLI = crate version; serde / serde_json / sha2 / url / image 0.25 / seccompiler semantics; Vite worker, asset queries, virtual module; vitest 3 globalSetup; supabase config.toml keys; Playwright setOffline and CDP gating; supabase-js PKCE options and sync callback; zustand v5 usage; xmldom defaults.
+66
View File
@@ -443,3 +443,69 @@ Context: R4.0 plan rev 2 (`.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md`:
Decision: OD-1 module workers everywhere; import needs Firefox 114 (today it already needs DecompressionStream: Firefox 113, Safari 16.4); import support documented per browser apart from app support, from real checks. OD-2 incremental ExportSession in main instance: PDF + one decode ≈ 0.37 MB/view vs TS ≈ 3.8 MB/view (RGB planes held until save) vs two calls ≈ 0.91; offline export kept; cleanup on error/cancel. OD-3 JSON value budget in linear pre-scan + module `--max-memory`, thresholds from R4.2 reproducible measurements; not shown → stop before R4.3 import switch. OD-4 overwritten duplicate key holding lone surrogate refused, file untouched. OD-5 PDF crash/timeout `error_generic`, copy crash/timeout `error_core_unavailable`, kinds keep technical / resource / invalid apart. OD-6 J1 matrix exact, unrun device never reported validated. OD-7 ~5 MB fixtures, no real data in git.
Alt rejected: classic iife worker for Firefox 102-113 (dev/prod split for dead versions); two-call export (all PNGs in linear memory); disposable export worker (asset fetched at export breaks offline, protocol cost); throwaway main-thread instance (glue retains instances, LRN-060); own lossless JSON reader (R2 rejection holds).
Status: active. Order: plan merge → Safari download bugfix (owner validation) → feature/rust-r4-pdf-core → R4.1.
## BDR-058 | 2026-10-18 | R4.2 validated: OD-3 thresholds fixed, R4.3 switch gated on large-file memory and leak series
Context: R4.2 report (RUST.md §10.3, §10.4): O7 144/144, O9 38/38, O8 47 + 4 declared, browsers 666/678; security gate BLOCK(1) fixed (prescan count past depth cap) → PASS. Owner validation 2026-10-18.
Decision: `MAX_JSON_VALUES` = 400,000 (10 × CAP envelope 39,652) and `--max-memory` 1 GiB final for R4; existing depth / size / complexity / inflation caps kept, no raise without measurement. 1 GiB = safety net, never a tab memory guarantee. Leak criterion: first import = init cost, counted apart; then ≥ 5 consecutive imports + idle, recurring growth ≤ 10 MiB, in Chromium + Firefox + WebKit, GC fluctuations repeated and explained; global peaks kept beside. Three distinct subjects: no leak / low peak / ceiling guarantee. Before the app import switch: 20–50 MiB files (WebKit 324 MiB vs TS 76) must be fixed (fewer ArrayBuffer copies, fewer linear copies, early release, no retained refs, transfer / streaming when it pays) and re-measured on 3 engines, or an explicit size limit with controlled refusal proposed with numbers; no switch before that is solved or decided. OD-4 refusals accepted (L1); no legitimate corpus file may be refused; never rewrite source files or drop bilan data on error; oracles unchanged. Worker technical error / resource overflow / timeout never presented as proof of a corrupt PDF. TS reader deleted only after parity + non-regression. WebKit one-off worker `error`: not blocking, keep trace, repetition tests, never mask `error` events. J1 on real devices announced with "TEST FONCTIONNEL DISPONIBLE"; headless ≠ Safari/iPhone validation.
Alt rejected: 1,000,000 values (25 × CAP; more headroom, weaker bound). Switch import before the large-file fix.
Status: active. R4.3 started 2026-10-18 on feature/rust-r4-pdf-core; no R4 merge into develop, no R5, no 0.2.0, no deploy.
## BDR-059 | 2026-10-18 | J1 authorised with the two WebKit reserves; PDF cap kept at 50 MiB
Context: R4.3 checkpoint report (RUST.md §10.5): WebKit 50 MiB file 145 MiB vs TS 76 (worker read was 324); WebKit leak series above 10 MiB but navigation control grows too, one-page series levels off; no forced GC headless. Owner decisions 2026-10-18.
Decision: both WebKit reserves accepted provisionally; J1 device acceptance launched on `feature/rust-r4-pdf-core`. PDF cap stays 50 MiB; no streaming scanner in R4.3. Leak criterion unchanged (≤ 10 MiB recurring over ≥ 5 imports after init), same-page measures separated from navigation ones, a no-import control kept; any device overshoot documented and analysed before final acceptance. OD-3 400,000 / 1 GiB, copy cap 16 MiB, worker protections, validated messages kept. J1 focus: Safari iOS, large PDFs, repeated imports, timers. Deliverable: PASS / FAIL / NON TESTÉ per device and scenario, gaps, residual risks, argued recommendation. Not a final validation of R4.3; headless never sufficient; TS reader kept; no merge; stop at J1, no R4.4.
Alt rejected: streaming scanner now; lowering the PDF cap; blocking J1 on the WebKit growth.
Status: active. Kit generated at ../faunosteo-j1-kit; results template docs/development/R4_J1_RESULTS.md; waiting for the owner's device run.
## BDR-060 | 2026-10-18 | R4.3 accepted provisionally; iPhone J1 blocking before any R4 merge; R4.4 go
Context: J1 partial (computer run, no failure; iPhone unavailable, deferred). Owner decision 2026-10-18.
Decision: R4.3 provisionally accepted on the branch, only for scenarios actually run; Safari iOS J1 mandatory before any merge of R4 into develop; BDR-058/059 WebKit memory reserves stay open; headless ≠ device. R4.4 authorised on the same branch per plan: layout, text, AFM, dates, DrawLog, validated against O1, O4, O5 and the Step 6 goldens. No regression on R4.3: reader, worker and memory guarantees untouched unless demonstrated need + prior validation. Automated tests and parity checks at every step; TS reader kept until R4.8. End of R4.4: detailed report (changes, tests, parity, performance, risks, decisions), stop before R4.5.
Status: active.
## BDR-061 | 2026-10-18 | R4.4 validated; R4.5 serialiser authorised with parity, tooling and compatibility gates
Context: R4.4 report (RUST.md §10.6: O1 12 runs 2,124 calls, O4/O5/O6 exact). Owner decision 2026-10-18.
Decision: R4.5 on the branch: content emitter + numberToString, pdf-writer, PNG gate and decode, links, Info, attachment, self-check, from_envelope. Gates: parity with O2, O4, O6 and applicable goldens (declared differences kept, oracles never edited to hide a gap); `qpdf --check`, poppler 150 dpi 0 px vs R3, O11 reads; restoration compat: R4 PDF read by Rust reader + kept TS reader, envelope/N-1 copies, no bilan data loss on export → import; PNG and PDF structure protections before large allocations (plan caps), invalid cases and messages checked; measure performance, allocations, real wasm size with the writer linked (W1 600 KB per plan), compared with TS baselines on same files/conditions; R4.3 import and worker guarantees untouched; WebKit reserves and iOS recette still blocking merge; gates green; RUST.md documented. Stop at R4.5 checkpoint: components, oracle/golden results, compat, perf/memory, wasm size, gaps/risks, R4.6 recommendation.
Status: active.
## BDR-062 | 2026-10-19 | R4.5 validated; R4.6 session export authorised; chunked file, decode on arrival, catalog last
Context: owner decision 2026-10-19 on the R4.5 report (RUST.md §10.7). R4.6 brief: ExportSession + app driver, rasters as bytes one by one, OD-2 buffers documented, `view_raster_failed` on raster failure, parity + restoration (Rust → Rust, Rust → TS reader, N-1), E3/E4 three engines same data, shipped W1 measured, TS engine kept until R4.8, no merge, stop at R4.6.
Decision (design, measured): session in main instance per OD-2. File written in chunks never reallocated (target 1 MiB doubling to 8 MiB), image object written at `add_raster` (PNG + planes freed in the call), logos kept until branding batch completes (slot order as engine), catalog + page tree objects written last, file handed to JS in parts → `new Blob(parts)`, self-check scans attachment chunk behind header. R4 digests (own bytes, not TS oracle) re-frozen once for it; O2 suite + qpdf + poppler re-run green. Hex strings upper-case as pdf-lib (B4). Alternatives measured and dropped: single `Vec` doubling (125 MiB for 44 MiB file, realloc spike), two buffers (2 × file at finish), 1 MiB fixed chunks (0.12 MB fragmentation per view).
Status: active; owner checkpoint R4.6 pending.
## BDR-063 | 2026-10-19 | R4.6 accepted provisionally; R4.7 report-compare authorised; Chromium 10 MiB series = open reserve
Context: owner decision 2026-10-19 on the R4.6 report (RUST.md §10.8). Chromium per-export RSS growth on L (≈ 20 MiB, same in TS control, plateau after 8) accepted provisionally: not a leak validation, kept as open reserve; reports must split wasm linear memory / browser global / canvas-blob-URL retention / transient vs persistent; thresholds never changed, no FAIL turned PASS. J1 + J2 on real devices mandatory before any merge; NON TESTÉ kept. R4.7 per plan, no scope widening; S2 export worker not engaged without proof + new decision.
Decision (R4.7 design): `pdf::compare` pure module behind feature `cli` (= pdf-read + pdf-write, never in wasm), `Files` trait for fs; binary `src/bin/report_compare.rs` only std::fs file; seed sheet read at run time from `CARGO_MANIFEST_DIR/../../supabase/seed/.../draft` (no drawing); root `report:compare` → `scripts/report-compare.sh` (rust-env + cargo run --release --features cli). A.3 closed lines chosen: `report document invalid: <serde detail>` (ZodError dumps), `attachment refused: lone UTF-16 surrogate escape at byte N` (surrogates kept/overwritten), `report version null cannot be read` (overflow → null, incl. envelopeVersion overflow where TS printed a rejected-envelope header). Alternatives dropped: `include_str!` of the seed (bakes content, rebuild on seed change); spawning the binary per O10 row in tests (230 spawns, slow): in-process `run` + 8 spawns instead.
Status: active; owner checkpoint R4.7 pending.
## BDR-064 | 2026-10-19 | R4.7 validated; R4.8 deletions: test read-back on own PDF reader, N-1 scanner exported, in-process import helper
Context: owner validated R4.7 (three A.3 lines accepted, 25 s first compile accepted, no prebuilt binary). R4.8 brief: delete packages/pdf, pdf-lib, TS CLI, redundant tests, generators; keep frozen oracles, goldens, reference PDFs, fixtures; `packages/anatomy` render until R5; audit consumers first; non-regression proofs; checks must fail on missing Rust component; no merge, no R5.
Decision: vitest read-back of the app export without pdf-lib = `tests/helpers/pdfFile.ts`, a reader of the writer's own format (objects, inline dicts, Flate via node:zlib, Kids order, Info, annots, XObjects) + `buildPdfWithAttachment` for the rejection inputs; view goldens from the SVGs captured at the mocked rasteriser (request order = engine order; the bundled partner SVG logo comes first with real branding); `importReportFromPdf` for tests = module `SheetHandle.import_pdf` on a throwaway handle + worker's `pdfImportOf` (`tests/helpers/pdfImport.ts`; `GlueSheetHandle.free()` added to the interface); envelope + N-1 suites read attachments with the frozen O11 scanner, exported through `@faunosteo/core-wasm/n-1` (index re-export only, copies untouched); `pdf.export.app` deleted (re-export from envelope = cargo `export_from_envelope`, no sheet/branding in signature); `@faunosteo/domain` dropped from apps/app (two incidental test uses → core types / N-1 Zod); ledger script reads frozen cases from the committed TSV. Alternatives dropped: keep pdf-lib as test-only devDependency (review R4 row forbids it in apps/app lockfile); move all content-stream checks to cargo (loses app-path coverage of non-fixture reports); `importPdf` on main-thread SheetOps (breaks OD-1).
Status: active; owner checkpoint R4.8 pending.
## BDR-065 | 2026-10-20 | R4.9: Chromium export reserve classified bounded browser raster path; no rasteriser change; recettes re-issued
Context: owner R4.9 brief (R4.8 validated; final checks, memory bench before merge, import risk classes, J1/J2 re-issue, fresh audits; no merge, no R5). Bench `scripts/browser/r4-memory-bench.mjs` (5 dimensions + rest windows + Chromium pressure + raster-only control).
Decision: Chromium ≈ 20 MiB/L export = browser raster path, not session: control with no core call grows same 20 MiB/step to same plateau (436 vs 437 MiB, 16 steps, last 5 within 10 MiB); linear flat after init, JS heap flat, 847/847 canvases + Blobs collected, 854/854 URLs revoked after 30 s; critical pressure returns nothing. Class: accepted temporarily (§6 row 7), device check J2.6/J2.7. Correction only if a device fails: one reused canvas / OffscreenCanvas, bench vs control first; rasteriser untouched (pixel parity pinned). Import risks: PDF_IMPORT_HARDENING §6, 20 rows; blocking before merge = J1 + J2 device runs + timer confirmation. Port 4173 recette surface closed by UFW by default; owner opens one rule per session.
Alt rejected: reused canvas now (no measure says it helps; risk on pinned raster output); disposable export worker S2 (no device failure).
Status: active; owner checkpoint R4.9 pending; gitleaks allowlist `[gated]` marker = owner action.
## BDR-066 | 2026-10-21 | R4.10 owner decisions final: J1.7 PASS with reserve, J2.3 option 1, logo bundle, gitleaks marker valid, 23 deletions, Safari iOS real device only
Context: owner verdict after R4.10 gates (verifier 8/8 + one formal scope gap = contract file itself; security PASS 3 LOW).
Decision: J1.7 functional PASS, perf reserve (~60 s OS picker offline, same via Ctrl+O outside app); M1/M2 PASS ~60 s; M3 NON TESTÉ = complementary non-blocking, never PASS without run; M4/M5/M6 NON TESTÉ; no app work on 60 s without Faunosteo-specific proof; Cache-Control fix kept. J2.3 option 1 final: editor export = current branding even for logo-less archive; corrected expected result validated; data/oracles/goldens unchanged. ZenQuality logo bundle dcc7940 validated (same image, CSP intact, no zenquality.fr dependency); reintroduction tests + CSP proof (every violation fails, except refusal a negative test expects) kept. `[gated 2026-10-18]` marker valid: marker needs explicit owner decision, writing delegable (Claude wrote it under authorization). R4.8 authorization = exactly 23 test files of 0dc1ba2 (21 = census error, EVAL-025 superseded on count); no further deletion under it. Safari iOS NON TESTÉ until real iPhone results; simulator never memory proof.
Recorded: RUST.md §10.11 (marker wording, count) + §10.12 D; R4_MINI_RECETTE, R4_J1/J2 + RESULTS. LEDGER.tsv untouched (generated byte for byte by `scripts/r4-ledger.mjs`).
Status: active; R4 close still waits on Safari iOS real device; no merge, no R5, no release.
## BDR-067 | 2026-10-21 | R4 closed: owner accepts J1/J2 on computer + Android + real iPhone, validates R4.12, authorizes merge into develop with named residual risks
Context: owner brief « Validation finale de R4 et autorisation de fusion » after R4.12 checkpoint (verifier CONFORME 9/9, security PASS 3 LOW).
Decision: J1 + J2 declared PASS as a whole on iPhone Safari iOS (no per-check split, no model/version/timing/memory given → recorded as missing, never invented); J1.7 PASS w/ picker-delay reserve; J2.3 PASS under approved rule (new export = current branding); M3 NON TESTÉ non-blocking. R4.12 D1/D3/D6 validated. Residual risks accepted for develop merge, open until own deadline (never closed by merge): base image by tag not digest + cosign unchecked (before prod image), semgrep partial parse 2 test files, guardrails WARN `species_select_active` outside diff, device timings/memory unreported (hardening §6 items 5/6/7/9/20), J1.7 cause unknown, BDR-063 Chromium raster growth, D2/D4/D5 deferred. Merge = `gitflow finish` after usual final checks; blocking defect → stop and report.
Alternatives: wait for per-check iPhone measures (rejected by owner: device-level declaration suffices for merge, measures = follow-up); regenerate goldens on any gap (forbidden).
Recorded: RUST.md §10.15 (risk table + checks), PDF_IMPORT_HARDENING.md §7, R4_J1/J2_RESULTS + MINI_RECETTE, CHANGELOG headers, TODO R4.13.
Status: active; limits stay: no release 0.2.0, no deploy, no DNS/server change, no R5 before next owner signal, D2/D4/D5 deferred.
+7
View File
@@ -185,3 +185,10 @@ Method: scratch round-trip test (3 golden reports); fuzz agent (37k draft.restor
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.
## EVAL-025 | 2026-10-20 | R4.9 gates — bench, verifier ×3, security ×4, check:all
Method: memory bench 3 engines × demo/L × 6 exports + Chromium L 16 + raster control; contract 16 criteria (owner §2 list), fresh verifier per pass; full security gate on 168 R4 source files, then targeted re-gates on each fix; check:all.
Result: verifier pass 1 ECARTS(1): core with no feature did not compile (`restore_copy` used gated `pdf::read` const; workspace feature unification via crates/wasm hid it in rust-check/check:all) → gated + no-feature clippy in rust-check; pass 2 ECARTS(1): §6 lacked J2 merge-gate row → added. Security pass 1 BLOCK(1): `.gitleaks.toml` allowlist (R4.1, owner-approved in journal) lacks owner `[gated]` marker → owner action; MEDIUM serve.mjs `--host ""` bound every interface.
Anomalies: my first host fix = exact-string denylist → bypassed by `0`, `0::`, `::ffff:0.0.0.0`, scoped `::` (re-gate 1); rebuilt resolve-then-BlockList; re-gate 2 found post-bind check dead for IPv6 (`family` 'IPv6' vs 6) and my fstat-first CLI read opened FIFOs before the type check (regression). Each fix of a gate finding introduced the next finding: 3 re-gates for 2 small fixes. Contract CHECKs used root vitest path (absent): oracle defect.
Action: owner checkpoint; floor 21 DELETED_TEST (R4.8 deletions, approved in brief §1) need owner `[gated]` clarification line to clear formally.
+32
View File
@@ -282,3 +282,35 @@ Owner go R4.0 (A1-A13: one branch + J1, old PDFs preserved, years 0-99 kept, Pro
Owner validated R4.0 plan with conditions (BDR-057, plan §A.6, LRN-059/060). R3 state checked: merged 8df964b, branch gone. chore/rust-r4-plan finished → develop ae17097. Hotfix bugfix/pdf-download-webkit 2b8000e: downloadBlob (anchor attached, URL revoked after 30 s) shared by rescue copy + PDF export; 3 challengers SOLID, app 405, security PASS, RUST.md 8.7 synced. Playwright WebKit 27.2 now starts (owner installed libs); desktop WebKit/Firefox/Chromium save the PDF even with immediate revoke → fix unproven until owner iPhone run. Stop: owner iPhone validation + CHANGELOG wording, then merge, then feature branch.
- 2026-10-18 owner iPhone run of the Safari fix: all OK → check green (1015) → gitflow finish fcff92b. Owner go R4.1: feature/rust-r4-pdf-core cut from develop.
- 2026-10-18 R4.1 freeze done on feature/rust-r4-pdf-core (eff5405..4439fd2): O1-O13 generators + oracles committed, ledger 299 rows (150 ported / 28 replaced / 88 kept / 33 deleted), browser harness scripts/browser (Chromium 156, Firefox 157, WebKit 27.2, 4 GiB RSS watchdog = not guaranteed limit). TS baselines: CAP export stopped by ceiling in all 3 engines, L peak content 0.8-1.35 GB, import 226 files same outcome everywhere; O9 browsers = Node on 26 rows. Repo +5.92 MB stored vs ~5 MB approved. Frozen step6/r2/r3 goldens untouched. .gitleaks.toml narrow allowlist for compare.json. Next: checkpoint report to owner, then R4.2.
- 2026-10-18 owner validated R4.1 (fixtures 5.92 MB kept incl. real raster; gitleaks exception OK if narrow; decoy-first OD-4 kept in register, risk to explain before R4.3; UPNG/text oracles kept; headless OK for R4.1). Go R4.2 (reader, inflate, JSON pre-scan, UTF-8 parity, wasm facade, memory protections). Hard stop end of R4.2 before any import switch; budgets whole-browser; gains compared on identical perimeters. No merge, no R5, no release/prod.
- 2026-10-18 R4.2 done on feature/rust-r4-pdf-core (21d34fb..): pdf::read (scan, strings, stamp, inflate, probe), json_js, import_pdf, SheetHandle.import_pdf; O7 144/144, O9 38/38, O8 51 (4 declared: 3 OD-4 lone surrogate in overwritten dup value, 1 OD-3 values-1m), reference PDFs all import, through wasm too. OD-3: MAX_JSON_VALUES 400,000 (10 × CAP envelope 39,652), rescue copy guarded, --max-memory 1 GiB trap proven; hostile 16 MiB: 784 MiB → 16 MiB linear. Security gate BLOCK(1) (count stopped past depth cap → bypass) fixed 593893a, re-gate PASS. Browser run 3 engines: 666/678 agree, W4 max 68 MiB, W2 46 ms; open: after-GC residue 11.7 MiB first import (one-time), worker holds file twice on 50 MiB inputs (WebKit 324 MiB). Module 422 KB gzip. STOP before R4.3: owner to confirm thresholds.
- 2026-10-18 owner validated R4.2 (BDR-058): thresholds 400,000 / 1 GiB final; R4.3 go on feature branch; app import switch gated on the 20–50 MiB file memory fix (WebKit 324 vs 76 MiB) re-measured on 3 engines, and leak series (init apart, ≥ 5 imports, ≤ 10 MiB recurring). LRN-061, LRN-062 written. Next: R4.3a bytes API + streaming read, worker protocol, HomeRoute, CSP proof, series measurements.
- 2026-10-18 R4.3 done on feature/rust-r4-pdf-core (52471db..b08373a): FileBytes sink + import_pdf_bytes/restore_copy_bytes; worker protocol v1 (task/chunk/ack/end → ready/result/failed), page reads file in 1 MiB BYOB chunks (amendment B.1.5: WebKit worker file read ≈180 MiB), client timers + settle-once + terminate, controller, HomeRoute switched, B.1.8 messages pinned on O8/O7/O2/O3 via in-process worker, 6 suites migrated (458 app tests). Security gates: reader PASS after fix, worker PASS 7 LOW → hardenings 8ddf185. Browser proofs on dist: 666/678, W5 0 long tasks, CSP with/without OK; 50 MiB WebKit 145 vs TS 76 (was 324); leak series Chromium OK, Firefox sawtooth reclaimed, WebKit grows with same-tab navigation (control too). DEPLOY note, R4_J1.md + kit script. Open for owner: WebKit large-file gate, WebKit leak criterion. Next: owner decision, J1 on devices.
- 2026-10-18 owner: J1 authorised with both WebKit reserves (BDR-059), cap 50 MiB kept, no streaming scanner, criterion 10 MiB / 5 imports kept with same-page vs navigation split + control. Kit generated (../faunosteo-j1-kit, 13 MB, L report as rescue copy for the 42 MB export), R4_J1_RESULTS.md template. STOP: waiting for device results; no merge, no R4.4.
- 2026-10-18 J1 partial: owner ran the functional checks on a computer, no failure (browser/version, timings pending); iPhone not available, deferred → stays NON TESTÉ, blocks final R4.3 acceptance (OD-6). Proposed: continue R4.4 on the branch with the iPhone J1 as a blocking item before any merge; waiting for the owner's decision. No merge, no R4.4 started.
- 2026-10-18 R4.4 done (70007e0, 1550d21): pdf::write text/afm_data/dates (O4 55,992 widths bit-exact, 1,168 wraps, safeText every code point, upper 1,580 = Rust to_uppercase, O5 tables, O6 6,468 cells), input checks, layouts → DrawLog; O1 12 runs 2,124 calls equal, step6 text/images 24 derived. Layout L 3 ms, CAP 24 ms release. Nothing wired, module size unchanged. STOP before R4.5.
- 2026-10-18 owner validated R4.4; R4.5 go (BDR-061). Subtasks R4.5a-f in TODO. Tooling present: qpdf 12.3.2, poppler 26.01 (pdftoppm, pdfdetach), crates.io reachable.
- 2026-10-18 R4.5 done (d420f67..b44dd80): content emitter (60 streams byte-equal, numberToString 703 + V8 pow10 quirk), PNG gate + UPNG decoder (O6 108/108), own object writer (pdf-writer dropped: numberToString everywhere, no dep), serialiser, export + self-check, from_envelope; O2 14 runs equal (streams after B3, planes, links, Info, attachment), qpdf clean, poppler 0 px, O11 + N-1 + TS reader read R4 PDFs, wasm = native digests; Node TS→Rust demo 198→36 ms, L 772→57, CAP 5.7 s→0.22 s; writer linked 531.6 KB gzip (proofs build), shipped 426 KB. Gate PASS 4 LOW → hardenings. Open: one-shot path holds PNGs twice (R4.6 session must stream), L real rasters 5 s native (deflate 6), E3 judged at R4.6. STOP before R4.6.
- 2026-10-19 owner validated R4.5; R4.6 go (BDR-062). R4.6 done (9e688b6..): ExportSession (decode on arrival, chunked never-realloc file 1→8 MiB, catalog last, parts → Blob, self-check on attachment chunk), views.rs (compose_highlight requests, raster_size_of O4 57/57), wasm ExportSession + CoreExportSession, app export.ts on session (abort on unmount, User Timing), labels.ts; app suites read content streams (pdfRead.ts), app-path bytes = R4 digests (re-frozen: object order B2, hex upper-case B4), Step 6 goldens via app path, 14 O2 runs through module = digests, request SVG = TS compose text, export Rust → import Rust / TS reader / N-1 ok. E3 Chromium demo 0.67, L 0.74 (Firefox 0.66/0.67, WebKit 0.91/0.95); E4 CAP completes 3 engines (TS stopped by ceiling); peaks lower (L Chromium 805→470 MiB). Linear memory L real 62 MiB flat over 7 exports; Chromium per-export RSS growth ≈ 20 MiB on L same as TS control, plateau after 8. Shipped 519.7 KB gzip (W1). rust-check 0, pnpm check 1,099 tests, ledger 11 pending (R4.7). J2 kit + procedure. STOP before R4.7.
- 2026-10-19 owner accepted R4.6 provisionally (Chromium series = open reserve); R4.7 go (BDR-063). R4.7 done: `pdf::compare` (feature `cli`), `report-compare` bin, `scripts/report-compare.sh` behind root `report:compare`, cargo `pdf_compare` 15 tests: O10 230 rows (158 exact, 72 declared A.3 → 62 `report document invalid`, 7 surrogate refusals, 3 `version null`), 11 scenario cases = ledger targets (301 rows, 0 pending), binary spawned 8×. Release binary 7 ms/PDF, 6 MiB RSS; module unchanged 1,535,289 B / 519,795 gzip. RUST.md §10.9, CLAUDE.md, PDF-FORMAT. STOP before R4.8.
- 2026-10-19 owner validated R4.7; R4.8 go (BDR-064). R4.8 done: packages/pdf (70 files, 12,010 lines TS), TS CLI, TS import path, generators, ts-engine comparison deleted; deps pdf-lib / @pdf-lib / resvg / @faunosteo/pdf / tsx / @faunosteo/domain (app) gone, xmldom only under anatomy; test read-back on own `pdfFile.ts` reader, view goldens from captured session SVGs, N-1 scanner exported via core-wasm/n-1, in-process import helper on module reader; `r4.census` suite (8); ledger 301 rows from frozen TSV, 0 pending; app 427 tests, core-wasm 58; docs RUST.md §10.10, CLAUDE.md, README, PDF-FORMAT, DEPLOY rollback R4, CHANGELOG R4 entry, hardening §5 pdf-lib closed. STOP before R4.9.
## 2026-10-20 (R4.9 final checks)
Owner validated R4.8; R4.9 go. check:all green ×2. Memory bench (5 dims, 3 engines, rest windows, Chromium pressure + raster control): linear flat after init, all canvases/Blobs/URLs released, Chromium 20 MiB/L export = browser raster path (control identical, plateau after 8) → accepted temporarily, BDR-065. PDF_IMPORT_HARDENING §6 (20 rows). J1/J2 re-issued (OD-6 list, J1.13, J2.12-14, report:compare dry run identical), kits regenerated outside repo. Gates: verifier ECARTS → no-feature core build fixed + rust-check guard; §6 J2 row; security BLOCK(1) gitleaks marker = owner; serve.mjs wildcard bind fixed (3 re-gates), CLI bounded read. EVAL-025, LRN-065. packages/pdf/node_modules rm refused by permissions → owner. No merge, no R5.
## 2026-10-21 (R4.10 J1/J2 anomalies)
Owner results: Chrome/Firefox/Brave/Android run, Safari iOS not; J1.7 FAIL Firefox+Brave, J2.3 FAIL, rest PASS declared without browser split (declared column only, device cells NON TESTÉ). A: repro headless → serve.mjs lacked nginx Cache-Control on /assets/ (Chromium refuses cached worker chunk offline); fixed, harness `r4-offline-import.mjs` 6/6, negative run exit 1; picker freeze not reproducible headless → discriminating step in `R4_MINI_RECETTE.md`. B: nologos reference archive has null logo slots; editor export always uses bundled `loadBranding()` (same at 66909b6); J2.3 expected result wrong since R4.6 → owner decision, no code change. RUST.md §10.12, LRN-066. Gates dispatched. No merge, no R5.
## 2026-10-21 (R4.10 decisions, J1.7 rectified, ZenQuality logo)
Owner: J2.3 option 1 (current branding on editor export; expected result corrected, no engine/golden/oracle change); gitleaks `[gated 2026-10-18]` marker applied on owner's written authorization; R4.8 trace verified: 23 test files deleted by 0dc1ba2 (RUST.md said 21 → corrected), 22 in ledger, ts-engine test in §10.10, approval = R4.9 contract header + BDR-064. J1.7 rectified by owner: picker opens after ~60 s with system network cut, same via Ctrl+O → functional PASS, performance reserve, cause unclaimed; cache-header fix kept. ZenQuality footer logo: hotlink refused by documented CSP (VPS proxy, not docker nginx; faunosteo.com sends no CSP today; PDF unaffected) → bundled exact remote PNG, Footer test, `r4-app-csp.mjs` counts every violation (12/12 none), offline harness 6/6, app 429 tests. LRN-067. Verifier + security dispatched. No merge, no R5, Safari iOS pending.
## 2026-10-21 (R4.10 owner verdict recorded, scope + redaction)
Owner verdict: J1.7 PASS w/ reserve, M3 complementary, J2.3 option 1 final, logo bundle + CSP hardening validated, gitleaks marker valid (writing delegable), 23 R4.8 deletions authorized (21 = census error), Safari iOS real device only → BDR-066, RUST.md §10.11/§10.12 D, recette docs. Contract FILE SCOPE amended (itself, memory, redactions), criteria 9-12 added, none removed. Redacted `/home/<user>` + scratchpad paths in results JSON, contracts, README, history plan; harness now writes repo-relative distDir. LRN-068. Verifier left to orchestrator. No merge, no R5.
- 2026-10-21 R4.10 final: check:all green on 8943bf3; verifier CONFORME 12/12 (scope incl. contract itself, floor clean); security PASS (2 LOW: username readable in contract criterion 11 regex; pre-existing gated gitleaks allowlist). Waiting owner Safari iOS J1/J2 + explicit merge signal. No merge, no R5.
- 2026-10-21 R4.12 pre-merge fixes: D3 safeNextPath re-probes rebuilt path (dot segments → //host refused; 5 tests, 3 red on old), D1 worker on distroless static-debian13 (e2e:avatar 5/5), D6 DEPLOY http2 on with nginx 1.24 form kept (1.24 rejects `http2 on`, proven nginx -t). check:all green; verifier CONFORME 9/9; security PASS (fuzz 218, 0 escape). D2/D5 → a11y chantier, D4 → backlog. STOP pre-merge; Safari iOS pending.
+53
View File
@@ -466,3 +466,56 @@ Apply: Rust ports of JS readers of untrusted text (R4 PDF reader, Step 13 upload
- `--target web` glue keeps the instance in module scope (`let wasm`, `__wbg_finalize_init`); ES module records are never unloaded, so each fresh glue import (`?instance=n`) keeps its old instance and memory (BLK-012: dead instances retained until reload). Linear memory never shrinks.
- Memory-heavy one-shot work: reuse the long-lived instance (high-water kept until reload) or run in a Worker terminated after (everything freed). A "disposable instance" on the main thread is a leak, not a release.
Apply: R4 import worker and export placement, any future in-browser wasm batch job.
## LRN-061 | 2026-10-18 | A multi-budget pre-scan must keep every budget sound, even once another check already refuses
- R4.2 `json_js::prescan` returned early at depth > 64 with the partial value count; the PDF probe checked both verdicts, the rescue copy checked values only → a 16 MiB copy nested 65 deep reported 66 values, passed the budget, built 792 MiB (security gate BLOCK, fixed 593893a: count runs to the end, depth verdict kept).
- Rule: one linear pass serving several guards finishes every measure; an early return for one verdict silently disarms the callers that rely on the others. Controls must never neutralise each other; a refusal path stays bounded in time and memory.
Apply: any shared pre-scan / lexer feeding several caps (R4.3 worker, R5 pipeline, Step 13 uploads); test each guard alone with the other verdict already failing.
## LRN-062 | 2026-10-18 | Non-finite numbers: follow the JSON actually serialised, not the JS type before serialisation
- `parseVersioned` tested `typeof version === 'number'` on `JSON.parse` output: `1e999` → `Infinity`, a number, so the probe accepted; `JSON.stringify` then wrote `null`, so the core saw no version → `no_attachment`. A Rust port that rewrote overflow → `null` before the probe gave `attachment_stripped` (3 O8 rows).
- Fix: probe on a copy where overflowing tokens stay finite numbers (`rewrite_overflow_numbers_as_finite`, `0`), hand the `null` form to the core. Same family as LRN-059 (overflow, lone surrogates): every JS parse → stringify hop is a transformation to reproduce step by step, in order.
Apply: porting any JS reader whose acceptance test ran between parse and stringify (R4 writer inputs, R5 pipeline, server validation).
## LRN-063 | 2026-10-19 | wasm linear memory: never grow one big Vec; long-lived chunks big enough not to interleave with transients
- Growing `Vec<u8>` for a 44 MiB file in wasm (dlmalloc) peaked 125 MiB: realloc keeps old + new while copying; decode transients (≈ 10 MB per PNG) sit between file and heap top so no in-place growth. Linear memory never shrinks → spike is the high-water for the page.
- Fixed chunks (never realloc) remove the spike. 1 MiB chunks still cost 0.12 MB per view (long-lived alloc every other raster interleaved with transients → fragmentation); 8 MiB chunks cost 0. Adaptive target 1 → 8 MiB: small files pay one small chunk, big files few long-lived allocs. `shrink_to_fit` on seal gives slack back.
- Hand chunks to JS one by one (`take_part`, freed in module), `new Blob(parts)`: file never held twice across heaps.
Apply: any wasm producer of large outputs (R5 pipeline, future image work): measure stage by stage with `memory.buffer.byteLength`, never trust the estimate.
## LRN-064 | 2026-10-19 | Test facts from the produced PDF, not from draw-call spies; recorder order ≠ file order
- Step 6 goldens were recorded by spying pdf-lib `drawText`/`drawImage`: footers recorded after every page's content (global call order). Read back from content streams, facts come page by page. Same set, same within-page order: compare against the golden stably sorted by page.
- `tests/helpers/pdfRead.ts`: pdf-lib loads the file, inflates each content stream, parses `Tf/Tm/Tj/ET` and `cm … Do`, resolves `/F1` through page resources, WinAnsi = windows-1252. Lets 16 roundtrip + 7 goldens cases run unchanged on the Rust output.
Apply: when an implementation is swapped under a test that spied the old one, read the artefact instead of mocking the new one; keep the old generator pinned to the old engine (r4.writer-oracles → `exportReportArchive`).
## LRN-065 | 2026-10-20 | Feature unification hides no-default builds; host refusal by resolution, not spelling; control run isolates browser memory
- `cargo test --workspace` unifies features across members: crates/wasm enabling `pdf-read` made core compile in every gate while `cargo check -p faunosteo-core` (default = []) failed. Apply: gate runs one per-crate no-feature build (`cargo clippy -p <crate> --all-targets`) whenever a crate has optional features.
- Refusing wildcard binds by string set fails: getaddrinfo accepts `0`, `0x0`, `0.0.0`, `0::`, `::ffff:0.0.0.0`, `::%lo`. Apply: `dns.lookup(host,{all:true})` → refuse if any result in `BlockList(0.0.0.0, ::)` (scope stripped, type from `net.isIPv6(address)`), listen on resolved literal, re-check `server.address()` (its `family` is 'IPv6', lookup's is 6).
- Opening before stat-checking type blocks on a FIFO (O_RDONLY): stat path first, then open, then fstat recheck.
- Browser RSS growth across exports: run the same raster steps with no core call (control) in the same page; same slope + same plateau = browser cache/allocator, not app retention. FinalizationRegistry counters + createObjectURL/revoke ledger + CDP `Performance.getMetrics` / heap census separate page-held objects from renderer memory; `Memory.simulatePressureNotification critical` tests reclaimability.
## LRN-066 | 2026-10-21 | Recette server must mirror production cache headers; headless never proves native dialogs
- Offline import (J1.7) failed on owner's Brave + Firefox but harness server `serve.mjs` sent no `Cache-Control` on `/assets/` while nginx sends `immutable`: Chromium refuses stale cache entry offline (`net::ERR_ABORTED`), Firefox offline mode serves it anyway, WebKit headless never serves worker script from cache offline. Apply: any test server standing in for prod copies prod's cache + CSP lines verbatim and the harness asserts them (`r4-offline-import.mjs`); test "offline" two ways (Playwright `setOffline` + server killed), they differ per engine.
- Headless browsers replace OS file dialogs: a frozen `<input type=file>` picker cannot be reproduced or excluded headless. Apply: write a discriminating human step (Ctrl+O in empty tab offline, kit copied local) instead of claiming a cause.
- Expected recette result written from an oracle fixture (`nologos` = fetch 404 mode) described the fixture, not the product rule (editor export always embeds bundled branding; archived branding only via `export_from_envelope`). Apply: before writing an expected result, trace which code path the recette step actually runs.
## LRN-067 | 2026-10-21 | "Known violation" excluded from a verdict hides a real defect; wait before calling a dialog frozen
- Footer hotlinked `zenquality.fr` logo since 2026-05-21, same day DEPLOY.md CSP `img-src 'self'` written; R2 + R4 CSP proofs saw refusal on every page, harness listed it as `KNOWN_IMAGE_HOST` and excluded from verdict → nobody fixed it for 5 months. Live site sends no CSP yet, so symptom invisible. Apply: a harness never carries a "known" exception longer than one slice; either fix the cause or open a TODO line with owner date. Bundle third-party images (`?url`, exact remote bytes = no branding change) instead of widening CSP.
- Owner's J1.7 "picker never opens, browser unusable" = OS file dialog taking ~60 s to open with system network cut (same from Ctrl+O in empty tab). Apply: recette step for any "hang" says wait 2 min before declaring FAIL and records time; a symptom reproduced outside the app closes the app-defect hypothesis, cause of delay stays unclaimed unless traced.
## LRN-068 | 2026-10-21 | Contract FILE SCOPE lists itself, memory files by name and every redaction; harness results carry repo-relative paths
- R4.10 verifier: 8/8 MET but formal gap: contract's own file in the diff, absent from FILE SCOPE ("memory" written vaguely). Apply: FILE SCOPE names the contract path, each `.claude/memory/*.md` and TODO touched, and gets amended in the same commit as any later scope growth; never drop a CHECK to pass.
- `scripts/browser/lib/app-build.mjs` wrote absolute `DIST_DIR` (user home) into committed results JSON from R4.6 on (older runs relative). Apply: any committed report names paths relative to repo or a placeholder; scan `git grep -E "/home/|-home-"` before each report commit.
## LRN-069 | 2026-10-21 | Runbook syntax fixes need the target's real version; URL sanitiser must re-check its own output
- Context7 said nginx `listen ... http2` deprecated → `http2 on;`, but live VPS sends `Server: nginx/1.24.0` and 1.24 rejects `http2 on` (`unknown directive`). Apply: before changing a runbook directive, read the target's version (Server header, `nginx -v`) and `nginx -t` both forms in throwaway containers of each version; document both when the fleet straddles.
- WHATWG URL normalisation can create the escape it was meant to catch (`/..//host` → pathname `//host`, same origin for the probe). Apply: sanitiser re-validates the value it returns (not only the input), plus an idempotence test; fuzz with dot segments, `%2e`, tabs inside `..`.
+96 -11
View File
@@ -203,21 +203,106 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [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
- [x] R4 pdf core (CLOSED 2026-10-21: owner J1 + J2 on computer, Android and real iPhone declared passed, R4.12 validated, merged into develop; RUST.md §10.15): 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
- [x] R4.0 plan (owner go 2026-10-17, arbitrations A1-A13): `.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md` rev 2 after 3 challengers (correctness 6 major, robustness 10 major, simplicity 3 major; none fatal) on chore/rust-r4-plan; Playwright Firefox 157 installed + proven, WebKit 27.2 downloaded (owner: `sudo apt-get install libevent-2.1-7t64 libmanette-0.2-0`); validated by the owner 2026-10-18 with conditions (plan §A.6, BDR-057)
- [x] R3 closed checked 2026-10-18 (8df964b on develop, branch gone); chore/rust-r4-plan finished into develop ae17097 (owner signal 2026-10-18)
- [x] Safari PDF download fix (bugfix/pdf-download-webkit, 2b8000e + docs + CHANGELOG in owner wording): owner iPhone run 2026-10-18 all OK (several views, warnings alert, prompt open > 30 s); check green (1015 tests, typecheck, lint, build); merged fcff92b
- [x] cut feature/rust-r4-pdf-core from develop fcff92b (owner go 2026-10-18); WebKit libs installed by owner 2026-10-18, Playwright WebKit 27.2 runs workers + wasm
- [ ] R4.1 freeze (O1-O13, ledger, browser harness, TS baselines)
- [ ] R4.2 reader (cargo + wasm, differential, OD-3 thresholds confirmed with owner before R4.3)
- [ ] R4.3 import worker + rescue copy (B.1.5, OD-1 applied, browser proof per slice from here)
- [x] cut feature/rust-r4-pdf-core from develop 66909b6 (after fcff92b; owner go 2026-10-18); WebKit libs installed by owner 2026-10-18, Playwright WebKit 27.2 runs workers + wasm
- [x] R4.1 freeze (O1-O13, ledger, browser harness, TS baselines)
- [x] R4.1a O11 frozen TS scanner copy + O13 synthetic reports L (60×2), CAP (500×2)
- [x] R4.1b writer oracles: O1 draw logs (12), O2 R3 PDFs (12 + real raster + store path), O3 pre-R2 envelope PDFs
- [x] R4.1c text, AFM, dates, PNG oracles (O4, O5, O6)
- [x] R4.1d reader oracles: O7 outcomes + inputs as bytes, O8 differential (full R3 path), O9 inflate (Node)
- [x] R4.1e browser harness (scripts/browser, Chromium + Firefox + WebKit, 4 GiB RSS watchdog): O9 browser verdicts, O12 TS baselines (export demo/L/CAP, import O2 + hostile)
- [x] R4.1f O10 report:compare outputs, test ledger (crates/core/tests/pdf/LEDGER.tsv), freeze record (RUST.md §10 draft, fixtures README)
- [ ] R4.2 reader (cargo + wasm, differential, OD-3 thresholds confirmed with owner before R4.3); owner go 2026-10-18 (R4.1 validated: fixtures kept, gitleaks exception accepted if narrow, decoy-first kept in register + risk explained before R4.3, headless accepted; stop at end of R4.2, budgets = whole browser, same perimeters as TS when a gain is claimed)
- [x] R4.2a `crates/core/src/pdf/read/{scan,strings,stamp}.rs`: scan.ts port (header, typed dicts, stream bounds, Filespec names, /Keywords stamp, decodePdfString; JS regex semantics explicit); cargo tests on O7 findEmbeddedFiles / hasArchiveStamp / decodePdfString rows (155 inputs incl. semantics rows)
- [x] R4.2b `pdf/read/inflate.rs` (miniz_oxide, zlib framing, DecompressionStream verdicts): cargo tests on O9 (26 rows) + O7 flate inputs; Node verdict pinned, browsers agree (inflate.browsers.json)
- [x] R4.2c `pdf/json_js.rs`: `{` probe after BOM/whitespace, depth 64 + value-count pre-scan (OD-3 budget hook), lossy UTF-8 + one BOM (TextDecoder parity), overflow → null rewrite, lone-surrogate-neutralised probe through parse_json, versioned check; unit tests + text parity cases
- [x] R4.2d `pdf/read/probe.rs` locate_attachment (shared 16 MiB budget, `break` on oversized, cancelled inflation not charged), `pdf/import.rs` (read → session::import_archive), op `pdf.import` + `SheetHandle.importPdf(bytes)` on the wasm facade, ts-rs `PdfImportKind`; cargo tests on O7 locate/readAttachedDocument/readReportArchive rows, O8 differential (51), Node tests through the wasm build on O2/O3/O8/hostile
- [x] R4.2e (Node part done: cap 400,000 = 10 × CAP envelope 39,652 values, rescue copy guarded, 1 GiB ceiling proven; browser run pending) OD-3: measurement harness (fresh wasm instance per case, time, linear memory; Node) on the hostile classes (16 MiB token-dense attachment, 16 MiB rescue copy, 50 MiB file, 16 MiB inflation, 32 candidates) + browser harness (worker page, content-process RSS, same perimeter as the TS import baseline); value budget = 10 × largest legitimate archive; `--max-memory`; W1 module size; thresholds table for the owner
- [ ] R4.2e follow-ups for R4.3: worker holds the File ArrayBuffer and its linear copy together (50 MiB file: WebKit content peak 324 MiB vs 76 TS) → release the buffer after the glue copy or read in chunks; after-GC residue 11.7 MiB first import (one-time, +1.9 then −0.2 on repeats) → owner decides the §B.3 criterion; `scripts/browser/lib/import-inputs.mjs` shortcut: copy of import-baseline's listing, fold into one module when import-baseline is retired (R4.8)
- [x] R4.2f (done 2026-10-18; RUST.md §10.3 + §10.4; STOP for the owner before R4.3) record: RUST.md §10.3 (reader, parity, budgets, thresholds, residual risks), decoy-first (OD-4) risk explanation + proof it blocks no legitimate Faunosteo document, ledger `ported` targets exist, suites green (rust:check, wasm:build, check); STOP for the owner before R4.3
- [ ] R4.3 import worker + rescue copy (B.1.5, OD-1 applied, browser proof per slice from here); owner go 2026-10-18 (BDR-058): switch gated on large-file memory fix + leak series
- [x] R4.3a bytes API: `PdfBytes` sink (reserve ≤ 50 MiB, push chunks) + `SheetHandle.import_pdf_bytes` / `restore_draft_bytes` (strict UTF-8, one BOM, OD-3 guard) so the worker streams `file.stream()` into linear memory, one copy, no JS ArrayBuffer of the file, no JSON wrapping of the copy; Node + browser re-measure of 20–50 MiB files on 3 engines (same perimeter as R4.2e)
- [x] R4.3b worker + client (`apps/app/src/core/worker/`): protocol v1 (B.1.5 items 1–7), controller module-level, timers (start, task 20 s paused when hidden), settle-once, terminate always, failure classification (worker_unavailable / crashed / timeout / read), compiled Module posted, static glue, prefetch after editor load; vitest in-process via spawn seam; no `error` event masked
- [x] R4.3c HomeRoute on the controller (routing on first KiB + size pre-checks unchanged), rescue copy through the worker, B.1.8 messages (OD-5), hydrateImport from the core output; route tests per throwable and phase, settle-once, result after timeout, error after result, unmount, second pick, main runtime untouched; message test over O2/O3/O8/hostile; 612 leaves through the worker; v2/v3 imports preserved
- [x] R4.3d browser proofs on the production build (SHEET_BUNDLE=draft dist, serve.mjs CSP): import-baseline on the app (3 engines) vs TS baseline; CSP with and without 'wasm-unsafe-eval'; leak series per owner §2 (init cost apart, ≥ 5 imports + idle, ≤ 10 MiB recurring, GC fluctuations repeated); peaks kept; WebKit repetition on dense documents (error events captured)
- [x] R4.3e (done 2026-10-18; two WebKit points for the owner: 50 MiB file 145 MiB vs TS 76, leak series not demonstrable headless) record RUST.md §10.5, DEPLOY note (worker CSP, Firefox 114 line per OD-1), PDF_IMPORT_HARDENING §5 results, J1 procedure; announce "TEST FONCTIONNEL DISPONIBLE" with the 7-point checkpoint (BDR-058)
- [ ] J1 owner checkpoint (plan A.4)
- [ ] R4.4 layout → draw log
- [ ] R4.5 serialiser (pdf-writer, self-check, from_envelope)
- [ ] R4.6 app export (session in main instance, owner phone check of L)
- [ ] R4.7 report-compare in Rust
- [ ] R4.8 deletions + docs + ledger census
- [ ] R4.9 verifier + security + owner final acceptance → merge on owner signal
- [ ] R4.4 layout → draw log (owner go 2026-10-18, BDR-060; stop before R4.5)
- [x] R4.4a `pdf/write/{text,afm_data,dates}.rs`: safe_text (O4 ranges), js_upper (O4 runs/special), js_trim/whitespace, measure = units × (size/1000) with WX||250 + KPX over WinAnsi bytes (O5 tables generated by scripts/r4-afm-data.mjs), wrap_lines (JS \s+), format_date fr/en (O6 grid, years 0-99 → 19xx per A3); cargo tests on O4 measure groups, wrapLines, safeText, upper, O5 widths, O6
- [x] R4.4b `pdf/write/{mod,input,draw_log,layout/{header,footer,observation,conclusion}}.rs`: ExportInput (ts-rs) checks (branding/labels, assert_snapshot + read_svg per asset, sheet mismatch, caps), rasters by key + PNG dims (IHDR only; gate at R4.5), DrawLog ops at full precision in TS call order (footers after all pages), links, embeds, warnings; cargo O1 12 logs exact, step6 text/images goldens (24) derived
- [x] R4.4c (done 2026-10-18, STOP before R4.5) record RUST.md §10.6 (modules, parity, declared differences, performance), ledger targets, suites green, STOP before R4.5
- [ ] R4.5 serialiser (pdf-writer, self-check, from_envelope) (owner go 2026-10-18, BDR-061; stop before R4.6)
- [x] R4.5a `pdf/write/content.rs`: pdf-lib operator sequences for text/image/line/rectangle + `numberToString` (O4 cases, exponent quirks); `pdf/write/png.rs`: branding PNG gate (`pngIssue` port) + UPNG-rule decode to RGBA8 (O6 108 cases: gate verdicts + plane digests), alpha plane only when an alpha < 255; caps before allocation
- [x] R4.5b `pdf/write/serialize.rs` on pdf-writer: catalog, pages, 3 Type1 WinAnsi fonts, image XObjects (DeviceRGB + DeviceGray SMask Decode [0 1]), Link annots (Border [0 0 0], URI hex ASCII), Info (Producer/Creator Faunosteo, Title/Author/Subject/Keywords UTF-16BE hex, dates literal), attachment (EmbeddedFile Flate + Params, Filespec, Names, AF), classic xref; `export.rs` (checks → layout → serialise), `self_check.rs` (re-read with R4 reader, attachment == envelope), `from_envelope.rs`; errors `self_check_failed`
- [x] R4.5c cargo O2: 12 R3 PDFs + real raster + store path: streams equal after B3 name resolution (lopdf dev-dep), image planes equal, links equal, Info equal but Producer/Creator, attachment bytes equal (store-path: D-R11 order only); goldens/r4/pdf.*.sha256 of the R4 outputs; export-side security cases (PNG budget 28, SVG hostile, URL injection, size E2, reexport)
- [x] R4.5d external checks: `qpdf --check` clean, `pdfdetach -list` osteo-report.json, `pdftoppm -r 150` R3 vs R4 0 px (12 + real raster), O11 frozen scanner + N-1 Zod copy read every R4 PDF, stripped R4 PDF → attachment_stripped; TS reader (packages/pdf) reads R4 PDFs; R4 PDF → Rust import → same report (no data loss)
- [x] R4.5e wasm: proofs export `export_pdf_for_test` (input JSON + rasters) → wasm digests == native digests; module size with the writer linked (W1 ≤ 600 KB gzip); Node timings/allocations on demo, L, CAP vs TS baseline (same files)
- [x] R4.5f (done 2026-10-18; STOP before R4.6) record RUST.md §10.7, ledger targets, suites green; STOP before R4.6
- [ ] R4.6 app export (owner go 2026-10-19; session in main instance per OD-2; stop before R4.7)
- [x] R4.6a core `pdf/write/session.rs` `ExportSession` (B.1.4 state machine: `new` → branding batch → observation k batches → done; `add_raster` decodes + writes the image object on arrival, PNG and planes dropped; `raster_failed` → warning; closed kinds `unknown_key` `duplicate_key` `out_of_order`); `views.rs` (`raster_size_of` on O4, `compose_highlight` per (observation, view), branding SVG requests); `objects.rs` streams into one buffer (catalog/pages written at the end, B2: R4 digests re-frozen once, declared); layout split (branding / observation / finish) over an `ImageSink`; `export_pdf(input, &Rasters)` = a driver over the session (one code path); decode failure of a view → `view_raster_failed` (TS `embedPng` throw), not `self_check_failed`
- [x] R4.6b cargo: O1/O4/O6 and O2 suites green on the session; view SVG = TS `renderHighlightedView` text (compose oracle), raster sizes = O4; state-machine refusals; warnings order (rejection order then view order); memory: linear high-water on demo/L/CAP via the proofs build vs PDF size
- [x] R4.6c facade: `ExportSession` wasm-bindgen struct (`new(input)`, `next()` → `ExportStep` JSON, `add_raster(key, bytes)`, `raster_failed(key)`, `finish()` → bytes, `warnings()`), ts-rs `ExportInput` `RasterRequest` `ExportStep` `ExportWarning` `ExportErrorKind`; `CoreRuntime` session wrapper (generation-bound, `invoke`, `free` in finally); proofs export kept for the digests
- [x] R4.6d app: `apps/app/src/pdf/labels.ts` (verbatim from `packages/pdf/src/i18n`), `export.ts` on the session (snapshot, branding, `new Date()`, `next` loop, `browserRasterizer` under `Promise.all`, `raster_failed` in rejection order then `add_raster` in request order, `finish`, free); EditorRoute alerts unchanged; `exportReportToPdf` keeps its signature; `@faunosteo/pdf` leaves `apps/app/src` (tests keep it until R4.8)
- [x] R4.6e app suites: pdf.goldens (Step 6 text/images/links via the app path, Rust output), pdf.roundtrip, pdf.export.app (re-export via core), EditorRoute.export, coreStopped/coreFailures mocks; app-path bytes = R4 digests (stub rasters, FIXED_EXPORTED_AT); 612 leaves exported + re-imported on Rust; export Rust → import Rust, → TS reader, → N-1 (O11 + Zod): no loss
- [x] R4.6f browsers (scripts/browser): Rust vs TS composed-view rasters pixel-identical (Chromium, Firefox, WebKit); E3/E4 harness demo/L/CAP, same data, TS vs Rust: total, raster, serialise, linear memory, JS heap, RSS; release proof on success / raster error / cancel (unmount) / recovery (trap mid-session); W1 shipped module with the writer linked (gzip -9; report > 550 KB)
- [x] R4.6g docs: RUST.md §10.8 (buffers ownership and lifetimes, allocations, release proofs, E3/E4 tables, W1, deviations: catalog at the end, decode at arrival, logo batch order), DEPLOY.md if the module size line moves, fixtures README, ledger rows (pdf.goldens, pdf.roundtrip targets filled), memory (BDR, LRN, journal)
- [x] R4.6h (done 2026-10-19; STOP before R4.7) owner recette procedure (visual + functional on the owner's devices: FR/EN, logos, annotations, real rasters, links, L on the phone), report, STOP before R4.7
- [ ] R4.7 report-compare in Rust (owner go 2026-10-19, R4.6 accepted provisionally; stop before R4.8)
- [x] R4.7a core `pdf/compare/{mod,lines,run}.rs` behind feature `cli` (= pdf-read + pdf-write): `esc` on the V8 `[\p{Cc}\p{Cf}\u2028\u2029]` table (`SAFE_TEXT_DROPPED`), `Comparison` (header, v3 and migrated observation lines, footer, normalized, counts), `render_comparison` / `render_summary` / `diff_lines`, `parse_args`, `run(sheet, argv, &dyn Files)` → stdout, stderr, exit code; closed failure wording (A.3): `report document invalid: <core detail>` for the Zod dumps, `attachment refused: lone UTF-16 surrogate escape at byte N` for the kept surrogates, `report version null cannot be read` for an overflow read as null; `as_str` on Severity, SeverityV2, LateralSide, SnapshotRejection
- [x] R4.7b `src/bin/report_compare.rs` (feature `cli`, the only std::fs file): seed sheet from `supabase/seed/anatomical-sheets/equine/draft` (ref, document, map; no asset), arguments relative to `INIT_CWD`, folders expanded, size pre-check, exit code; `scripts/report-compare.sh` (rust-env + cargo run --release --features cli) behind the root `report:compare`; rust-check feature lists widened to `cli`
- [x] R4.7c cargo `tests/pdf_compare.rs`: the 230 O10 invocations in-process (158 undeclared rows exact: stdout, stderr, exit; 72 declared rows against the Rust wording per A.3 class), scenario PDF digests = `inputs`, the 11 scenario cases named for the ledger, one spawn of the real binary (usage, INIT_CWD, output = in-process); ledger rows 135–145 targets filled, `scripts/r4-ledger.mjs` regenerated
- [x] R4.7d (done 2026-10-19; STOP before R4.8) docs: RUST.md §10.9 (binary, parity 158/72, A.3 lines as printed, timing), CLAUDE.md (command, map), fixtures README if touched, memory journal; rust-check + pnpm check green; report, STOP before R4.8
- [ ] R4.8 deletions + docs + ledger census (owner go 2026-10-19, R4.7 validated; stop before R4.9)
- [x] R4.8a test read-back without pdf-lib and without the TS engine: `tests/helpers/pdfFile.ts` (reader of the writer's own files: objects, dicts, Flate streams via zlib, pages in order, Info, annots, XObject sizes), `pdfRead.ts` on it, `goldens.ts` (`readLinks` on it; `snapshotView` from the session's request SVGs captured at the rasteriser; `recordDrawing` dropped), `tests/helpers/pdfImport.ts` (`importReportFromPdf` = the module's `SheetHandle.import_pdf` + the worker's `pdfImportOf`; `importAttachment` = `sheet.ops.importArchive`), `@faunosteo/core-wasm/n-1` exports the frozen O11 scanner (`readAttachmentBytes`); suites rewritten: pdf.goldens (2×1 PNG decode read from the XObject), pdf.roundtrip (foreign PDFs = the r4/read fixtures), archive.envelopes + n-1.reader (N-1 scanner), migration.leaves, goldenReports, helpers/sheet (labels from `@/pdf/labels`), core-wasm pdf-export.session (request SVG vs the frozen R3 compose oracle)
- [x] R4.8b deletions after the consumer audit (grep census per package): `packages/pdf/**` (engine, tests, R3/R4 oracle generators, helpers), `apps/app/src/pdf/import.ts`, `apps/app/scripts/compare-reports.ts` + `compare/*`, `tests/unit/{scripts.compare,pdf.import,pdf.export.app,r4.compare-oracles,r4.tolerance-oracles,r4.writer-oracles}.test.ts`, `tests/helpers/r4-draw.ts` (what survives moves), `packages/core-wasm/tests/pdf-export.ts-engine.test.ts`; deps: `@faunosteo/pdf` (app, core-wasm), `pdf-lib` + `tsx` + app `report:compare` script (app), Dockerfile COPY line; `pnpm install` → lockfile without pdf-lib, @pdf-lib/*, @resvg/resvg-js; `@xmldom/xmldom` only under packages/anatomy (R5); `packages/anatomy` render untouched
- [x] R4.8c ledger: `scripts/r4-ledger.mjs` reads the frozen 301 cases from the committed TSV (no vitest run of deleted suites), re-derives dispositions (deleted suites → `deleted` with their cargo / vitest target, N-1 switch noted, read-back notes), census: every cargo target in `cargo test --list`, every vitest target in the live report, counts = 301; TSV regenerated
- [x] R4.8d non-regression proofs (owner §3): grep census test (no `@faunosteo/pdf`, `pdf-lib`, `@faunosteo/domain` import under apps/app/src, packages/core-wasm/src; the import worker path, the export session path and the root `report:compare` script named by a test), wasm:build, rust-check, pnpm check, pnpm check:all (app image, worker test + image), N-1 reader suites, O2/O3/O7/O8 fixtures still read, 612 leaves, rescue copies and quarantine suites
- [x] R4.8e (done 2026-10-19; STOP before R4.9) docs: RUST.md §10.10 (deleted files and packages, dependencies removed, Rust-only features, TS still legitimate with reasons, tests, risks, R5 prerequisites), CLAUDE.md (stack table, map, PDF conventions, workflow lines), DEPLOY.md (module size, rollback), PDF-FORMAT, PDF_IMPORT_HARDENING §5, TEST_STRATEGY, WORKSPACE, packages/README, fixtures README, CHANGELOG (Unreleased), README; memory (BDR, journal); report, STOP before R4.9
- [ ] R4.9 final verification, independent audits, J1/J2 recettes (owner go 2026-10-20, R4.8 validated; no merge, no R5, stop at the checkpoint)
- [x] R4.9a memory bench (owner §3: the Chromium 10 MiB reserve of R4.6 is NOT closed by R4.8): `scripts/browser/r4-memory-bench.mjs` on the series machinery, one editor tab, demo + L, ≥ 6 exports after the init export, reproducible; five readings told apart per step: (1) wasm linear memory (`WebAssembly.Memory` captured at instantiation), (2) content-process RSS (watchdog), (3) live canvases / images / bitmaps / blobs / object URLs (FinalizationRegistry counters + createObjectURL/revoke ledger; Chromium heap-snapshot class census), (4) transient peak during the export (RSS sampler), (5) retained after the exports: settled, after the 30 s `downloadBlob` revocation window, after leaving the editor (Home) + GC; three engines; results JSON + table in RUST.md §10.11; cause / severity / fix proposed if a durable retention is confirmed, nothing declared resolved without a measure
- [x] R4.9b import security classification (owner §4): every open point of PDF_IMPORT_HARDENING §5 and of BDR-058 / BDR-059 / BDR-063 in one table: fixed with proof / accepted temporarily with justification / blocking before merge / before public exposure or upload activation; written in PDF_IMPORT_HARDENING.md §6, hostile refusals kept, no silent change of user data
- [x] R4.9c J1 + J2 recettes refreshed (owner §5): `R4_J1.md` / `R4_J2.md` on the R4.8 state (export on the core, no TS engine), device list per plan OD-6 verbatim (computer: Chrome + Firefox; iPhone: Safari iOS; low-end Android: its browser), kits regenerated (`r4-j1-kit`, `r4-j2-kit`) and checked, `pnpm report:compare` step in J2, results templates NON TESTÉ untouched; announce TEST FONCTIONNEL J1 DISPONIBLE + TEST FONCTIONNEL ET GRAPHIQUE J2 DISPONIBLE; no human test declared done
- [x] R4.9d full checks: `pnpm check:all`, PGlite suite, wasm size line (519,795 B gzip accepted; budget 600 KB / report 550 KB kept, proofs test unchanged), oracles + goldens diff vs R4.1 freeze = empty
- [x] R4.9e independent audits (owner §6): contract `.claude/tasks/contracts/2026-10-20-rust-r4-final-1000.md` (owner §2 list as criteria), fresh verifier + fresh security audit in parallel; real anomalies fixed minimally with regression tests + targeted re-audit; oracles/goldens unchanged
- [x] R4.9f docs + memory: RUST.md §10.11 (bench, classification, audits, checks, residuals), CHANGELOG, TODO; BDR / EVAL / journal; commits on `feature/rust-r4-pdf-core` (hooks push)
- [x] R4.9 results (2026-10-20): bench = linear flat, objects/URLs released, Chromium growth = browser raster path (control identical, plateau), BDR-065; §6 20 rows; recettes re-issued + kits; check:all green 49b812b; verifier CONFORME 16/16 (pass 3); security PASS after BLOCK(1) gitleaks marker (owner) + host bind fix ×3 re-gates; EVAL-025, LRN-065
- [x] R4.9g checkpoint report (owner §9: verifier, security, checks, memory + reading, residual risks, real merge blockers, J1/J2 instructions, git state) → STOP; merge and R5 only on the owner's explicit signal (delivered 2026-10-20)
- [ ] R4.10 J1/J2 anomalies (owner 2026-10-21: J1.7 FAIL Brave + Firefox, J2.3 FAIL; no merge, no R5, no release, no faunosteo.com)
- [x] R4.10a results recorded as declared: J1.1-J1.6, J1.8-J1.13 PASS declared (no per-browser split given: cells stay NON TESTÉ per device, declared status in a note), J1.7 FAIL Brave + Firefox, J2.3 FAIL, others PASS declared; Safari iOS NON TESTÉ; Brave noted as outside the OD-6 list
- [x] R4.10b anomaly A diagnosis: headless repro (Chromium, Firefox, WebKit; emulated offline): Chromium refuses the worker chunk offline = serve.mjs sends no Cache-Control on /assets/ while nginx sends `public, max-age=31536000, immutable` → recette surface defect; picker freeze not reproduced headless (native dialog) → discriminating protocol for the owner
- [x] R4.10c fix A: serve.mjs mirrors nginx.conf cache headers (/assets/ immutable); regression harness `scripts/browser/r4-offline-import.mjs` (J1.7 offline on the 3 engines + header check)
- [x] R4.10d anomaly B diagnosis: editor export always embeds the bundled branding (Step 6 rule, unchanged since 66909b6); archived branding reused only by `export_from_envelope` (cargo); J2.3 expectation wrong (R4.6 wording) → owner decision, no code change
- [x] R4.10e gates: verifier CONFORME 7/7; security PASS, 2 LOW applied (immutable by resolved folder, harness child cleanup) + targeted re-gate; mini-recette `R4_MINI_RECETTE.md`; LRN-066; commits 63034e1..baebb98
- [x] R4.10f owner decisions (2026-10-21): J2.3 option 1 (editor export keeps the application's current branding; the archive keeps its data for a faithful reproduction); J1.7 stays open (cache fix accepted, picker freeze unexplained, Ctrl+O = a clue not a proof, network-share hypothesis not confirmed); Safari iOS pending (real device, no simulator for memory); gitleaks marker authorised again; R4.8 deletion trace to verify; ZenQuality footer logo to diagnose
- [x] R4.10g J2.3 docs per option 1: R4_J2.md expected result (logos of the application's current branding, the archive's `null` slots not reused), R4_J2_RESULTS.md (declared cell = acceptable under the rule, subject to the logos matching the expected branding), RUST.md §10.12 decision line, mini-recette J2.3 line; no engine, golden or oracle change
- [x] R4.10h `.gitleaks.toml`: the exact `[gated 2026-10-18]` marker in the one allowlist description, scope unchanged
- [x] R4.10i R4.8 deletion trace: 23 test files deleted by 0dc1ba2 (one commit, nothing else on the branch); 22 traced case by case in LEDGER.tsv (ported / replaced / deleted with a target), the glue's `pdf-export.ts-engine.test.ts` traced in RUST.md §10.10 and R4.8b; approval = contract 2026-10-20 header (« Je valide officiellement R4.8 … les remplacements de tests sont approuvés ») + BDR-064; RUST.md §10.11 says 21 → corrected to 23; no new deletion
- [x] R4.10j ZenQuality footer logo (dcc7940: 12/12 CSP passes no violation, offline 6/6, app 429 tests): diagnosis (hotlink since caac149 2026-05-21; the DEPLOY.md CSP is the VPS reverse proxy's, docker/nginx.conf carries none; faunosteo.com today sends no CSP header; the PDF uses the bundled `zenquality-logo-fr.png`, unaffected; seen by the R2 and R4 CSP proofs as the known violation, never a J1/J2 item) → fix: the exact remote file bundled under `src/assets/brand/`, Footer `?url` import like the partner logo (same pixels, no branding change); `components.Footer` test (no external image source); `r4-app-csp.mjs` drops the known-host exception (any violation is a problem); build:preview + r4-app-csp + r4-offline-import re-run; CSP unchanged
- [x] R4.10k (verifier 8/8 MET, one formal scope gap: the contract file itself; security PASS, 3 LOW, protocol-relative test regex fixed 1877c4b) (owner 2026-10-21 rectification recorded: J1.7 PASS with picker-delay reserve, M1/M2 PASS ~60 s, M3-M6 NON TESTÉ, cause unclaimed, no app change) gates: verifier on the contract, security gate on the diff; docs (RUST.md §10.12, CHANGELOG), memory; report → STOP: owner's M1-M5 + Safari before any R4 close; no merge, no R5, no release, no deploy
- [x] R4.10n final gates: check:all green 8943bf3, verifier CONFORME 12/12, security PASS (2 LOW) → STOP, wait Safari iOS + merge signal
- [x] R4.10l owner verdict recorded (BDR-066: J1.7 PASS w/ reserve, M3 complementary non-blocking, J2.3 option 1 final, logo + CSP hardening validated, gitleaks marker valid with delegated writing, 23 deletions authorized, Safari iOS real device only); contract FILE SCOPE amended (contract itself, memory, redactions) + criteria 9-12; report paths redacted, harness distDir repo-relative; check:all + gitleaks/semgrep/cargo deny/pnpm audit run; verifier re-dispatch = orchestrator
- [x] R4.11 dependency maintenance (verifier CONFORME 12/12 pass 2, security PASS; checkpoint delivered, waiting owner signal) before the R4 merge (owner 2026-10-21: three advisories; minimal updates, separate commits; stop on any large migration)
- [x] R4.11a analysis: rustls-webpki 0.103.15 and webpki-roots 1.0.9 reach the tree through ureq 3.4.2 → rustls 0.23.46 (worker only, its TLS client to Supabase; no other crate); fixes 0.103.16 / 1.0.10 published, not yanked, same minor; react-router 7.15.1 through react-router-dom ^7.1.1 (app only): 5 advisories, 4 not reachable (RSC, SSR hydration, server-side route matching; the app is a BrowserRouter SPA with no loader, action or server), 1 reachable in principle (GHSA-wrjc-x8rr-h8h6 backslash open redirect through `<Link>` / `useNavigate`) but the only untrusted destination is `next`, rebuilt by `safeNextPath` from a parsed URL against a sentinel origin; latest 7.x = 7.18.4 (2026-09-15), patch-level changelog, no API change for the app
- [x] R4.11b (7a7b71c) `cargo update -p rustls-webpki -p webpki-roots` (Cargo.lock only)
- [x] R4.11c (c9dab63) react-router-dom ^7.18.4 (apps/app/package.json + lockfile)
- [x] R4.11d (a604c07) worker TLS test: an in-process rustls server with a self-signed certificate (rcgen, dev-dependency) must be refused by `HttpBackend` (certificate validation active); honest limit: proves validation, not the emSign distrust itself
- [x] R4.11g owner decisions on the Context7 review (2026-10-21): D1 distroless debian13 now, D3 safeNextPath now, D6 DEPLOY http2 now; D2 outline-hidden + D5 MotionConfig reducedMotion → accessibility chantier (not in R4); D4 config chores → maintenance backlog (below); no major upgrade
- [x] R4.12 pre-merge fixes D1 / D3 / D6 (one commit each; owner 2026-10-21; then STOP at the pre-merge checkpoint; owner validated 2026-10-21)
- [x] R4.12a (51a5a80) D3 `safeNextPath`: the returned value is resolved again against the sentinel origin and must stay same-origin and not start with `//` (dot segments `/..//`, `/%2e%2e//`, `/..\\`, tab inside `..`), else fallback; tests: dot segments, double slashes, backslashes, schemes, encodings, valid destinations unchanged; consumer test through LoginRoute (MemoryRouter) with `next=/..//evil.test` → /app
- [x] R4.12b (49b1849; e2e:avatar 5/5 on the new image) D1 worker runtime `gcr.io/distroless/static-debian13:nonroot` (provenance: GoogleContainerTools distroless, cosign-signed; same user 65532, no shell, static); worker:test, worker:image `run --check`, sandbox tests; Dockerfile only
- [x] R4.12c (60faac8; nginx 1.24 rejects `http2 on`: both forms documented, nginx -t on 1.24 and 1.31) D6 DEPLOY.md: `listen 443 ssl http2;` → `listen 443 ssl;` + `http2 on;` (nginx ≥ 1.25.1 noted); nothing else in the runbook
- [x] R4.12d (verifier CONFORME 9/9; security PASS, fuzz 218 inputs 0 escape, 3 LOW; check:all green 18:55:30) gates: check:all on the final state, pnpm audit --prod, cargo deny, worker tests, navigation suites, goldens/oracles unchanged; contract + fresh verifier + security gate; RUST.md §10.14, CHANGELOG, memory → STOP pre-merge checkpoint
- [x] R4.13 close (owner 2026-10-21 « Validation finale de R4 et autorisation de fusion »): recette results consolidated as declared (iPhone Safari iOS J1 + J2 PASS as a whole, missing details listed not invented; J1.7 PASS w/ reserve; J2.3 PASS under the approved rule; M3 NON TESTÉ), RUST.md §10.15 (residual risks table, deadlines), PDF_IMPORT_HARDENING.md §7 (items 3/19 unblocked, 5/6/7/9/20 still open), CHANGELOG headers; final checks on 22bbfb4: check:all green 22:15:50, audit --prod clean, gitleaks 111 commits clean (tree: git-ignored `.env.worker` only), no local path / personal id, merge-tree clean, goldens/oracles/digests untouched, 51 deletions all in 0dc1ba2; then `gitflow finish` → develop (no-ff), branch deleted. Not done: release 0.2.0, deploy, DNS, R5, D2/D4/D5
- [ ] accessibility chantier (owner 2026-10-21, after R4, needs a visual recette): D2 `focus-visible:outline-none` → `outline-hidden` in the 13 files listed in `.claude/audits/CONTEXT7-2026-10-21.md` (keyboard focus, forced-colors, graphic coherence); D5 `<MotionConfig reducedMotion="user">` at the root (Dialog scale, ObservationCard height animations, transitions)
- [ ] maintenance backlog (owner D4, accepted in principle, not scheduled): apps/app/vitest.config.ts dead `coverage` block (no @vitest/coverage-v8); tests/setup.ts → `@testing-library/jest-dom/vitest`; eslint.config.js `tseslint.config` → `defineConfig`; ui/Input, Select, Textarea `forwardRef` → ref prop (React 19); authStore.ts:95-97 stale deadlock comment; no major upgrade (react-router 8, zod 4, TS 7, vite 8 + vitest 4, ESLint 10, PGlite 0.5 stay out) (`.claude/audits/CONTEXT7-2026-10-21.md`: distroless debian13, Tailwind outline-hidden, safeNextPath dot segments, dead coverage block, jest-dom entry, tseslint defineConfig, forwardRef, DEPLOY http2, reduced motion) → nothing changed until decided
- [x] R4.11e checks (rust-check, deny advisories ok, audit --prod clean, app 429, check:all green 17:27:54, goldens untouched, criterion 11 generic; gates dispatched): rust-check, `cargo deny check advisories` clean, `pnpm audit --prod` clean, app suite (routing, auth, redirects), check:all (images, sandbox), goldens and oracles unchanged (git status), contract + fresh verifier + targeted security gate; contract criterion 11 regex made generic (owner §6)
- [x] R4.11f docs (RUST.md §10.13, CHANGELOG, contract 1700): RUST.md §10.13 table (advisory, old, new, audit, residual), CHANGELOG, DEPLOY if the TLS note changes; memory; checkpoint table → wait for the owner's signal
- [x] R4.10m (closed by R4.11: rustls-webpki 0.103.16 + webpki-roots 1.0.10 in 7a7b71c, react-router-dom 7.18.4 in c9dab63; `pnpm audit --prod` clean at the close; the full audit's 54 advisories are dev tooling only, 26 on the pinned pnpm itself) security reserves found by the R4.10l checks, pre-existing, not fixed (dependency upgrades = owner decision, outside R4.10 scope): RUSTSEC-2026-0382 rustls-webpki 0.103.15 + RUSTSEC-2026-0381 webpki-roots 1.0.9 (worker → ureq; `cargo update -p rustls-webpki -p webpki-roots`; advisories warn-only in check:all, release gate blocks); `pnpm audit --prod` 5 (react-router <7.18.2: 2 high, 3 moderate; several RSC/framework-mode only, open-redirect GHSA-wrjc-x8rr-h8h6 applies to `<Link>`/`useNavigate`); full audit 57 incl. 2 critical tinypool (vitest, dev only); gitleaks history 561 commits clean, working tree 1 jwt in git-ignored `.env.worker` (never committed)
- [x] owner actions: J1 + J2 on the OD-6 devices (done 2026-10-21, iPhone included); still owner-side: delete the UFW 4173 rule after the recette sessions (`sudo ufw status numbered`, `sudo ufw delete <n>`)
- [ ] owner action (non-blocking): `packages/pdf/node_modules` leftover (13 pnpm symlinks, 6 bin shims, 1 vitest cache file, 0 tracked or useful files) → `rm -rf packages/pdf/node_modules && rmdir packages/pdf` (the recursive delete was refused to Claude by the permission layer)
- [ ] outside R4 (owner 2026-10-17, non-blocking): worker container ignores SIGTERM (Docker kill after 10 s; chore, e.g. `init: true`); README test counter stale (367 vs 1,015)
- [ ] 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
- [ ] separate chore (D-R7): form constraints module + PGlite `pg_constraint`/config.toml parity test
@@ -20,7 +20,7 @@ Freeze the current PDF pipeline behaviour before any refactor: new fixtures, gol
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/routes.HomeRoute.import.test.tsx tests/unit/routes.EditorRoute.export.test.tsx 2>&1 | tail -3
EXPECT: Tests .* passed
5. Whole app suite, typecheck and lint green; no file under apps/app/src changed.
CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run 2>&1 | tail -4; git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l
CHECK: cd apps/app && corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run 2>&1 | tail -4; git -C $HOME/Documents/faunosteo status --short apps/app/src | wc -l
EXPECT: Tests .* passed ; 0
## FILE SCOPE
@@ -19,7 +19,7 @@ Give the domain package the archive contracts (sheet snapshot, envelope v1, bran
6. `packages/domain/src/report/rebase.ts`: `rebaseReportOnSheet(report, index, archived)` as spec §13; tests: same sha → untouched, `rebased false`; different sha → unknown annotation → `unresolved: true` + labels from the archived snapshot's annotation name (both locales) when the zone had none; unknown viewId → unresolved; finding with no node → unresolved; already-unresolved items stay; resolved items untouched; `report.sheet` replaced by `index.sheet.ref`; output passes `ReportSchema`.
7. Bundle: `apps/app/vite/sheet-bundle.ts` payload gains `assetHashes` (from `assets.json` `sha256` by `svg_asset_id`); `apps/app/src/sheets/provider.ts` `BundledSheetData`/`LoadedSheet` gain `assetHashes: Readonly<Record<string, string>>` and `schemaVersion: number` (from `ref.schema_version`); `parseBundledSheet` fills them; `tests/unit/sheets.provider.test.ts` asserts the hash of the horse asset equals the manifest value.
8. Green everywhere: `corepack pnpm -r typecheck && corepack pnpm -r lint && corepack pnpm -r test:run` from the repo root (domain, anatomy, supabase, app). The Phase 0 golden tests and route characterisation tests under apps/app/tests must pass unchanged.
CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm typecheck 2>&1 | tail -2 && corepack pnpm test:run 2>&1 | grep -E "Tests|Test Files" | tail -8
CHECK: cd $HOME/Documents/faunosteo && corepack pnpm typecheck 2>&1 | tail -2 && corepack pnpm test:run 2>&1 | grep -E "Tests|Test Files" | tail -8
EXPECT: all passed
## FILE SCOPE
@@ -18,7 +18,7 @@ Promote the Node-side view composer of the curation pipeline (`packages/anatomy/
EXPECT: Tests .* passed
4. Tests (xmldom, draft document + draft horse.svg): main view with two selected annotations (one point → both hitbox and twin highlighted, one spine zone), head view (no halo), nothing selected (layer empty), unknown view throws, idempotent halo (no duplicate filter when called on a root that already has one), highlight keeps `<title>`, zero `data-` attributes in the serialised output, review-mode output byte-identical to the previous `renderAppReviewDrawing` for both views.
5. `pnpm typecheck && pnpm lint && pnpm test:run` green in packages/anatomy; no other package changed.
CHECK: git -C /home/bchanot/Documents/faunosteo status --short | grep -v "^?? packages/anatomy\|^ M packages/anatomy" | grep -v ".claude/" | wc -l
CHECK: git -C $HOME/Documents/faunosteo status --short | grep -v "^?? packages/anatomy\|^ M packages/anatomy" | grep -v ".claude/" | wc -l
EXPECT: 0
## FILE SCOPE
@@ -22,7 +22,7 @@ Create `packages/pdf` (`@faunosteo/pdf`): the browser-free PDF engine that expor
9. Raster (`tests/raster.test.ts`, T10, resvg): a real `Rasterizer` built on `@resvg/resvg-js` (`fitTo width`) renders the demo report's main and head highlighted views: PNG width = 1200, height = requested ±1, pixels within ±24 of `#b85a3f` present, non-white ratio in [0.01, 0.9]; a rasterizer that throws yields a PDF whose page has no image and one `view_raster_failed` warning.
10. Size (T7): demo envelope attachment stored bytes (the EmbeddedFile stream `contents.length` found through `enumerateIndirectObjects`) < 250,000; the test prints stored and raw sizes for `nologos` and `logos` brandings.
11. Everything green: `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run` in packages/pdf, and `corepack pnpm -r typecheck` at the root; `apps/app/src` untouched.
CHECK: git -C /home/bchanot/Documents/faunosteo status --short apps/app/src | wc -l
CHECK: git -C $HOME/Documents/faunosteo status --short apps/app/src | wc -l
EXPECT: 0
## FILE SCOPE
@@ -17,7 +17,7 @@ Wire the application onto `@faunosteo/pdf`: export through the engine with a sna
6. New tests: `pdf.export.app.test.ts` (T2: export the demo fixture through `exportReportToPdf` with the real bundled sheet, then mutate a cloned LoadedSheet's labels and one geometry, re-export the ENVELOPE through `exportFromEnvelope` and assert the engine output facts equal the first export, not the mutated sheet; T13 call shape covered by Phase 0), `pdf.goldens.test.ts` adapted so the app export path reproduces the Phase 0 goldens through the engine (same spies; the `rasterizeSvg` mock becomes a mock of `@/pdf/browserRasterizer`), `routes.HomeRoute.archive.test.tsx` (T15: envelope import with same sha → archive kept in store, archive_ok alert; envelope whose sha differs → rebased alert with count, unresolved flags, labels filled, `report.sheet` updated; snapshot rejected outcome → snapshot_rejected alert with the reason label; `attachment_stripped` → its error message), `migration.leaves.test.ts` kept green (612 leaves through the new path).
7. Bundle cost: `SHEET_BUNDLE=draft corepack pnpm build` in apps/app succeeds; report the gzip size of the main JS chunk before (from `git stash`-free method: build develop in a worktree is NOT allowed; instead read the size printed by vite for the chunk containing xmldom and report the total gz of dist/assets/*.js) and the size of the xmldom portion if vite's output isolates it; ceiling 50 KB gz for xmldom's share, else report.
8. Green: from the repo root `corepack pnpm typecheck && corepack pnpm lint && corepack pnpm test:run && corepack pnpm build`; `grep -rn "fetch(" apps/app/src/pdf` shows only `branding.ts`.
CHECK: cd /home/bchanot/Documents/faunosteo && corepack pnpm test:run 2>&1 | grep -E "Test Files|Tests " | tail -8
CHECK: cd $HOME/Documents/faunosteo && corepack pnpm test:run 2>&1 | grep -E "Test Files|Tests " | tail -8
EXPECT: all passed
## FILE SCOPE
@@ -2,7 +2,7 @@
- date: 2026-10-13 | flow: ad-hoc correction (owner brief 2026-10-13, after R0 delivery) | branch: feature/rust-r0-foundation (R0 closed at bd9c7d1; this delta on top)
- status: closed 2026-10-13 — pass 2 CONFORME 11/11, security pass 2 PASS; post-pass fix 496f549 (fail-closed drift step) verified by execution (oracles 6, 9, 10 amended before dispatch after a dry run by the orchestrator; pass 1: verifier ECARTS(2) = two floor STUB hits on doc prose "(not implemented)" → reworded; security PASS with 1 MEDIUM + 6 LOW → fixes: warn-only advisories stage and porcelain drift gate in check-all.sh and ci.yml, PATH guard appends an absolute dir only, literal rm path, prctl unused arguments as unsigned long with an honest comment; evidence of pass 2 = check-all-2.log)
- spec: owner brief (REQUEST below), docs/development/RUST.md §1 and §4 (what the correction builds), docs/development/RUST_ARCHITECTURE_REVIEW.md Annex C.1
- evidence logs (runs made by the orchestrator on this host, readable): /tmp/claude-1000/-home-bchanot-Documents-faunosteo/71caaac9-9523-489e-bc17-e28e1d4fd532/scratchpad/{toolchain-install.log,warm-build.log,native-check.log,native-check-2.log,docker-alt.log,check-all.log,check-all-2.log}
- evidence logs (runs made by the orchestrator on this host, readable): <session scratchpad>/{toolchain-install.log,warm-build.log,native-check.log,native-check-2.log,docker-alt.log,check-all.log,check-all-2.log}
- the verifier never installs, uninstalls or updates anything on the host; cargo commands below run the native toolchain already installed (rustup in ~/.cargo); `~/.cargo/bin` may be absent from a non-interactive PATH: prefix commands with `PATH="$HOME/.cargo/bin:$PATH"` when `cargo` is not found. Docker commands are not re-run (read check-all.log).
## REQUEST (owner brief 2026-10-13, condensed — IMMUTABLE)
@@ -10,7 +10,7 @@ Development machine = self-hosted Ubuntu server (native, not WSL, not the VPS) w
## ACCEPTANCE CRITERIA
1. Native toolchain pinned and complete, user-level only.
CHECK: cd /home/bchanot/Documents/faunosteo && "$HOME/.cargo/bin/rustup" show active-toolchain | cut -d' ' -f1; "$HOME/.cargo/bin/rustup" component list --installed --toolchain 1.99.0 | grep -c "rustfmt\|clippy"; "$HOME/.cargo/bin/rustup" target list --installed --toolchain 1.99.0 | grep -c "^wasm32-unknown-unknown$"; "$HOME/.cargo/bin/wasm-bindgen" --version; "$HOME/.cargo/bin/cargo-deny" --version; dpkg-query -W rustc cargo 2>&1 | grep -c "no packages found"
CHECK: cd $HOME/Documents/faunosteo && "$HOME/.cargo/bin/rustup" show active-toolchain | cut -d' ' -f1; "$HOME/.cargo/bin/rustup" component list --installed --toolchain 1.99.0 | grep -c "rustfmt\|clippy"; "$HOME/.cargo/bin/rustup" target list --installed --toolchain 1.99.0 | grep -c "^wasm32-unknown-unknown$"; "$HOME/.cargo/bin/wasm-bindgen" --version; "$HOME/.cargo/bin/cargo-deny" --version; dpkg-query -W rustc cargo 2>&1 | grep -c "no packages found"
EXPECT: 1.99.0-x86_64-unknown-linux-gnu ; 2 ; 1 ; wasm-bindgen 0.2.129 ; cargo-deny 0.20.2 ; 2
2. Scripts: the two Rust scripts live under scripts/ (not docker/), source the PATH guard, and the root scripts make native the primary path with `:docker` alternatives and a single pre-merge gate.
CHECK: ls scripts | tr '\n' ' '; ls docker | grep -c "rust-check.sh\|wasm-build.sh"; grep -c "^\. scripts/rust-env.sh" scripts/rust-check.sh scripts/wasm-build.sh; grep -c '"rust:check": "bash scripts/rust-check.sh"' package.json; grep -c '"rust:check:docker": "bash docker/rust-run.sh bash scripts/rust-check.sh"' package.json; grep -c '"wasm:build": "bash scripts/wasm-build.sh"' package.json; grep -c '"wasm:build:docker": "bash docker/rust-run.sh bash scripts/wasm-build.sh"' package.json; grep -c '"check:all": "bash scripts/check-all.sh"' package.json
@@ -28,13 +28,13 @@ Development machine = self-hosted Ubuntu server (native, not WSL, not the VPS) w
CHECK: grep -c "gated" crates/worker/src/decode.rs crates/worker/src/sandbox.rs; grep -c "unsafe {" crates/worker/src/decode.rs; grep -c "// SAFETY:" crates/worker/src/decode.rs; grep -c "unsafe {" crates/worker/src/sandbox.rs; grep -c "// SAFETY:" crates/worker/src/sandbox.rs; grep -rc "unsafe {" crates/core/src crates/wasm/src | grep -vc ":0$"; grep -c "width.checked_mul(4)" crates/worker/src/decode.rs; grep -c "c_int::try_from(width \* 4)" crates/worker/src/decode.rs; grep -c 'unsafe_code = "forbid"' Cargo.toml; grep -c 'unsafe_code = "deny"' crates/worker/Cargo.toml
EXPECT: decode.rs:0 and sandbox.rs:0 ; 6 ; 6 ; 2 ; 2 ; 0 ; 1 ; 0 ; 1 ; 1
7. The native Rust gate is green and the committed ts-rs types do not drift.
CHECK: cd /home/bchanot/Documents/faunosteo && PATH="$HOME/.cargo/bin:$PATH" bash scripts/rust-check.sh > /tmp/claude-1000/verify-rust-check.log 2>&1; echo rc=$?; grep -E "^test result" /tmp/claude-1000/verify-rust-check.log | grep -c "ok\."; grep -E "^test result" /tmp/claude-1000/verify-rust-check.log | grep -c " 10 passed\| 9 passed\| 14 passed"; grep -c "bans ok, licenses ok, sources ok" /tmp/claude-1000/verify-rust-check.log; git diff --exit-code -- packages/core-wasm/types > /dev/null && echo SAME
CHECK: cd $HOME/Documents/faunosteo && PATH="$HOME/.cargo/bin:$PATH" bash scripts/rust-check.sh > /tmp/claude-1000/verify-rust-check.log 2>&1; echo rc=$?; grep -E "^test result" /tmp/claude-1000/verify-rust-check.log | grep -c "ok\."; grep -E "^test result" /tmp/claude-1000/verify-rust-check.log | grep -c " 10 passed\| 9 passed\| 14 passed"; grep -c "bans ok, licenses ok, sources ok" /tmp/claude-1000/verify-rust-check.log; git diff --exit-code -- packages/core-wasm/types > /dev/null && echo SAME
EXPECT: rc=0 ; 12 ; 3 ; 1 ; SAME
8. The native wasm build and the TypeScript/WASM proofs pass on the module it produces; the size stays within 1 KB of the R0 builder figure (224 713 B raw).
CHECK: cd /home/bchanot/Documents/faunosteo && PATH="$HOME/.cargo/bin:$PATH" bash scripts/wasm-build.sh 2>&1 | grep "faunosteo_wasm_bg.wasm:"; corepack pnpm --filter @faunosteo/core-wasm test:run 2>&1 | grep -E "Tests "
CHECK: cd $HOME/Documents/faunosteo && PATH="$HOME/.cargo/bin:$PATH" bash scripts/wasm-build.sh 2>&1 | grep "faunosteo_wasm_bg.wasm:"; corepack pnpm --filter @faunosteo/core-wasm test:run 2>&1 | grep -E "Tests "
EXPECT: a line "faunosteo_wasm_bg.wasm: NNNNNN bytes raw, …" with 223713 <= NNNNNN <= 225713 ; "Tests 14 passed (14)"
9. The single pre-merge gate passed end to end on this host (native stages, Node pipeline, application image, worker sandbox tests + seccomp derivation, worker runtime read-only), read from the evidence log.
CHECK: L=/tmp/claude-1000/-home-bchanot-Documents-faunosteo/71caaac9-9523-489e-bc17-e28e1d4fd532/scratchpad/check-all-2.log; grep -c "^== all checks passed" "$L"; grep -c "DONE rc=0" "$L"; grep -c "== allowlist covers the trace" "$L"; grep -E "Tests [0-9]+ passed" "$L"; grep -c "test result: ok. 16 passed" "$L"
CHECK: L=<session scratchpad>/check-all-2.log; grep -c "^== all checks passed" "$L"; grep -c "DONE rc=0" "$L"; grep -c "== allowlist covers the trace" "$L"; grep -E "Tests [0-9]+ passed" "$L"; grep -c "test result: ok. 16 passed" "$L"
EXPECT: 1 ; 1 ; 1 ; six per-package lines (domain 194, core-wasm 14, supabase 24, anatomy 130, pdf 137, app 278 = 777, every one "passed") ; 1
10. Documentation reflects the three environments and the CI status; no doc still claims a Docker-only or CI-run toolchain.
CHECK: grep -c "native on the development machine" docs/development/RUST.md; grep -c "prepared, no CI active" docs/development/RUST.md; grep -c "### 5.8 Native toolchain run" docs/development/RUST.md; grep -c "C.1 Addendum 2026-10-13" docs/development/RUST_ARCHITECTURE_REVIEW.md; for f in CLAUDE.md README.md CHANGELOG.md docs/development/RUST.md docs/development/TEST_STRATEGY.md; do grep -c "check:all" $f; done | tr '\n' ' '; grep -c "no toolchain on the host\|never on the host\|all through the builder image" CLAUDE.md docs/development/RUST.md docs/development/WORKSPACE.md | grep -vc ":0$"; grep -c "(not implemented" docs/development/RUST.md docs/development/RUST_ARCHITECTURE_REVIEW.md | grep -vc ":0$"; grep -c "No CI/CD\|no CI active\|No CI runs" DEPLOY.md CLAUDE.md README.md | grep -vc ":0$"
@@ -2,7 +2,7 @@
- date: 2026-10-13 | flow: ad-hoc phase (owner go 2026-10-12, BDR-045) | branch: feature/rust-r0-foundation (base develop = 5fec065)
- status: active (amended 2026-10-13 after verifier pass 1: criteria 10 and 14 oracles counted comment lines; pass 2 CONFORME 16/16, criterion 16 oracle excludes the contract file itself; pass 3 after the security fixes: criteria 10 and 11 oracles updated to the gated SAFETY form and the second refusal arm; no code change)
- spec: docs/development/RUST_ARCHITECTURE_REVIEW.md (Part III, Annex B, Annex C), docs/development/RUST.md (what was built and proven)
- evidence logs (runs made by the orchestrator on this host, readable): /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/{pnpm-check.log,worker-test-build-5.log,worker-image-build-2.log,builder-build-2.log}
- evidence logs (runs made by the orchestrator on this host, readable): <session scratchpad>/{pnpm-check.log,worker-test-build-5.log,worker-image-build-2.log,builder-build-2.log}
## REQUEST (owner brief 2026-10-12, condensed — IMMUTABLE)
Implement R0 per Annex B: Cargo workspace with crates core, wasm, worker; pinned Rust and dependencies; reproducible Docker builder (no Rust on the VPS); native and WebAssembly compilation; working TypeScript bindings; JSON contracts compatible with the current data; first wasm size and performance measurements; applicable security and isolation tests; CI integration; development and deployment documentation. The seven proofs run in the real environment where possible (serialisation, wasm panics, musl, seccomp verified experimentally; a proof that cannot be obtained is reported, not assumed). Compatibility: the React app, Report v3, PDF v2/v3, Supabase, the interfaces and the existing tests stay unchanged; the frontend does not load the module. No migration of anatomy, PDF or business validations (R2–R5); no avatar business processing (R1). Everything dockerised; production images built in CI and pulled by the VPS; live deployment unchanged; no tag or merge into main.
@@ -33,7 +33,7 @@ Implement R0 per Annex B: Cargo workspace with crates core, wasm, worker; pinned
CHECK: grep -c "tokio" crates/worker/Cargo.toml; grep -n "vars_os().next().is_some()\|sandbox::apply(\|read_to_end(&mut input)" crates/worker/src/decode.rs | head -3; grep -n "ensure_single_thread()?;\|set_rlimits(limits)?;\|install_seccomp()?;" crates/worker/src/sandbox.rs | head -3
EXPECT: 0 ; the three lines appear in that order (env check line < sandbox line < read line) ; the three calls appear in that order
9. seccomp allowlist is the traced set plus the abort path, denies every file and process syscall, and was derived and proven on the musl binary.
CHECK: sed -n '/^pub const ALLOWED_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs | grep -c '("'; sed -n '/^pub const ABORT_PATH_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs | grep -c '("'; grep -c "open\|execve\|clone\|socket" <(sed -n '/^pub const ALLOWED_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs); grep -E "test result: ok. 16 passed|allowlist covers the trace" /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/worker-test-build-11.log | sed -E 's/^#[0-9]+ [0-9.]+ //' | sort -u
CHECK: sed -n '/^pub const ALLOWED_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs | grep -c '("'; sed -n '/^pub const ABORT_PATH_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs | grep -c '("'; grep -c "open\|execve\|clone\|socket" <(sed -n '/^pub const ALLOWED_SYSCALLS/,/^];/p' crates/worker/src/sandbox.rs); grep -E "test result: ok. 16 passed|allowlist covers the trace" <session scratchpad>/worker-test-build-11.log | sed -E 's/^#[0-9]+ [0-9.]+ //' | sort -u
EXPECT: 7 ; 7 ; 0 ; both lines present
10. The keyed parent never decodes: spawn.rs and webp_check.rs use no image decoder; output capped at 512 KiB; the RIFF check allowlists four chunk types and refuses the rest.
CHECK: grep -c "image::" crates/worker/src/spawn.rs crates/worker/src/webp_check.rs; grep -c "MAX_OUTPUT_BYTES: usize = 512 \* 1024" crates/worker/src/limits.rs; grep -c 'b"VP8X", b"VP8 ", b"VP8L", b"ALPH"' crates/worker/src/webp_check.rs; grep -c "return Err(WebpIssue::ForbiddenChunk(fourcc))" crates/worker/src/webp_check.rs
@@ -42,10 +42,10 @@ Implement R0 per Annex B: Cargo workspace with crates core, wasm, worker; pinned
CHECK: grep -l "libwebp_sys::" crates/worker/src/*.rs; grep -c "// SAFETY" crates/worker/src/decode.rs; grep -c "MIN_LIBWEBP_VERSION: (u8, u8, u8) = (1, 6, 0)" crates/worker/src/limits.rs; grep -c "the_linked_libwebp_is_recent_enough" crates/worker/tests/sandbox.rs
EXPECT: crates/worker/src/decode.rs only ; >= 4 ; 1 ; 1
12. Test hooks never ship: release build without features; the runtime image is distroless static, non-root, with `run --check` as its command.
CHECK: grep -n "cargo build -p faunosteo-worker --release --locked" crates/worker/Dockerfile | grep -c "features"; grep -c "FROM gcr.io/distroless/static-debian12:nonroot" crates/worker/Dockerfile; grep -c "^USER nonroot" crates/worker/Dockerfile; grep -c 'CMD \["run", "--check"\]' crates/worker/Dockerfile; tail -1 /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/worker-image-build-6.log
CHECK: grep -n "cargo build -p faunosteo-worker --release --locked" crates/worker/Dockerfile | grep -c "features"; grep -c "FROM gcr.io/distroless/static-debian12:nonroot" crates/worker/Dockerfile; grep -c "^USER nonroot" crates/worker/Dockerfile; grep -c 'CMD \["run", "--check"\]' crates/worker/Dockerfile; tail -1 <session scratchpad>/worker-image-build-6.log
EXPECT: 0 ; 1 ; 1 ; 1 ; exit=0
13. Frontend, live deployment and database untouched; the existing suites still pass.
CHECK: git diff --stat 5fec065..HEAD -- apps/app Dockerfile docker-compose.yml docker/nginx.conf docker/entrypoint.sh supabase packages/domain packages/anatomy packages/pdf packages/supabase | wc -l; tail -1 /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/pnpm-check.log; grep -E "apps/app test:run:\s+Tests|packages/pdf test:run:\s+Tests|packages/anatomy test:run:\s+Tests" /tmp/claude-1000/-home-bchanot-Documents-faunosteo/2fbc125b-9811-4458-8ebc-489c2f9255be/scratchpad/pnpm-check.log
CHECK: git diff --stat 5fec065..HEAD -- apps/app Dockerfile docker-compose.yml docker/nginx.conf docker/entrypoint.sh supabase packages/domain packages/anatomy packages/pdf packages/supabase | wc -l; tail -1 <session scratchpad>/pnpm-check.log; grep -E "apps/app test:run:\s+Tests|packages/pdf test:run:\s+Tests|packages/anatomy test:run:\s+Tests" <session scratchpad>/pnpm-check.log
EXPECT: 0 ; exit=0 ; 278, 137, 130 passed
14. CI: rust job before check through the builder image with the types drift check; docker job builds the worker test stage and starts the runtime image read-only with every capability dropped; advisories nightly; release-images manual only and deploys nothing.
CHECK: grep -c "needs: rust" .gitea/workflows/ci.yml; grep -c "docker/rust-check.sh\|git diff --exit-code -- packages/core-wasm/types" .gitea/workflows/ci.yml; grep -c -- "--target test\|--read-only --cap-drop ALL" .gitea/workflows/ci.yml; grep -v "^#" .gitea/workflows/release-images.yml | grep -c "^ workflow_dispatch:"; grep -v "^#" .gitea/workflows/release-images.yml | grep -cE "^\s*(push|pull_request|schedule):|ssh |scp |compose (up|pull)"; grep -c "cron:" .gitea/workflows/rust-advisories.yml
@@ -0,0 +1,226 @@
# CONTRACT — rust-r4-final (R4.9)
- date: 2026-10-20 | flow: verify (R4.9 gates) | branch: feature/rust-r4-pdf-core
- status: active
- plan: `.claude/tasks/plans/2026-10-17-rust-r4-pdf-core.md` (rev 2, owner-validated 2026-10-18, §A.6 conditions; slice R4.9 in §B.7), TODO `R4.9a–g`
- base: 66909b6 (develop tip the branch was cut from); freeze commit aada799 (R4.1, frozen oracles); d492bf7 (R4.6, the declared re-freeze of the R4 digests); run every CHECK from the repository root
## REQUEST (verbatim — IMMUTABLE)
# FAUNOSTEO — Validation R4.8 et lancement R4.9
Je valide officiellement R4.8.
Les suppressions des anciennes implémentations PDF TypeScript, le nettoyage des dépendances, le recensement des consommateurs et les remplacements de tests sont approuvés.
Les résultats annoncés de `pnpm check:all` sont satisfaisants.
Tu peux commencer **R4.9 : vérification finale, audits indépendants et préparation des recettes J1/J2**, conformément au plan R4.0 validé.
## 1. Nettoyage R4.8 approuvé
Je valide :
- La suppression de `packages/pdf`.
- La suppression de l'ancienne CLI de comparaison TypeScript.
- La suppression des dépendances PDF devenues inutiles.
- La conservation des oracles, goldens, PDF historiques et lecteurs N-1.
- La conservation temporaire de `packages/anatomy` et `packages/domain` pour R5.
- Le registre LEDGER.tsv avec 301 cas, aucun en attente.
- Les contrôles de recensement empêchant la réintroduction des anciens moteurs métier.
Ne supprime aucun autre composant encore nécessaire au pipeline anatomique.
Le reliquat local `packages/pdf/node_modules` peut être nettoyé après vérification de son contenu et de l'absence de fichiers utiles non suivis. Ce nettoyage n'est pas bloquant.
## 2. Objectif de R4.9
Réaliser les contrôles finaux de R4 sans recommencer les développements ni l'étude architecturale.
Je souhaite une vérification indépendante :
- Des contrats de lecture et d'écriture PDF.
- De la compatibilité v2/v3.
- Des archives et pièces jointes.
- Du rendu anatomique.
- Des comportements de refus contrôlés.
- De la conservation des données sur erreur.
- De la suppression effective des moteurs TypeScript remplacés.
- De la couverture de tests conservée après nettoyage.
Les oracles et goldens doivent rester inchangés.
## 3. Mémoire : point important avant la fusion
Ne considère pas la réserve Chromium de R4.6 comme résolue par le nettoyage R4.8.
Effectue le banc mémoire prévu et distingue :
1. Mémoire linéaire WASM.
2. Mémoire globale des processus navigateur.
3. Rétention des canvas, images, Blob et URL objet.
4. Allocations transitoires.
5. Mémoire durablement retenue après les exports et retours au repos.
Comparer les comportements sur plusieurs exports successifs avec un protocole reproductible.
Distinguer coût d'initialisation, pic temporaire et croissance persistante.
Si une rétention durable problématique est confirmée, présenter sa cause, sa gravité et le correctif proposé avant de clore R4.
Ne pas déclarer un problème résolu sans mesure.
## 4. Sécurité de l'import
Reprendre les réserves de `PDF_IMPORT_HARDENING §5` et les décisions BDR-058, BDR-059 et BDR-063.
Classer chaque risque :
- Corrigé avec preuve.
- Accepté temporairement avec justification.
- Bloquant avant fusion.
- À traiter avant exposition publique ou activation des uploads concernés.
Les refus de fichiers hostiles déjà validés restent acquis.
Aucune donnée utilisateur ne doit être supprimée ou modifiée silencieusement.
## 5. Recettes J1 et J2
Préparer les procédures existantes, sans les réinventer.
Je dois pouvoir tester depuis mes appareils réels, via l'accès LAN :
**J1 :**
- Imports PDF sur les navigateurs et appareils prévus.
- PDF historiques v2.
- PDF v3.
- Fichiers volumineux.
- Imports répétés.
- Comportements WebKit/Safari.
- Messages et conservation des données sur erreur.
**J2 :**
- Export PDF FR/EN.
- Vues anatomiques et détails.
- Marqueurs et surlignages.
- Pièces jointes et archives.
- Relecture et réimport.
- Comparaison avec `pnpm report:compare`.
- Tous les autres contrôles prévus dans `R4_J2.md`.
Respecter la liste exacte des appareils et navigateurs définie dans le plan R4.
Ne déclarer aucun test humain comme effectué avant mon retour.
Signaler clairement :
TEST FONCTIONNEL J1 DISPONIBLE
TEST FONCTIONNEL ET GRAPHIQUE J2 DISPONIBLE
lorsque les deux recettes sont prêtes.
## 6. Audits indépendants
Exécuter le vérificateur et l'audit de sécurité indépendants prévus pour R4.9.
Analyser toute anomalie réelle.
Pour une correction nécessaire, effectuer les tests de non-régression concernés et, selon sa portée, un nouvel audit ciblé.
Éviter les refontes sans justification.
## 7. Taille WASM
La taille actuelle de 519 795 octets gzip est acceptée pour R4.
Conserver le suivi du budget et du seuil d'alerte.
Ne pas augmenter artificiellement le budget pour masquer une régression.
La taille pourra être réévaluée au cours de R5 avec des mesures réelles.
## 8. Git et documentation
Rester sur `feature/rust-r4-pdf-core`.
Conserver les commits, pushs, audits, mémoire et documentation selon le workflow habituel.
Aucune fusion R4 dans develop avant ma validation finale.
Ne commence pas R5.
La release 0.2.0 reste en attente.
Aucune modification de production, DNS ou déploiement sur faunosteo.com.
## 9. Livraison du checkpoint
À la fin de R4.9, présente :
1. Les résultats du vérificateur indépendant.
2. Les résultats de l'audit sécurité.
3. Les résultats des tests complets.
4. Les mesures mémoire et leur interprétation.
5. L'état de chaque risque résiduel.
6. Les éventuels blocages réels à la fusion.
7. Les instructions finales des recettes J1/J2.
8. L'état Git et les derniers commits.
Si J1/J2 ne sont pas encore validées par moi, arrête-toi à ce checkpoint.
**Ne fusionne pas R4 et ne commence pas R5 sans mon accord explicite.**
## CLARIFICATIONS
Q: what counts as "the oracles and goldens"? / A: everything frozen at R4.1 (`crates/core/tests/oracles/**` but the R4.2-added `inflate.browsers.json`, `crates/core/tests/fixtures/**` but the R4.2-added `utf8-lossy.json`, `apps/app/tests/fixtures/goldens/{step6,r2,r3}/**`, `apps/app/tests/fixtures/pdf/**`), unchanged since aada799; the R4 digests `goldens/r4/pdf.*.sha256` are the writer's own bytes, re-frozen once at R4.6 (BDR-062, B2 + B4, commits 9e688b6 and d492bf7) and unchanged since; `crates/core/tests/pdf/LEDGER.tsv` is the living register (targets filled per slice), not an oracle. [gated 2026-10-20]
Q: the memory bench's five dimensions? / A: `scripts/browser/r4-memory-bench.mjs` (+ `lib/memory-probes.mjs`): (1) linear = the page's live `WebAssembly.Memory` buffers, (2) content and summed RSS from the watchdog, (3) live canvases / images / bitmaps / blobs / PDF blobs (FinalizationRegistry) and object URLs (created − revoked), Chromium heap-snapshot census, (4) the watchdog's content peak per export, (5) rest windows: settled, after the 30 s revocation, Home, Home idle. Results `scripts/browser/results/2026-10-20-r4-memory-bench.json`, reading in RUST.md §10.11. [gated 2026-10-20]
Q: where does the import security classification live? / A: `docs/development/PDF_IMPORT_HARDENING.md` §6, one row per open point of §5 and of BDR-058 / BDR-059 / BDR-063, class ∈ {fixed with proof, accepted temporarily, blocking before merge, before public exposure}. [gated 2026-10-20]
Q: J1/J2 device list? / A: plan OD-6 verbatim: the computer with Chrome and Firefox, the iPhone with Safari iOS, the low-end Android phone with its browser; every result cell stays NON TESTÉ until the owner fills it. [gated 2026-10-20]
Q: `pnpm check:all` needs Docker; may the verifier run `pnpm check` instead? / A: yes; `check:all` is run by the orchestrator and its log cited. [gated 2026-10-20]
Q: (internal, orchestrator, after verifier pass 1) the vitest binary path of criteria 2–7? / A: oracle defect: the package-local `./node_modules/.bin/vitest` of `apps/app` and `packages/core-wasm`, assertions unchanged. Criterion 4 keeps its no-feature cargo command on purpose: it is the regression proof of the default-feature build defect found by pass 1 (criterion 16). [gated 2026-10-20]
## ACCEPTANCE CRITERIA
1. PDF read and write contracts: every cargo suite of the core (reader, inflate, JSON, layout, PNG, content, serialiser, session, budget, robustness, compare) passes with every feature on.
CHECK: cd crates && (. ../scripts/rust-env.sh; cargo test -p faunosteo-core --features cli --quiet > /tmp/r49-cargo.log 2>&1) && ! grep -q "FAILED\|panicked" /tmp/r49-cargo.log && grep -c "test result: ok" /tmp/r49-cargo.log | awk '$1 >= 25 {print "CARGO_OK"}'
EXPECT: CARGO_OK
2. v2 / v3 compatibility: the 612 legacy leaves migrate through the worker's import path and the v2 PDFs round-trip (app suites `migration.leaves`, `pdf.roundtrip`, `routes.HomeRoute.messages` on the O2 / O3 / O7 / O8 corpora).
CHECK: cd apps/app && ./node_modules/.bin/vitest run tests/unit/migration.leaves.test.ts tests/unit/pdf.roundtrip.test.ts tests/unit/routes.HomeRoute.messages.test.ts > /tmp/r49-compat.log 2>&1 && grep -q "Test Files 3 passed" /tmp/r49-compat.log && echo COMPAT_OK
EXPECT: COMPAT_OK
3. Archives and attachments: the envelope suites and the N-1 reader read the R4 attachments; the cargo session suite proves the self-check (`archive.envelopes`, `n-1.reader`, `pdf.goldens`; cargo `pdf_session`, `pdf_serialize`).
CHECK: cd apps/app && ./node_modules/.bin/vitest run tests/unit/archive.envelopes.test.ts tests/unit/n-1.reader.test.ts tests/unit/pdf.goldens.test.ts > /tmp/r49-arch.log 2>&1 && grep -q "Test Files 3 passed" /tmp/r49-arch.log && cd ../../crates && (. ../scripts/rust-env.sh; cargo test -p faunosteo-core --features cli --test pdf_session --test pdf_serialize --quiet > /tmp/r49-arch2.log 2>&1) && ! grep -q "FAILED" /tmp/r49-arch2.log && echo ARCHIVE_OK
EXPECT: ARCHIVE_OK
4. Anatomical rendering: the R3 compose and layer oracles and the export's request SVGs against the frozen compose oracle (cargo `anatomy_compose`, `anatomy_layer`, `anatomy_canvas_op`; core-wasm `pdf-export.session.test.ts`).
CHECK: cd crates && (. ../scripts/rust-env.sh; cargo test -p faunosteo-core --test anatomy_compose --test anatomy_layer --test anatomy_canvas_op --quiet > /tmp/r49-anat.log 2>&1) && ! grep -q "FAILED" /tmp/r49-anat.log && cd ../packages/core-wasm && ./node_modules/.bin/vitest run tests/pdf-export.session.test.ts > /tmp/r49-anat2.log 2>&1 && grep -q "Test Files 1 passed" /tmp/r49-anat2.log && echo RENDER_OK
EXPECT: RENDER_OK
5. Controlled refusals: the hostile corpora answer closed kinds and the validated messages (cargo `pdf_robustness`, `pdf_import`, `pdf_budget`, `svg_sanitiser`; app `routes.HomeRoute.import`, `routes.HomeRoute.rescueCopy`, `routes.HomeRoute.archive`).
CHECK: cd crates && (. ../scripts/rust-env.sh; cargo test -p faunosteo-core --features cli --test pdf_robustness --test pdf_import --test pdf_budget --test svg_sanitiser --quiet > /tmp/r49-ref.log 2>&1) && ! grep -q "FAILED" /tmp/r49-ref.log && cd ../apps/app && ./node_modules/.bin/vitest run tests/unit/routes.HomeRoute.import.test.tsx tests/unit/routes.HomeRoute.rescueCopy.test.tsx tests/unit/routes.HomeRoute.archive.test.tsx > /tmp/r49-ref2.log 2>&1 && grep -q "Test Files 3 passed" /tmp/r49-ref2.log && echo REFUSALS_OK
EXPECT: REFUSALS_OK
6. Data kept on error: a refused import, a crashed or timed-out worker, a stopped engine and a failed export leave the draft, the archive and the file untouched (app `routes.coreStopped`, `state.coreFailures`, `routes.EditorRoute.export`, `routes.EditorRoute.degraded`).
CHECK: cd apps/app && ./node_modules/.bin/vitest run tests/unit/routes.coreStopped.test.tsx tests/unit/state.coreFailures.test.tsx tests/unit/routes.EditorRoute.export.test.tsx tests/unit/routes.EditorRoute.degraded.test.tsx > /tmp/r49-keep.log 2>&1 && grep -q "Test Files 4 passed" /tmp/r49-keep.log && echo KEPT_OK
EXPECT: KEPT_OK
7. The TypeScript PDF engines are gone and cannot return: no tracked file under `packages/pdf`, no `pdf-lib` / `@pdf-lib` / `@resvg` in the lockfile, no `@faunosteo/pdf` or `@faunosteo/domain` import under `apps/app/src` or `packages/core-wasm/src`, and the census suite passes.
CHECK: [ "$(git ls-files packages/pdf | wc -l)" = 0 ] && ! grep -q "pdf-lib\|@pdf-lib\|@resvg" pnpm-lock.yaml && ! grep -rq "@faunosteo/pdf\|@faunosteo/domain" apps/app/src packages/core-wasm/src && cd apps/app && ./node_modules/.bin/vitest run tests/unit/r4.census.test.ts > /tmp/r49-census.log 2>&1 && grep -q "Test Files 1 passed" /tmp/r49-census.log && echo GONE_OK
EXPECT: GONE_OK
8. Test coverage kept after the cleanup: the ledger holds 301 frozen cases, none pending, every target present (`node scripts/r4-ledger.mjs` prints the census and exits 0).
CHECK: node scripts/r4-ledger.mjs > /tmp/r49-ledger.log 2>&1 && [ "$(tail -n +2 crates/core/tests/pdf/LEDGER.tsv | wc -l)" = 301 ] && ! grep -qi "pending" crates/core/tests/pdf/LEDGER.tsv && echo LEDGER_OK
EXPECT: LEDGER_OK
9. Oracles and goldens unchanged: nothing frozen at R4.1 differs from aada799 (the two R4.2 additions excepted), the R4 digests are unchanged since d492bf7.
CHECK: [ -z "$(git diff --name-only aada799..HEAD -- crates/core/tests/oracles crates/core/tests/fixtures apps/app/tests/fixtures/goldens/step6 apps/app/tests/fixtures/goldens/r2 apps/app/tests/fixtures/goldens/r3 apps/app/tests/fixtures/pdf | grep -v 'oracles/r4/inflate.browsers.json\|fixtures/pdf/r4/utf8-lossy.json')" ] && [ -z "$(git diff --name-only d492bf7..HEAD -- apps/app/tests/fixtures/goldens/r4)" ] && echo ORACLES_OK
EXPECT: ORACLES_OK
10. The memory bench ran on the three engines for demo and L with the five dimensions and the rest windows; its reading is recorded in RUST.md §10.11.
CHECK: node -e "const r=require('./scripts/browser/results/2026-10-20-r4-memory-bench.json');const ok=r.runs.filter(x=>x.outcome==='bench');const eng=new Set(ok.map(x=>x.engine));const steps=['start','init','settled','after revoke','home','home idle'];if(eng.size!==3)throw new Error('engines '+[...eng]);for(const run of ok){for(const s of steps){const row=run.rows.find(x=>x.step===s);if(!row)throw new Error(run.engine+' '+run.report+' missing '+s);for(const k of ['linear','rssContent','peakContent','live','urlsLive'])if(row[k]===undefined)throw new Error(k)}}console.log('BENCH_OK')" && grep -q "10.11" docs/development/RUST.md && echo BENCH_DOC_OK
EXPECT: BENCH_OK and BENCH_DOC_OK
11. Import security classification: `PDF_IMPORT_HARDENING.md` §6 classifies every open point of §5 and of BDR-058 / BDR-059 / BDR-063 into the four classes, and names no hostile refusal as relaxed.
CHECK: grep -q "^## 6" docs/development/PDF_IMPORT_HARDENING.md && for c in "fixed with proof" "accepted temporarily" "blocking before merge" "before public exposure"; do grep -q "$c" docs/development/PDF_IMPORT_HARDENING.md || exit 1; done && grep -q "BDR-058" docs/development/PDF_IMPORT_HARDENING.md && grep -q "BDR-059" docs/development/PDF_IMPORT_HARDENING.md && grep -q "BDR-063" docs/development/PDF_IMPORT_HARDENING.md && echo CLASS_OK
EXPECT: CLASS_OK
12. J1 and J2 recettes re-issued on the R4.8 state with the OD-6 device list, and no human test declared done: the results templates hold no PASS or FAIL cell.
CHECK: grep -q "Chrome" docs/development/R4_J1.md && grep -q "Safari iOS" docs/development/R4_J1.md && grep -q "Android" docs/development/R4_J1.md && grep -q "report:compare" docs/development/R4_J2.md && ! grep -q "TypeScript engine (R4.6)" docs/development/R4_J1.md && [ "$(grep -c '| PASS\|| FAIL' docs/development/R4_J1_RESULTS.md docs/development/R4_J2_RESULTS.md | awk -F: '{s+=$2} END {print s}')" = 0 ] && echo RECETTE_OK
EXPECT: RECETTE_OK
13. The whole Node pipeline passes (typecheck, tests, lint, build).
CHECK: ./node_modules/.bin/pnpm check > /tmp/r49-check.log 2>&1 && echo CHECK_OK
EXPECT: CHECK_OK
14. WASM size: the shipped module stays under the 600 KB budget and the size test still pins it; the budget line was not raised.
CHECK: [ "$(gzip -9 -c packages/core-wasm/pkg/faunosteo_wasm_bg.wasm | wc -c)" -le 614400 ] && grep -q "600" packages/core-wasm/tests/size.test.ts && echo SIZE_OK
EXPECT: SIZE_OK
15. Scope: no merge into develop, no R5 file, no production change: HEAD is on `feature/rust-r4-pdf-core`, develop's tip is unchanged (66909b6 is its merge-base), and no deploy or DNS file changed.
CHECK: [ "$(git rev-parse --abbrev-ref HEAD)" = feature/rust-r4-pdf-core ] && [ "$(git merge-base develop HEAD)" = "$(git rev-parse 66909b6)" ] && [ -z "$(git diff --name-only 66909b6..HEAD -- DEPLOY.md docker/nginx.conf | grep -v DEPLOY.md)" ] && echo SCOPE_OK
EXPECT: SCOPE_OK
16. The core builds, lints and tests with no feature (the workspace run unifies the wasm crate's features and hid a gated path), and `rust:check` runs that build.
CHECK: cd crates && (. ../scripts/rust-env.sh; cargo clippy -p faunosteo-core --all-targets --locked -q -- -D warnings > /tmp/r49-nofeat.log 2>&1 && cargo test -p faunosteo-core --locked -q >> /tmp/r49-nofeat.log 2>&1) && ! grep -q "FAILED\|error\[" /tmp/r49-nofeat.log && grep -q "cargo clippy -p faunosteo-core --all-targets --locked" ../scripts/rust-check.sh && echo NOFEAT_OK
EXPECT: NOFEAT_OK
@@ -0,0 +1,107 @@
# CONTRACT — rust-r4-anomalies (R4.10)
- date: 2026-10-21 | flow: verify (R4.10 gates) | branch: feature/rust-r4-pdf-core
- status: active
- base: 4509313 (R4.9 tip); diff under review: 4509313..HEAD; run every CHECK from the repository root
- harness env: `PLAYWRIGHT_NODE_MODULES=$HOME/.local/lib/node_modules/gsd-pi/node_modules`; build in apps/app/dist (`pnpm build:preview`)
## REQUEST (verbatim — IMMUTABLE)
FAUNOSTEO — Précisions définitives J1/J2 et diagnostic des anomalies
Je complète mes résultats de recette R4.
Navigateurs réellement utilisés
- Chrome sur ordinateur.
- Firefox sur ordinateur.
- Brave sur ordinateur.
- Android avec son navigateur.
Safari sur iPhone n'a pas encore été testé.
La répartition exacte des 27 contrôles par navigateur n'a pas été fournie ; ne marque pas automatiquement chaque cellule PASS.
Anomalie A — J1.7, import hors ligne
FAIL confirmé sur Brave et Firefox.
Surface concernée : build de production local, port 4173, avec CSP de production.
Scénario : une fois hors ligne, cliquer sur « Importer » n'ouvre pas le sélecteur de fichiers et le navigateur devient impraticable.
Résultat attendu : le parcours prévu par J1.7 doit permettre d'importer un PDF de référence hors ligne après chargement préalable de l'application et du moteur.
Diagnostique précisément :
- Le déclenchement du sélecteur de fichiers.
- La navigation dans l'application après perte de connexion.
- Les éventuelles attentes réseau bloquantes.
- Le chargement et le cache du worker et du module WASM.
- Les erreurs JavaScript et les éventuelles restrictions CSP.
- Les différences Brave/Firefox et les conditions exactes de reproduction.
Distingue un défaut applicatif d'une limitation réelle et documentée du navigateur. Ne conclus pas à une cause sans preuve.
Corrige le problème si le diagnostic confirme un défaut de Faunosteo.
Anomalie B — J2.3, export sans logos
FAIL confirmé pour le comportement observé.
Après import de "1-reference/r3-demo.fr.nologos.pdf", le PDF exporté affiche encore des logos graphiques dans l'en-tête et le pied de page.
La procédure J2.3 prévoit un nom de site et des crédits sous forme de texte, sans ces logos.
Vérifie notamment :
- Le contenu exact du PDF de référence.
- Le branding effectivement stocké dans l'archive.
- Le branding ajouté par l'application.
- La réutilisation éventuelle de données d'une session précédente.
- Les règles historiques de fallback sans logos.
- Les oracles PDF et les contrats du cœur Rust.
Ne modifie ni les goldens, ni les règles métier, ni l'attendu de recette simplement pour faire passer le test.
Présente-moi le diagnostic si une décision de comportement produit est nécessaire.
Résultats à consigner
J1.1 à J1.6 : PASS déclarés.
J1.7 : FAIL sur Brave et Firefox.
J1.8 à J1.13 : PASS déclarés, J1.12 en quelques secondes sans mesure précise.
J2.1 et J2.2 : PASS déclarés.
J2.3 : FAIL confirmé, logos graphiques en en-tête et pied de page.
J2.4 à J2.14 : PASS déclarés.
Conserve NON TESTÉ pour Safari iOS et pour toute combinaison appareil/test non explicitement confirmée.
Suite
Réalise un diagnostic ciblé, puis les corrections nécessaires avec tests de non-régression et audit adapté.
Si les modifications sont limitées, prépare une mini-recette permettant de revalider uniquement les parcours touchés ainsi que leurs dépendances fonctionnelles.
Ne fusionne pas R4 dans develop.
Ne commence pas R5.
Ne touche ni à la release 0.2.0 ni à faunosteo.com.
Présente-moi tes conclusions et les instructions de revalidation avant toute clôture définitive de R4.
## CRITERIA
1. Results recorded as declared, nothing inferred: in `docs/development/R4_J1_RESULTS.md` J1.7 is FAIL in the Firefox and Brave cells and in the declared column; every other J1 row is `PASS déclaré` in the declared column only (J1.12 with « quelques secondes », no measure); in `R4_J2_RESULTS.md` J2.3 is FAIL and J2.1-J2.2, J2.4-J2.14 `PASS déclaré` in the declared column; every device cell other than J1.7 Firefox / Brave is `NON TESTÉ` (or `not applicable` as before for J2.11 / J2.14 phones); Safari iOS NON TESTÉ everywhere.
CHECK: `git diff 4509313 -- docs/development/R4_J1_RESULTS.md docs/development/R4_J2_RESULTS.md`
2. Anomaly A, cause shown with proof: `scripts/browser/serve.mjs` sends exactly `docker/nginx.conf`'s Cache-Control values (`no-store, no-cache, must-revalidate` on /env.js, `public, max-age=31536000, immutable` on /assets/ files) and nothing else in its behaviour changes (bind address checks, CSP, mounts, 404 and SPA fallback, report-uri).
CHECK: `git diff 4509313 -- scripts/browser/serve.mjs`; `grep -n Cache-Control docker/nginx.conf`
3. Regression harness: `scripts/browser/r4-offline-import.mjs` runs J1.7 (online import, network cut by Playwright offline mode and by killing the server, « Accueil », pick through « Remplacer ») on the three engines, checks the headers, exits 1 when a Chromium or Firefox row does not open the editor or any row has a page error or no answer; the committed results file shows 6 runs with empty `problems`.
CHECK: `PLAYWRIGHT_NODE_MODULES=$HOME/.local/lib/node_modules/gsd-pi/node_modules node scripts/browser/r4-offline-import.mjs --out /tmp/r4-offline-verify.json; echo exit=$?` → exit=0
4. Anomaly A, unproven part stated as unproven: RUST.md §10.12 does not claim the cause of the frozen file picker; it states it was not reproduced and gives a discriminating step; the WebKit headless limit is stated as such, Safari iOS unknown.
CHECK: `sed -n '/### 10.12/,$p' docs/development/RUST.md`
5. Anomaly B diagnosis with no behaviour change: no file under `apps/`, `crates/`, `packages/`, `supabase/`, goldens or oracles changed; the §10.12 claims hold: the nologos reference's archive has the four logo slots null, `apps/app/src/pdf/export.ts` passes `loadBranding()` (bundled logos) at HEAD and at 66909b6, the archived branding reaches the writer only via `export_from_envelope`; an owner decision is requested; `R4_J2.md` J2.3 expected result unchanged.
CHECK: `git diff --stat 4509313 -- apps crates packages supabase docs/development/R4_J2.md docs/development/R4_J1.md` → empty; `git show 66909b6:apps/app/src/pdf/export.ts | grep -n loadBranding`; `grep -rn "export_from_envelope\|exportFromEnvelope" apps crates/core/src | head`
6. Mini-recette `docs/development/R4_MINI_RECETTE.md` re-runs only J1.7 and its dependencies (J1.1, J1.13), with the discriminating step, setup (build, UFW 4173 open then deleted, serve), what to report; J2.3 explicitly waits for the decision.
CHECK: `cat docs/development/R4_MINI_RECETTE.md`
7. Scope and style: no merge, develop unchanged at 66909b6; no em-dash in the new or changed user-facing docs; prettier clean on the changed scripts.
CHECK: `git rev-parse --short develop`; `git diff 4509313 -- docs | grep '^+' | grep -c '—'` → 0; `node_modules/.bin/prettier --check scripts/browser/serve.mjs scripts/browser/r4-offline-import.mjs`
@@ -0,0 +1,56 @@
# Contract: R4.10 owner decisions (J2.3 option 1, gitleaks marker, R4.8 trace, ZenQuality logo) and the J1.7 rectification
Base: 1814a8d on `feature/rust-r4-pdf-core`. Date: 2026-10-21.
## REQUEST (verbatim, owner, two messages)
Message 1, « Décisions R4.10 et préparation de la mini-recette »:
- J2.3: « Je choisis définitivement l'option 1. Conserver le comportement historique : les nouveaux exports effectués depuis l'éditeur utilisent le branding actuel de Faunosteo, même lorsque le document importé provient d'une archive sans logos. […] Corrige uniquement l'attendu incorrect de J2.3 et les documents de recette associés. Ne modifie ni le comportement du moteur, ni les goldens, ni les oracles pour ce point. »
- J1.7: « J'accepte le correctif des en-têtes de cache du serveur de recette et les contrôles de sécurité associés. […] Ne considère pas J1.7 comme définitivement validé. […] Ne suppose pas que la piste du partage réseau est confirmée. Le test Ctrl+O est un indice de diagnostic, pas une preuve suffisante à lui seul. Préserve les résultats actuels des tests automatisés. »
- Safari iOS: « La validation Safari iOS réelle reste en attente. […] Un simulateur iPhone ne remplacera pas les mesures de mémoire sur matériel réel. »
- Marqueurs: « Je réitère mon autorisation d'ajouter le marqueur exact `[gated 2026-10-18]` à l'exception strictement ciblée de `.gitleaks.toml`. […] Applique-la sans élargir la portée de l'exception. Vérifie également que l'autorisation des 21 suppressions de tests de R4.8 est correctement tracée, sans créer de nouvelle suppression. »
- ZenQuality: « Vérifie son impact réel sur l'application et sur les exports PDF. Précise si cette ressource est effectivement absente du rendu en build de production et pourquoi les recettes précédentes n'ont pas détecté ce problème. Si un défaut est confirmé, présente un correctif ciblé. Privilégie une ressource locale embarquée, si possible et autorisée, plutôt qu'un assouplissement injustifié de la CSP. Ne modifie pas le branding produit sans décision préalable. »
- Livraison: « Mets à jour les documents correspondant à mes décisions. Exécute les vérifications ciblées nécessaires et conserve les audits précédents. Ne transforme pas les tests headless en résultats humains. Attends mon retour sur M1 à M5 et Safari avant de conclure R4. Reste sur feature/rust-r4-pdf-core. Aucune fusion dans develop. Ne commence pas R5. Ne publie pas la release 0.2.0. Ne déploie rien sur faunosteo.com. »
Message 2, « Rectification définitive J1.7 / M1 / M2 »:
« Lorsque la connexion réseau du système est coupée, le sélecteur de fichiers met environ une minute à s'ouvrir, aussi bien depuis Ctrl+O dans un onglet vide que depuis le bouton « Importer » de Faunosteo. Une fois le sélecteur ouvert, les imports hors ligne fonctionnent normalement. Résultats corrigés : M1 : PASS avec délai d'environ 60 secondes. M2 : PASS avec délai d'environ 60 secondes. J1.7 : PASS fonctionnel, avec réserve de performance concernant l'ouverture du sélecteur. M3 : NON TESTÉ. M4/M5 : NON TESTÉ dans la mini-recette ; les validations J1 antérieures restent déclarées. Le comportement est constaté hors de Faunosteo également. […] Conserve la correction des en-têtes Cache-Control […]. Mets à jour les résultats et le suivi R4.10, sans présenter l'origine exacte des 60 secondes comme prouvée. Ne lance pas de nouvelle modification applicative pour ce symptôme sans preuve d'un défaut de Faunosteo. Ma décision J2.3 reste l'option 1 […]. Les tests sur Safari iOS restent à effectuer. Aucune fusion R4 dans develop, aucun démarrage R5, aucune modification de production sans mon autorisation. »
## FILE SCOPE
Range: `git diff 1814a8d` (the base above) to the branch head. Every path
the range touches is listed here; anything else is out of scope.
- `docs/development/R4_J1.md` (Safari iOS rule), `R4_J2.md` (J2.3 expected result, Safari iOS rule), `R4_J2_RESULTS.md`, `R4_J1_RESULTS.md`, `R4_MINI_RECETTE.md`, `RUST.md` §10.11 (count, marker wording), §10.12 (decisions, C paragraph, D owner decisions), `CHANGELOG.md`, `CLAUDE.md` (map line)
- `.gitleaks.toml` (the one description string)
- `apps/app/src/components/brand/Footer.tsx`, `apps/app/src/assets/brand/zenquality-logo-horizontal.png` (new), `apps/app/tests/unit/components.Footer.test.tsx` (new, protocol-relative regex 1877c4b)
- `scripts/browser/r4-app-csp.mjs`, `scripts/browser/results/2026-10-21-r4-{csp,offline-import}.json` (new)
- `scripts/browser/lib/app-build.mjs` (results name the build relative to the repository), and the redaction of absolute local paths (the `distDir` line only) in `scripts/browser/results/2026-10-19-{r4-export,r4-export-series,r4-export-series-chromium-12,ts-export,ts-export-series-chromium}.json`, `2026-10-20-{r4-memory-bench,r4-memory-bench-chromium-L16-export,r4-memory-bench-chromium-L16-raster,r4-offline-import}.json`; `scripts/browser/README.md` (one example path); `docs/history/superpowers/plans/2026-05-23-responsive-mobile.md` (paths only)
- `.claude/tasks/contracts/2026-10-21-rust-r4-decisions-1500.md` (this contract), and the redaction of absolute local paths in `.claude/tasks/contracts/2026-10-11-step-06-phase-{0-freeze,1-domain,2-compose,3-engine,4-app}.md`, `2026-10-13-rust-r0-native-verify.md`, `2026-10-13-rust-r0-verify.md`, `2026-10-21-rust-r4-anomalies-1000.md` (`/home/<user>/` → `$HOME/`, session scratchpad → `<session scratchpad>`)
- `.claude/tasks/TODO.md`, `.claude/memory/decisions.md` (BDR-066), `.claude/memory/learnings.md` (LRN-067, LRN-068), `.claude/memory/journal.md`
Out of scope: `crates/**`, `packages/**`, `apps/app/src/pdf/**`, the goldens, the oracles, the R4 digests, `crates/core/tests/pdf/LEDGER.tsv` (generated byte for byte by `scripts/r4-ledger.mjs`), DEPLOY.md's CSP, `docker/nginx.conf`, any deletion.
## ACCEPTANCE CRITERIA
1. J2.3: `R4_J2.md` expects the application's current branding (the four logos of J2.1) on the export of `r3-demo.fr.nologos.pdf`; `R4_J2_RESULTS.md` records the owner's observation as acceptable under that rule, subject to the logos being the current branding, with the original FAIL declaration kept in the note; no file under `crates/`, `packages/`, `apps/app/src/pdf/`, `apps/app/tests/fixtures/goldens/`, `crates/core/tests/oracles/` changed (`git diff --stat 1814a8d`).
2. `.gitleaks.toml`: the allowlist description starts with `[gated 2026-10-18]`; `paths` unchanged, no other key added (`git diff 1814a8d -- .gitleaks.toml` is one line changed).
3. R4.8 trace: `git log --diff-filter=D --name-only --format= 66909b6..HEAD -- '*.test.ts' '*.test.tsx'` lists 23 files, all from 0dc1ba2; RUST.md §10.11 states 23 (and that the verifier counted 21), the ledger traces 22 of them case by case (`awk -F'\t' 'NR>1{print $1}' crates/core/tests/pdf/LEDGER.tsv | sort -u` contains every deleted path but `packages/core-wasm/tests/pdf-export.ts-engine.test.ts`, which §10.10 names); no file deleted by the diff from 1814a8d.
4. J1.7 recorded as the owner rectified it: `R4_J1_RESULTS.md` J1.7 cells for Firefox and Brave read PASS with the picker-delay note, the declared column a PASS with a performance reserve, the note keeps the first FAIL and says the cause of the delay is not established; `R4_MINI_RECETTE.md` §3 holds M1 PASS ~60 s, M2 PASS ~60 s, M3 NON TESTÉ, M4/M5 NON TESTÉ, M6 NON TESTÉ; no application change for the symptom (criterion 1's path list plus `apps/app/src/app/routes/HomeRoute.tsx` and `apps/app/src/core/**` unchanged).
5. ZenQuality: `Footer.tsx` has no `http` image source (`grep -n "src=" apps/app/src/components/brand/Footer.tsx`), imports `@/assets/brand/zenquality-logo-horizontal.png?url`; the file is a valid PNG 1024 × 237 whose sha256 is `8625f6b16022494ab376d94d86fa85cd54aa3d5280e3ceb27531ff33538c0f85`; `components.Footer.test.tsx` passes (`cd apps/app && ./node_modules/.bin/vitest run tests/unit/components.Footer.test.tsx`) and fails when `src={zenQualityUrl}` is replaced by the old URL (prove by a temporary edit, reverted); `DEPLOY.md` unchanged; `apps/app/src/pdf/branding.ts` unchanged.
6. CSP proof: `scripts/browser/r4-app-csp.mjs` holds no `KNOWN_IMAGE_HOST` and treats every document violation, CSP console message and report as a problem; `scripts/browser/results/2026-10-21-r4-csp.json` has 12 runs, every `problems` empty, every `documentViolations` and `consoleCsp` empty; `2026-10-21-r4-offline-import.json` has 6 runs with empty `problems`.
7. The app suite, typecheck and lint green: `pnpm typecheck`, `pnpm lint`, `cd apps/app && ./node_modules/.bin/vitest run` (59 files, 429 cases); the headless results are never written into a device cell of the results grids (every device cell of `R4_J1_RESULTS.md` and `R4_J2_RESULTS.md` other than J1.7 Firefox and Brave stays `NON TESTÉ` or `not applicable`).
8. Docs: RUST.md §10.12 carries the J2.3 decision, the J1.7 rectification (cause not claimed) and the C paragraph (impact, where the policy lives, the live site's header, why the recettes did not report it, the fix and its proofs); CHANGELOG Unreleased has the footer entry; CLAUDE.md map line names the footer logo.
9. Owner decisions of 2026-10-21 recorded: RUST.md §10.12 holds a « D. Owner decisions recorded » paragraph (J1.7 PASS with the reserve, M3 complementary and not blocking, J2.3 option 1 final, the logo and the CSP proof validated, the marker valid with its writing delegable, the 23 deletions with no further one, Safari iOS on the real iPhone only); §10.11 no longer says « only the owner adds the marker » nor « the owner's own `[gated]` line » and calls 21 a census error (`grep -c "only the owner adds the marker\|owner's own \`\[gated\]\`" docs/development/RUST.md` = 0; `grep -c "census" docs/development/RUST.md` ≥ 1); BDR-066 in `.claude/memory/decisions.md`.
10. Recette docs: `R4_MINI_RECETTE.md` names M3 a complementary control, not blocking, and leaves it NON TESTÉ; `R4_J1.md`, `R4_J2.md`, `R4_J1_RESULTS.md`, `R4_J2_RESULTS.md` state that Safari iOS stays NON TESTÉ until the real iPhone and that a simulator is never a memory proof (`grep -ci simulator` ≥ 1 in each); every iPhone cell of both results grids reads `NON TESTÉ` or `not applicable` (criterion 7).
11. Redaction: `git grep -n -I -E "/home/[a-z][a-z0-9_-]*/|-home-[a-z][a-z0-9_-]*-" | grep -v "/home/deploy/"` prints nothing (any home directory of any user, in path or in the session-folder spelling; the VPS service account `/home/deploy/` of the DEPLOY.md runbook is the one legitimate home path); the modified results JSON change the `distDir` line only (`git diff 1814a8d --diff-filter=M -- scripts/browser/results | grep -E '^[-+] ' | grep -vc distDir` = 0; the two 2026-10-21 files are new and covered by criterion 6); `scripts/browser/lib/app-build.mjs` reports `distDir` relative to the repository (`node -e "import('./scripts/browser/lib/app-build.mjs').then(m=>console.log(m.checkBuild().distDir))"` prints `apps/app/dist` when a build is present).
12. `pnpm check:all` exits 0 on the final code state (run by the executor, log path and tail in its report; re-run by the verifier only if needed).
## CLARIFICATIONS
Q: apply the fix or only present it? / A: the owner asked for a targeted fix with a bundled resource and no branding change; the bundled file is the exact remote file, so the picture does not change; applied on the branch, reversible by the owner. [gated 2026-10-21, owner's message 1]
Q: the owner's message 1 says « 21 suppressions »; which count is authorized? / A: 23, all from 0dc1ba2; 21 was a census error, confirmed by the owner on 2026-10-21; the quote in REQUEST stays verbatim. [gated 2026-10-21, owner's verdict]
Q: scope declaration / A: pass 1 of the verifier found the contract file itself missing from FILE SCOPE (formal gap, 8/8 MET); FILE SCOPE now lists this file, the memory files by name and the redactions; no criterion was removed.
@@ -0,0 +1,50 @@
# Contract: R4.11 dependency maintenance before the R4 merge
Base: 8943bf3 on `feature/rust-r4-pdf-core`. Date: 2026-10-21. Range: `8943bf3..HEAD`.
## REQUEST (verbatim, owner, « Dernière maintenance de sécurité avant clôture R4 »)
« Trois dépendances nécessitent une vérification et, si les versions affectées sont présentes, une mise à jour : rustls-webpki : RUSTSEC-2026-0382. webpki-roots : RUSTSEC-2026-0381. react-router : avis concernant les versions antérieures à 7.18.2, selon les plages affectées. […] Ces numéros ne remplacent pas la vérification des contraintes réelles du monorepo et des dépendances transitives. »
« Avant modification, établir : les versions actuellement résolues, les chemins de dépendances qui les introduisent, les composants effectivement concernés, l'exposition réelle de Faunosteo aux vulnérabilités, les versions corrigées disponibles et compatibles, les éventuels changements d'API ou de comportement attendus. Pour react-router, vérifier le mode utilisé par l'application, les appels Link, useNavigate et redirect, ainsi que le traitement des destinations provenant de données non fiables. Pour Rust, vérifier notamment la chaîne TLS du worker, les certificats de confiance et les compatibilités avec rustls. »
« Effectuer les mises à jour minimales raisonnables, avec commits séparés et traçables. Préserver les comportements métier. Ne pas changer l'architecture React ou Rust simplement pour réaliser une montée de version. Ne pas introduire d'exclusion de sécurité pour masquer les alertes. Si une mise à jour nécessite une migration importante ou présente un risque de régression significatif, arrête-toi et présente-moi les alternatives avant de continuer. »
« Après mise à jour : pnpm check:all. Audit npm/pnpm des dépendances de production. Cargo deny et contrôle des avis RustSec. Tests des parcours React Router concernés. Tests d'authentification, navigation, redirections et liens pertinents. Tests TLS du worker avec validation effective des certificats, dans la mesure où l'environnement le permet. Construction des images et tests sandbox. Vérification que les oracles PDF et les goldens restent inchangés. Audit de sécurité indépendant ciblé sur les mises à jour. Ne pas qualifier les vulnérabilités de corrigées uniquement parce que la compilation passe. »
« Présenter un tableau avec chaque avis, l'ancienne version, la nouvelle version, le résultat de l'audit et les risques résiduels. Si toutes les mises à jour sont compatibles et les grilles vertes, considérer la maintenance prête, mais attends toujours mon signal final. »
« M3 reste facultatif et NON TESTÉ. Safari iOS physique reste NON TESTÉ et nécessaire avant la fusion. Ne pas modifier la règle J2.3 ni relancer le diagnostic J1.7 sans nouveau défaut prouvé. Conserver les corrections Cache-Control et CSP. Si le critère de vérification contient inutilement un nom d'utilisateur local, le remplacer par une règle générique équivalente sans réduire sa couverture. Rester sur feature/rust-r4-pdf-core. Aucune fusion dans develop sans mon autorisation. Ne commence pas R5. Ne publie pas la release 0.2.0. Ne déploie rien sur faunosteo.com. »
## FILE SCOPE
Every path the range touches is listed here; anything else is out of scope.
- `Cargo.lock` (two crate bumps, then rcgen's tree), `crates/worker/Cargo.toml` (`[dev-dependencies]` only), `crates/worker/tests/tls.rs` (new)
- `apps/app/package.json` (`react-router-dom` range), `pnpm-lock.yaml` (react-router, react-router-dom)
- `docs/development/RUST.md` §10.13 (new), `CHANGELOG.md` (Unreleased, Fixed 2026-10-21)
- `.claude/tasks/contracts/2026-10-21-rust-r4-decisions-1500.md` (criterion 11 wording), `.claude/tasks/contracts/2026-10-21-rust-r4-maintenance-1700.md` (this contract)
- `.claude/tasks/TODO.md`, `.claude/memory/{journal,learnings,decisions}.md`
Out of scope: every file under `crates/worker/src`, `crates/core`, `crates/wasm`, `apps/app/src`, `packages/`, `apps/app/tests/fixtures`, `crates/core/tests`, `docker/`, `DEPLOY.md`, `.gitleaks.toml`, `deny.toml`, the recette documents and results; any deletion.
## ACCEPTANCE CRITERIA
1. Rust versions: `grep -A1 '^name = "rustls-webpki"' Cargo.lock` shows `0.103.16`, `webpki-roots` `1.0.10`; `cargo tree -i rustls-webpki -e normal` and `cargo tree -i webpki-roots -e normal` reach the workspace only through `ureq` → `faunosteo-worker`; `cargo deny check advisories` exits 0 (it exited 1 on 8943bf3 with the two ids); `deny.toml` unchanged (`git diff 8943bf3 -- deny.toml` empty) and its `ignore = []` still empty.
2. Node versions: `apps/app/package.json` has `"react-router-dom": "^7.18.4"`; `pnpm list -r --depth 2 react-router-dom` resolves `react-router-dom 7.18.4` and `react-router 7.18.4`; `pnpm audit --prod` prints `No known vulnerabilities found`; the lockfile diff from 8943bf3 touches only the react-router and react-router-dom entries (`git diff 8943bf3 -- pnpm-lock.yaml | grep -E '^[-+] ' | grep -vcE 'react-router|specifier: \^7|version: 7\.1[58]|resolution: \{integrity: sha512-'` = 0).
3. One commit per update: `git log --oneline 8943bf3..HEAD -- Cargo.lock` shows the webpki commit (7a7b71c) and the test commit (a604c07) and no other lockfile change; `git log --oneline 8943bf3..HEAD -- pnpm-lock.yaml apps/app/package.json` shows the react-router commit (c9dab63) alone.
4. No application or worker source change: `git diff --stat 8943bf3 -- apps/app/src crates/worker/src crates/core crates/wasm packages docker DEPLOY.md .gitleaks.toml` is empty; no deletion in the range (`git diff --diff-filter=D --name-only 8943bf3` empty); no new suppression (`git diff 8943bf3 | grep -E '^\+.*(nosemgrep|nosec|eslint-disable|allow\(|gitleaks:allow|ignore = \[)'` prints nothing but the test file's `#![allow(clippy::unwrap_used, clippy::expect_used)]`, the convention of every worker test file).
5. TLS proof: `cargo test -p faunosteo-worker --test tls` passes; the test builds a `HttpBackend` from `https://127.0.0.1:<port>` against an in-process rustls server with a self-signed certificate, expects `BackendError::Network` whose message contains `certificate`, asserts the service key string is absent from the message, and asserts the server saw the connection dropped (no request). Negative proof, run by the orchestrator (a verifier edits no tree): with `.tls_config(ureq::tls::TlsConfig::builder().disable_verification(true).build())` added to the agent builder in `crates/worker/src/http.rs` (temporary edit, restored with `git checkout --`), the test failed at tls.rs `expected a network error, got Ok([])` (orchestrator log quoted in the verifier's brief); the verifier checks by reading that the test panics on any `Ok` and that the server answers `[]` after a completed handshake.
6. Dev-dependencies: `crates/worker/Cargo.toml` adds `rustls` (default-features false, `ring`, `std`, `tls12`) and `rcgen` (default-features false, `ring`) under `[dev-dependencies]` only; `cargo tree -p faunosteo-worker -e normal` (no dev edges) lists neither; `cargo deny check` (all four checks) exits 0.
7. Suites: `pnpm rust:check` exits 0; `cd apps/app && ./node_modules/.bin/vitest run` → 59 files, 429 cases (includes `guards.RequireAuth`, `routes.LoginRoute`, `routes.SignupRoute`, `routes.HomeRoute.*`, `routes.EditorRoute.*`, `auth.validation` with `safeNextPath`); `pnpm typecheck` and `pnpm lint` exit 0; `git status --short` empty afterwards (the wasm module may need `pnpm wasm:build` first: the lockfile is a BUILD_STAMP input; the shipped bytes stay 1,535,289 raw).
8. `pnpm check:all` exit 0 on the final code state (orchestrator log `<session scratchpad>/checkall-r411.log`, path given in the verifier's brief, never in a tracked file; ending `== all checks passed`; the musl test stage runs `tests/tls.rs` too, `grep -n "tests/tls.rs" <log>` finds it in the Docker stage with `1 passed`); read the log, do not re-run.
9. Goldens and oracles unchanged: `git diff --stat 8943bf3 -- apps/app/tests/fixtures crates/core/tests` empty.
10. Docs: RUST.md §10.13 holds the table (advisory, component and path, before, after, audit, residual) for the five advisories, the exposure analysis (BrowserRouter SPA, `safeNextPath`, no server), the TLS proof with its negative run and its honest limit, the dev-dependency note, and the checks; CHANGELOG Unreleased has the dependency line.
11. Criterion 11 of the previous contract no longer names a local username: `grep -c "bchano" .claude/tasks/contracts/2026-10-21-rust-r4-decisions-1500.md` = 0, and its generic rule `git grep -n -I -E "/home/[a-z][a-z0-9_-]*/|-home-[a-z][a-z0-9_-]*-" | grep -v "/home/deploy/"` still prints nothing.
12. Recette state untouched: `git diff --stat 8943bf3 -- docs/development/R4_J1.md docs/development/R4_J2.md docs/development/R4_J1_RESULTS.md docs/development/R4_J2_RESULTS.md docs/development/R4_MINI_RECETTE.md` empty (J2.3 rule, J1.7, M3 and Safari iOS cells as the owner left them).
## CLARIFICATIONS
Q: 7.18.2 (the owner's minimum) or 7.18.4 (latest 7.x)? / A: 7.18.4: the owner allows « une version stable supérieure compatible »; patch-level changelog, published 2026-09-15, React 19 and Node 24 compatible. [gated 2026-10-21, owner's §1]
Q: a TLS test needs dev-dependencies (rcgen); allowed? / A: the owner asked for TLS tests « dans la mesure où l'environnement le permet »; dev-only, from the rustls project, named in §10.13; no runtime dependency changes. [gated 2026-10-21, owner's §4]
Q: criterion 4 quotes the suppression-grep pattern in its own text; does the floor count it? / A: no: it is the oracle's command, not a suppression in code; waived for this contract file only. [gated 2026-10-21, oracle wording]
@@ -0,0 +1,42 @@
# Contract: R4.12 pre-merge fixes D1 / D3 / D6
Base: ff122d1 on `feature/rust-r4-pdf-core` (« chore(memory): Context7 documentation review report, TODO R4.11 checkpoint »). Range: `ff122d1..HEAD`; `<base>` below is ff122d1. Date: 2026-10-21.
## REQUEST (verbatim, owner, « Validation R4.11 et derniers ajustements avant recette Safari »)
« D1 — Distroless Debian 13 : autorisé maintenant. Migrer l'image de base du worker de static-debian12 vers la variante Debian 13 officiellement maintenue. Vérifier la provenance et la compatibilité de l'image avant modification. Conserver l'exécution non-root, les protections sandbox, les contraintes de ressources et le comportement HTTPS. Valider avec worker:test, worker:image, les tests de sandbox et les vérifications pertinentes du worker réel. Ne pas modifier l'architecture ni assouplir les restrictions de sécurité. »
« D3 — safeNextPath : correction obligatoire maintenant. Corriger la faille logique permettant à une valeur telle que /..//evil.com d'aboutir à //evil.com. La fonction doit garantir que sa valeur retournée est un chemin interne sûr, y compris après normalisation. Ajouter des tests ciblant les segments de parcours, les doubles slashs, antislashs, schémas externes, encodages pertinents et destinations déjà valides. Ne pas casser les redirections internes légitimes. Vérifier les consommateurs et le comportement réel de React Router sans supposer que sa protection actuelle dispense de sécuriser notre propre contrat. »
« D6 — DEPLOY.md : correction autorisée maintenant. Mettre à jour la syntaxe Nginx obsolète vers http2 on; dans le runbook. Préserver les autres directives et le comportement documenté. Ne modifier aucun serveur de production. »
« D2 […] ne réalise pas maintenant un remplacement global des 13 fichiers. […] D4 — Ménages de configuration : différés. […] D5 — MotionConfig […] Ne l'implémente pas dans ce dernier lot R4. »
« Séparer clairement les commits des corrections D1, D3 et D6. Exécuter pnpm check:all sur l'état final, les audits de sécurité, les tests du worker et les tests ciblés de navigation. Conserver les oracles et goldens PDF inchangés. Faire vérifier indépendamment les corrections réalisées. Signaler toute régression ou incompatibilité réelle plutôt que d'ajouter une exception. Ne pas modifier le comportement du moteur PDF en l'absence de défaut démontré. […] Après les trois corrections ciblées et leurs vérifications, arrête-toi au checkpoint de pré-fusion. »
## FILE SCOPE
- D3: `apps/app/src/auth/redirects.ts`, `apps/app/tests/unit/auth.validation.test.ts`, `apps/app/tests/unit/routes.LoginRoute.test.tsx`
- D1: `crates/worker/Dockerfile` (the runtime `FROM` line and its comment)
- D6: `DEPLOY.md` (the host nginx `listen 443` lines of Option A)
- Docs: `docs/development/RUST.md` §10.14 (new), `CHANGELOG.md` (Unreleased, Fixed 2026-10-21)
- `.claude/tasks/contracts/2026-10-21-rust-r4-premerge-1830.md` (this contract), `.claude/tasks/TODO.md`, `.claude/memory/{journal,learnings,decisions}.md`
Out of scope: every other file, in particular the 13 files of D2 (`outline-none` stays), `MotionConfig`, the D4 files (`apps/app/vitest.config.ts`, `apps/app/tests/setup.ts`, `apps/app/eslint.config.js`, `ui/{Input,Select,Textarea}.tsx`, `state/authStore.ts`), `crates/**/src`, `crates/core/tests`, `apps/app/tests/fixtures`, `packages/**`, package manifests and lockfiles; any deletion.
## ACCEPTANCE CRITERIA
1. Three code/doc commits, one per decision: `git log --oneline <base>..HEAD -- apps/app/src/auth/redirects.ts` = one commit (D3); `-- crates/worker/Dockerfile` = one other commit (D1); `-- DEPLOY.md` = one third commit (D6); none of the three commits touches another decision's files (`git show --stat <sha>`).
2. D3 contract: for every input in `['/..//evil.test','/.//evil.test','/a/..//evil.test','/a/b/../..//evil.test','/..\\\\evil.test','/x/..\\/evil.test','/%2e%2e//evil.test','/%2E%2E//evil.test','/.%2e//evil.test','/a/%2e%2e//evil.test','/.\t.//evil.test','///evil.test','//evil.test','/\\evil.test','https://evil.test/','javascript:alert(1)','']` the returned value does not start with `//` and resolves to the same origin as a probe origin (check by a node one-liner importing the compiled logic, or read through the test file's cases); legitimate paths unchanged: `/app/account?tab=x#s`, `/editor`, `/app//account`, `/%2F%2Fevil.test` (literal), `/app/account?next=//evil.test`; `/app/../app/account` → `/app/account`.
3. D3 tests: `apps/app/tests/unit/auth.validation.test.ts` has the four new `safeNextPath` cases (dot segments, schemes and escapes, encoded and legitimate paths, idempotence) and `routes.LoginRoute.test.tsx` the `next=/..//evil.test/app/account` → dashboard case; they pass (`cd apps/app && ./node_modules/.bin/vitest run tests/unit/auth.validation.test.ts tests/unit/routes.LoginRoute.test.tsx tests/unit/guards.RequireAuth.test.tsx`); at least the dot-segment case and the LoginRoute case fail on the pre-fix function (`git show <base>:apps/app/src/auth/redirects.ts`), proven by the orchestrator's run: « × safeNextPath > refuses dot segments that normalise into a protocol-relative path », « × safeNextPath > keeps encoded slashes literal and legitimate internal paths unchanged », « × LoginRoute > lands on the dashboard when next normalises into another host (R4.12) », « Tests 3 failed | 16 passed (19) »; the verifier checks by reading that the old function returns `//evil.test` for `/..//evil.test` (node one-liner on `new URL('/..//evil.test','http://next.invalid').pathname`).
4. D1: `crates/worker/Dockerfile` runtime stage is `FROM gcr.io/distroless/static-debian13:nonroot AS runtime`, still followed by `COPY --from=build /faunosteo-worker /faunosteo-worker`, `USER nonroot`, `ENTRYPOINT ["/faunosteo-worker"]`, `CMD ["run", "--check"]`; the build and test stages unchanged (`git diff <base> -- crates/worker/Dockerfile` touches only the runtime `FROM` and two comment lines); `docker image inspect faunosteo_worker:dev` shows user `nonroot`, entrypoint `/faunosteo-worker`, cmd `run --check`; `docker run --rm --network none --entrypoint /bin/sh faunosteo_worker:dev -c true` fails (no shell).
5. D1 proofs in the check:all log (`<session scratchpad>/checkall-r412.log`, path in the verifier's brief): `gcr.io/distroless/static-debian13:nonroot@sha256:d62067879de890a1def9da0e7766b7d20810a5e5555cef8506b752437d7a3e88` resolved for the runtime, the worker test stage `test result: ok` lines including `tests/tls.rs`, the seccomp derivation, the runtime `run --check` output; and `pnpm e2e:avatar` 5/5 on this image (`<session scratchpad>/e2e-d1.log`). Read the logs, do not re-run Docker builds or the stack.
6. D6: `DEPLOY.md` Option A server block reads `listen 443 ssl;`, `listen [::]:443 ssl;`, `http2 on;` with a comment naming nginx >= 1.25.1, the 1.24 form (`listen 443 ssl http2;`) and `nginx -v`; no other DEPLOY.md line changed (`git diff <base> -- DEPLOY.md`: 6 insertions, 2 deletions); the incompatibility (nginx 1.24 rejects `http2 on`) recorded in RUST.md §10.14.
7. Scope held: `git diff --stat <base> -- apps/app/src` lists `auth/redirects.ts` only; no `outline-none`, `MotionConfig`, vitest/jest-dom/eslint/forwardRef/authStore change; `git diff --stat <base> -- crates/core crates/wasm crates/worker/src apps/app/tests/fixtures crates/core/tests packages Cargo.lock pnpm-lock.yaml` empty; no deletion (`git diff --diff-filter=D --name-only <base>` empty).
8. Suites: `pnpm check:all` exit 0 on the final code state (log `<session scratchpad>/checkall-r412.log` ending `== all checks passed`, apps/app 59 files / 434 cases); `pnpm audit --prod` clean; `cargo deny check` ok; `pnpm typecheck`, `pnpm lint` exit 0; `git status --short` empty.
9. Docs: RUST.md §10.14 covers D3 (cases, consumers, react-router behaviour read in the installed package, negative run), D1 (provenance and digest, cosign not checked, contents, proofs, e2e), D6 (the 1.24 incompatibility and the nginx -t runs); CHANGELOG Unreleased has the line; TODO carries the accessibility chantier (D2, D5) and the maintenance backlog (D4) without doing them.
## CLARIFICATIONS
Q: D6 says « vers http2 on; »; the live VPS runs nginx 1.24, which rejects it. Replace blindly? / A: no: the owner asked to report a real incompatibility rather than work around it silently; the runbook gives the new form for >= 1.25.1 and names the 1.24 form, both proven with `nginx -t`. [gated 2026-10-21, owner « Signaler toute régression ou incompatibilité réelle »]
Q: the worker's real check without the managed Supabase? / A: `pnpm e2e:avatar` on the local stack (the documented real-stack test, plain HTTP on the Docker network); the HTTPS path is the R4.11 TLS test, unchanged and run in the image's test stage. [gated 2026-10-21, owner D1 « vérifications pertinentes du worker réel »]
+7
View File
@@ -0,0 +1,7 @@
# Repository gitleaks config: the default rules, plus narrow, justified exceptions.
[extend]
useDefault = true
[allowlist]
description = "[gated 2026-10-18] R4 report:compare oracle: sha256 digests of fixture PDFs whose names contain 'key' or 'keywords' (the /Keywords stamp cases); no secret can live in this generated file"
paths = ['''^crates/core/tests/oracles/r4/compare/compare\.json$''']
+1
View File
@@ -6,3 +6,4 @@ apps/app/tests/fixtures/goldens/
packages/core-wasm/types/
packages/core-wasm/pkg/
packages/core-wasm/pkg-proofs/
packages/core-wasm/tests/n-1/
+12
View File
@@ -6,10 +6,22 @@ Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Fixed (2026-10-21, R4 close)
- Sign-in redirects: a `next` value whose dot segments normalise into `//host` (`/..//host`, `/%2e%2e//host`) now falls back to the dashboard instead of being returned as a protocol-relative path. The worker image runs on `distroless/static-debian13:nonroot` (the Debian 12 tags are no longer updated). DEPLOY.md shows `http2 on;` for nginx 1.25.1 and later and keeps the `listen ... http2` form for nginx 1.24 (`docs/development/RUST.md` §10.14).
- Dependencies: `rustls-webpki` 0.103.16 and `webpki-roots` 1.0.10 (RUSTSEC-2026-0382, RUSTSEC-2026-0381; the worker's TLS client), `react-router-dom` 7.18.4 (GHSA-wrjc-x8rr-h8h6, GHSA-chx6-hx7r-mcp5 and three RSC / SSR advisories the application does not reach). A worker test proves the HTTPS client refuses an untrusted server certificate (`docs/development/RUST.md` §10.13).
- The footer's « Propulsé par ZenQuality » logo is bundled with the application instead of loaded from zenquality.fr: the documented production CSP (`img-src 'self' data: blob:`) refused the external image and showed the alt text in its place. Same picture, no policy change; the exported PDF never depended on it.
### Fixed (2026-10-18)
- Improve Safari/iOS PDF download reliability by attaching the download link to the document during activation and delaying object URL revocation by 30 seconds. The file name and content remain unchanged.
### Changed (Rust R4, PDF core, 2026-10-18 to 2026-10-19; validated by the owner's device acceptance on the computer, Android and a real iPhone, and merged 2026-10-21)
- **The PDF archives are read, written and checked by the Rust core** (`crates/core/src/pdf`, `docs/development/RUST.md` §10). Import: the attachment is located by the core's byte scan, inflated under the 16 MiB cap, probed as JSON and read by the R2 layered reader, inside a module worker created for the file and terminated after it (R4.3; the rescue copy follows the same path). Export: an incremental session in the page's engine composes each view, takes the browser's rasters one by one, decodes and writes each image on arrival, and hands the file out in parts (R4.6; no raster and no second copy of the file kept). `pnpm report:compare` runs the core's `report-compare` binary (R4.7). The PDFs are the ones the TypeScript engine wrote: same streams, images, links, metadata and attachment, pixel-identical through poppler on the reference reports; three declared differences only (`Producer`/`Creator` now `Faunosteo`, the attachment's report in contract key order, hostile files refused where the TypeScript repaired them).
- **Removed at R4.8** (2026-10-19): `packages/pdf` (the TypeScript engine and its tests), `pdf-lib`, `@pdf-lib/*` and `@resvg/resvg-js`, the TypeScript CLI `apps/app/scripts/compare-reports.ts`, the application's TypeScript import path and its dependency on `@faunosteo/domain`, the oracle generators. Kept: the frozen oracles, goldens and fixture PDFs, the frozen N-1 readers (`packages/core-wasm/tests/n-1`: the Zod schemas and the byte-scan reader of the R3 build), `packages/anatomy` and `packages/domain` for the curation pipeline until R5.
- Old browsers (Firefox 102 to 112, Safari 16.0 to 16.3) gain the import and the logos; module workers need Firefox 114 (OD-1). Memory: the import worker holds one copy of the file; the export's linear memory stays reserved in the page until reload (OD-2), about 62 MiB for a 44 MiB file; the per-export growth of the browser's own process in Chromium is an open reserve (BDR-063). Module 1,535,289 B raw, 519,795 B gzip (budget 600 KB).
### Changed (Rust R3, anatomy core, 2026-10-15; validated by the owner's LAN acceptance and merged 2026-10-17)
- **The editor canvas draws what the Rust core composes** (`crates/core/src/anatomy`): one SVG reader for every drawing the product shows (bounds checked by a markup scanner before any XML parser, the engine's allowlist matched the same way, a reference graph refusing cycles and expansions over 50,000 elements, a serialiser that re-reads to the same tree), the annotation layer and the view composition, reached through the new `view.canvas` operation and memoised per view. The canvas keeps its in-place selection styling, click and tooltip delegation. The browser-side denylist and the app's dependency on the TypeScript renderer are gone; the PDF engine and the curation pipeline keep the TypeScript renderer until R4 and R5.
+43 -37
View File
@@ -20,8 +20,9 @@ tables `species`, `anatomical_sheets` / `_versions` / `_assets`). Step 5 moved t
application onto that model: the editor renders the bundled reference sheet (the
curated equine DRAFT, `SHEET_BUNDLE=draft`), writes Report v3 and imports v2 PDFs
through a generated migration map. Step 6 made the PDF an autonomous archive: the
`packages/pdf` engine renders from explicit inputs (report, sheet snapshot, branding,
labels, rasterizer) with no network and no DOM, and the attachment is an envelope v1
PDF engine (TypeScript `packages/pdf` until R4, the Rust core `crates/core/src/pdf`
since) renders from explicit inputs (report, sheet snapshot, branding, labels,
rasterizer) with no network and no DOM, and the attachment is an envelope v1
carrying the report, a lean sheet snapshot, the branding and the labels used, so an old
bilan is reproduced identically after any catalog, wording or logo change
(`docs/PDF-FORMAT.md`). Step 7 added identity: email/password sign-up with
@@ -57,7 +58,7 @@ MVP species: equine only. Open-source MIT.
| Styling | Tailwind CSS v4 CSS-first (no postcss config) | 4.x |
| State | Zustand | 5 |
| Validation | Zod | 3 |
| PDF | pdf-lib | 1.17 |
| PDF | the Rust core's reader and writer (`crates/core/src/pdf`, R4; no PDF library) | — |
| SVG raster | native Image/canvas (no dependency) | — |
| Animation | motion | 11 |
| Tests | vitest + happy-dom + @testing-library/react | 3.x |
@@ -118,7 +119,7 @@ pnpm db:types:check # CI diff
pnpm build:preview # SHEET_BUNDLE=draft build (manual validation, preview deployments)
pnpm preview:draft # same, then serves it
pnpm import:equine # regenerate legacy-import/ and draft/ (document, migration map, review drawings)
pnpm report:compare <pdf|dir>... # archive check: attachment vs its v3 reading, unresolved items flagged (docs/PDF-FORMAT.md)
pnpm report:compare <pdf|dir>... # archive check: attachment vs its v3 reading, unresolved items flagged (docs/PDF-FORMAT.md); the core's `report-compare` binary since R4.7 (scripts/report-compare.sh, first run compiles)
# Rust (docs/development/RUST.md) — native toolchain (user-level rustup, channel of rust-toolchain.toml) first
pnpm rust:check # scripts/rust-check.sh: fmt --check, clippy -D warnings, cargo test (core, wasm, worker unit), ts-rs export, cargo deny
@@ -191,9 +192,8 @@ faunosteo/
├─ apps/app/ ← @faunosteo/app (everything below until packages/)
├─ public/ ← favicons, env.js, site header logo only (PDF logos live in src/assets/brand; no anatomy asset)
├─ vite/sheet-bundle.ts ← Vite plugin: `virtual:faunosteo-sheet` (SHEET_BUNDLE=draft|none)
├─ scripts/compare-reports.ts ← `pnpm report:compare`: archive PDF vs v3 reading (pure part in scripts/compare/report.ts)
├─ src/
│ ├─ assets/brand/ ← the four PDF branding logos, bundled by Vite (?inline / ?raw / ?url), never fetched
│ ├─ assets/brand/ ← the four PDF branding logos and the footer's ZenQuality logo, bundled by Vite (?inline / ?raw / ?url), never fetched (production CSP img-src 'self')
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ useUnsavedGuard.ts ← beforeunload while the report is unsaved, called once in App
@@ -234,8 +234,8 @@ faunosteo/
│ │ ├─ shell/{AppLayout,SidebarNav,MobileDrawer,UserBadge,SignOutButton}.tsx
│ │ └─ account/{SectionCard,SaveRow,AvatarSection,PersonalInfoForm,ProfessionalInfoForm,PreferencesForm,SecurityPanel,RoleBadges}.tsx
│ ├─ account/avatarTransport.ts ← magic-byte sniff (never SVG), createImageBitmap → canvas ≤ 1024 px → JPEG transport blob
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
│ ├─ pdf/ ← the app side of the PDF (export on the core's session since R4.6; the import runs in the worker, `core/worker`)
│ │ ├─ export.ts + labels.ts ← exportReportToPdf (snapshot + branding + labels → ExportSession, rasters one by one, Blob of the parts, abort on unmount), defaultPdfLabels (25 keys); the tests' in-process import lives in tests/helpers/pdfImport.ts (the module's reader)
│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter
│ ├─ lib/{dates,id,assert,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens}.css ← Tailwind v4 CSS-first
@@ -259,8 +259,7 @@ faunosteo/
├─ packages/domain/ ← @faunosteo/domain (pure, no DOM, zod only): anatomical-sheet (document, integrity rules, sheet-index), report (v3, v2 migration, rebase), archive (sheet snapshot, envelope v1, branding, labels, layered reader)
│ ├─ src/anatomical-sheet/{schema,validate,create}.ts ← canonical sheet document + integrity rules
│ └─ tests/{fixtures/horse-slice.ts,*.test.ts}
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, frozen TS annotation-layer renderer + view composer (`./render`: PDF engine until R4, pipeline until R5; the app no longer depends on it)
├─ packages/pdf/ ← @faunosteo/pdf: browser-free PDF engine — src/{export,read,text,branding}.ts, attachment/, svg/{parse,sanitize,view}.ts, render/, i18n/; tests reproduce the Step 6 goldens
├─ packages/anatomy/ ← @faunosteo/anatomy: legacy importer, curation pipeline, frozen TS annotation-layer renderer + view composer (`./render`: the pipeline until R5; no app and no PDF consumer since R4.8)
│ ├─ src/legacy/{svg,catalog,regions,ids,report,importer}.ts, src/cli/import-equine.ts
│ ├─ src/curation/{schema,targets,fields,ops,rename,apply,types,assets,labels,stats,changelog,review-report,overlay,seed,sources,pipeline}.ts ← changeset → draft
│ └─ tests/ ← counts preserved, special cases, determinism, curation ops, golden artifacts
@@ -278,12 +277,12 @@ faunosteo/
│ │ └─ draft/ ← GENERATED working revision: document, cleaned horse.svg, sheet-ref, report-migration-map, CHANGELOG, REVIEW-REPORT, review/*.svg, equine_draft.sql
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index
├─ packages/core-wasm/ ← @faunosteo/core-wasm: CoreRuntime (lazy, poison, recovery) + Node source, pkg/ shipped and pkg-proofs/ (built, git-ignored, BUILD_STAMP), ts-rs types (committed), frozen N-1 reader (tests/n-1), tests
├─ packages/core-wasm/ ← @faunosteo/core-wasm: CoreRuntime (lazy, poison, recovery) + CoreExportSession (R4.6) + Node source, pkg/ shipped and pkg-proofs/ (built, git-ignored, BUILD_STAMP), ts-rs types (committed), frozen N-1 reader (tests/n-1), tests
├─ crates/ ← Rust workspace (Cargo.toml, rust-toolchain.toml, deny.toml, clippy.toml, .cargo/config.toml at the root)
│ ├─ core/ ← faunosteo-core: domain/{js,sheet,report,archive,editor,session} (contracts and rules), anatomy/{svg/{prescan,tree,sanitize,refs,number,serialize},layer,compose} (R3: the one SVG reader, the layer, canvas + highlight composition), ops.rs + facade.rs (`call`, `call_with_sheet`), json (JS number printing); tests/{oracles,conformance,fixtures} frozen from the TypeScript (oracles/r3, fixtures/svg/hostile); no I/O, no clock (lint-enforced)
│ ├─ core/ ← faunosteo-core: domain/{js,sheet,report,archive,editor,session} (contracts and rules), anatomy/{svg/{prescan,tree,sanitize,refs,number,serialize},layer,compose} (R3: the one SVG reader, the layer, canvas + highlight composition), pdf/{read,json_js,import,write,compare} (R4: reader, writer and session, the archive check tool behind feature `cli`), ops.rs + facade.rs (`call`, `call_with_sheet`), json (JS number printing), bin/report_compare.rs (`pnpm report:compare`, the one file allowed std::fs); tests/{oracles,conformance,fixtures,pdf/LEDGER.tsv} frozen from the TypeScript (oracles/r3, oracles/r4, fixtures/svg/hostile); no I/O, no clock (lint-enforced)
│ ├─ wasm/ ← faunosteo-wasm: wasm-bindgen facade (core_version, call, SheetHandle; trap exports in the proofs build only)
│ └─ worker/ ← faunosteo-worker: plain main; `decode` sandboxed child (rlimits, seccomp allowlist, image → libwebp), parent Spawner + RIFF check; R1 `run` loop: config, log (JSON lines, allowlist), keys, backend trait + http (ureq, PostgREST rpc + Storage objects), job, sweep, watchdog; Dockerfile, scripts/derive-seccomp.sh
├─ scripts/{rust-env,rust-check,wasm-build,check-all,avatar-e2e}.sh, wasm-stamp.mjs ← native Rust gate, wasm build (pkg + pkg-proofs + stamp), the pre-merge gate (`pnpm check:all`), the real-stack avatar e2e
├─ scripts/{rust-env,rust-check,wasm-build,check-all,avatar-e2e,report-compare}.sh, wasm-stamp.mjs ← native Rust gate, wasm build (pkg + pkg-proofs + stamp), the pre-merge gate (`pnpm check:all`), the real-stack avatar e2e, the archive check tool (`pnpm report:compare`)
├─ scripts/{dev-env,supabase,dev}.sh ← the DEV origin (LAN address) in one place; CLI wrapper; `pnpm dev` on that origin
├─ docker-compose.yml ← `app` service; `worker` service under the `worker` profile (read-only, cap_drop ALL, external Supabase network, `.env.worker`)
├─ docker/rust-builder.Dockerfile, rust-run.sh, csp-proof/ ← reproducible Rust builder (alternative) + the CSP proofs (R0 module, R2 app image: app-image.sh)
@@ -321,23 +320,31 @@ SVG interaction
→ vertebra.select per tap, vertebra.sync / zone.add_sides on confirm → updateObservation() in store
→ toggle / remove_both_sides → the core's observation → updateObservation(); findings picker → finding.toggle
PDF export (app side: apps/app/src/pdf, engine: packages/pdf)
→ exportReportToPdf(report, index, { locale })
→ index.ops.snapshot(report) (core: archive.snapshot) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels
→ exportReportArchive({ report, sheet, branding, labels, locale, rasterizer: browserRasterizer, exportedAt })
assertSnapshot (caps, integrity, sheet invariant) → fonts (WinAnsi StandardFonts, safeText guard)
→ per observation: composeHighlightedViewSvg (xmldom: sanitise allowlist → composeViewSvg highlight) → rasterizer → page
→ conclusion page, footer, envelope v1 attached as osteo-report.json, Keywords faunosteo-archive/1
→ { pdf, envelope, warnings } → { pdf, warnings } to EditorRoute → browser download, alert naming failed logo slots / views
→ exportFromEnvelope(envelope, …) re-exports an archive from its own snapshot, branding and labels (no sheet)
PDF export (app side: apps/app/src/pdf; writer: crates/core/src/pdf/write, RUST.md §10.4 to §10.8)
→ exportReportToPdf(report, index, { locale, signal })
→ index.ops.snapshot(report) (core: archive.snapshot) + loadBranding() (4 logos bundled at build time, no network) + defaultPdfLabels (labels.ts)
→ openExportSession(runtime, ExportInput JSON): the core checks the input (branding and labels schemas, snapshot gate through the SVG reader,
sheet match, page caps), builds the envelope under 16 MiB, opens the file (Info, fonts)
→ loop session.next(): the SVG logos, then each observation's views (main first), composed by the core (R3 compose_highlight, 1200 px wide)
→ browserRasterizer under Promise.all → rasterFailed in rejection order, addRaster in request order (a view is decoded and its
XObject written on arrival, PNG and planes dropped; a PNG the decoder refuses is the view's warning)
→ session.finish(): conclusion page, footers, pages, attachment (osteo-report.json, Keywords faunosteo-archive/1), self-check by the R4
reader → the file in parts → new Blob(parts) to EditorRoute → browser download, alert naming failed logo slots / views; free() in finally
→ a trap poisons the runtime as any core call; a session of a dropped instance answers core_unavailable; leaving the editor aborts and frees
→ export_from_envelope (cargo only) re-exports an archive from its own snapshot, branding and labels (no sheet)
PDF import
→ readAttachment(bytes) → engine byte scan for the EmbeddedFile stream (TS until R4; no pdf-lib parse on untrusted
bytes, BLK-009): named osteo-report* first, capped native inflation, JSON depth pre-scan
→ loadSheetIndex (core loads here) → importAttachment(data, index) → core archive.import: layered reading (report:
v3 as is, v2 migrated, else incompatible_version; envelope metadata tolerant, snapshot/branding/labels strict →
archive kept or snapshotRejected) + rebase on the loaded sheet (unresolved flags, labels kept), one call
→ hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased / migrated) → navigate /editor
PDF import (R4.3, RUST.md §10.5; the core's reader `crates/core/src/pdf/read`, never a PDF library)
→ HomeRoute: routing on the first KiB and the size pre-checks → startImport (core/worker/controller) → a module worker
created for the file (import.worker.ts, handler.ts): the compiled module posted by the page, a SheetHandle of the
bundled sheet, the file streamed in chunks into the module's memory (FileBytes), `import_pdf_bytes`
→ in the core: byte scan for the EmbeddedFile stream (BLK-009: no object-graph parse): named osteo-report* first, capped
inflation (16 MiB budget shared by the candidates), JSON prescan (depth, value count OD-3), the JavaScript-path
decoding (`json_js`), then archive.import: layered reading (report: v3 as is, v2 migrated, else incompatible_version;
envelope metadata tolerant, snapshot/branding/labels strict → archive kept or snapshotRejected) + rebase on the
loaded sheet (unresolved flags, labels kept), one call
→ the settlement mapped by core/worker/outcome.ts (closed kinds; timeout, crash and read error told apart: OD-5),
the worker terminated → hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased /
migrated) → navigate /editor; a rescue copy (JSON) follows the same worker path (`restore_copy_bytes`)
Identity (Step 7, docs/development/IDENTITY.md)
→ AuthProvider: authStore.start() = client.auth.initialize() (PKCE code in URL) + onAuthStateChange
@@ -387,7 +394,7 @@ Database (Supabase)
- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match; while signed in, `services/localeSync.ts` writes it to `profiles.locale` and applies the account locale on sign-in
- Form validation messages are i18n keys returned by the Zod schemas (`src/auth/validation.ts`, `src/account/validation.ts`), translated next to the field; GoTrue messages never reach the screen (`auth.failure.*`)
- Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
- PDF static labels (section headings, metadata) live in the engine (`packages/pdf/src/i18n`, `defaultPdfLabels`, 25 keys) and are archived in the envelope; the app dicts hold no `pdf.*` key
- PDF static labels (section headings, metadata) live in `apps/app/src/pdf/labels.ts` (`defaultPdfLabels`, 25 keys, moved verbatim from the engine at R4.6) and are archived in the envelope; the app dicts hold no `pdf.*` key
### Identity strings
- NEVER hardcode APP_SITE_NAME, APP_BRAND_NAME, APP_FOOTER_NAME, APP_TAGLINE
@@ -400,7 +407,7 @@ Database (Supabase)
### Annotation rendering
- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the markers are
drawn from the document (Rust core for the canvas since R3, `crates/core/src/anatomy`; the frozen TS renderer
`@faunosteo/anatomy/render` for the PDF engine and the pipeline until R4/R5, same output), with the attributes listed there
`@faunosteo/anatomy/render` for the pipeline until R5, same output), with the attributes listed there
- Every SVG the product draws goes through the core's one reader (`anatomy::svg::read_svg`): caps before any parse,
allowlist, reference graph; a product drawing with anything removed is refused at load, never repaired
- Never rely on element id, className or a label for click targeting or behaviour — always `data-anno-id`
@@ -411,7 +418,7 @@ Database (Supabase)
### Schemas
- The data contracts live in Rust since R2 (`crates/core/src/domain/{sheet,report,archive}`, Zod semantics
reproduced: strict where Zod was strict, optional absent, nullable required, Zod schema field order);
`packages/domain` is frozen (no new logic) for the PDF engine, the pipeline and the compare CLI until R4/R5,
`packages/domain` is frozen (no new logic) for the pipeline until R5 (the app no longer depends on it: R4.8),
and its Zod copy under `packages/core-wasm/tests/n-1` is the permanent N-1 reader. Never change a contract
without bumping the version on a breaking change (additive optional fields keep it); a change touches the
Rust struct, the regenerated ts-rs types and the N-1 test
@@ -432,8 +439,8 @@ Database (Supabase)
- A4 portrait: 595.28 × 841.89 pt
- No raw URLs in PDF output — abbreviated citations only
- JSON attachment filename must start with osteo-report; content = report archive envelope v1 (report v3 + sheet snapshot + branding + labels); import accepts bare v2 (migrated), bare v3 and envelope v1; a bad snapshot never loses the report
- The engine (`packages/pdf`) has no DOM lib, no fetch, no Node-only global (lint-enforced); rasterisation is an injected adapter; every SVG it receives is sanitised by allowlist with caps
- Page layout is frozen by the Step 6 goldens: any visible change needs a user decision and a golden regeneration
- The writer (`crates/core/src/pdf/write`, since R4.6; the TypeScript engine deleted at R4.8) takes no clock and no I/O; rasterisation is the browser's, one raster per core request; every SVG it composes went through the core's one reader. The export is an incremental session (OD-2): the file is written as the rasters arrive, held once, handed out in parts; never accumulate rasters or build the file twice
- Page layout is frozen by the Step 6 goldens and the R4 oracles (O1 draw logs, O2 PDFs): any visible change needs a user decision and a golden regeneration; the R4 digests (`goldens/r4/pdf.*.sha256`) pin the writer's own bytes and are rewritten only for a declared structural change, with the O2 comparisons re-run
- Fonts are StandardFonts (Helvetica/TimesRoman, WinAnsi encoding) — TTF Inter/Fraunces planned but not yet embedded. Any non-Latin-1 glyph in PDF text must use an ASCII surrogate until the TTF migration lands (e.g. `(!)` instead of `⚠`).
### Anatomical sheet content
@@ -559,7 +566,6 @@ RUST.md §9; validated and merged 2026-10-17). Next: R4 (PDF core), R5 (pipeline
| tailwindcss 4 | CSS-first utility framework |
| zustand 5 | Lightweight global state |
| zod 3 | Schema validation + type inference |
| pdf-lib 1.17 | Pure-JS PDF generation + native attachments |
| motion 11 | Animations (modals, toasts, observation cards) |
| vitest 3 | Test runner |
| happy-dom | DOM environment for tests |
@@ -582,9 +588,9 @@ RUST.md §9; validated and merged 2026-10-17). Next: R4 (PDF core), R5 (pipeline
- Annotation rendering changes require updating docs/ANNOTATION-RENDERING.md first.
- Never modify the legacy sources under `supabase/seed/anatomical-sheets/equine/legacy-sources/` — they are the
importer's input (the user's historical files).
- Ask before any change to `readReportArchive`, `readArchiveDocument`, `readAttachedDocument` or `rebaseReportOnSheet`, and to their Rust ports (`crates/core/src/domain/{archive/read,report/rebase,report/read,session}.rs`) — they handle user data; archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2).
- Ask before any change to the readers of user data: `crates/core/src/domain/{archive/read,report/rebase,report/read,session}.rs` and the PDF reader `crates/core/src/pdf/{read,json_js,import}.rs` (the TypeScript originals `readReportArchive`, `readArchiveDocument`, `readAttachedDocument`, `rebaseReportOnSheet` left with `packages/pdf` at R4.8; the frozen N-1 copies under `packages/core-wasm/tests/n-1` are never edited); archive readers never drop a schema version (envelope v1, Report v2/v3, sheet document v2).
- Import never parses untrusted PDF object graphs: the attachment is located by byte scan and inflated under the 16 MiB cap (BLK-009). Opening the import to external users is gated by `docs/development/PDF_IMPORT_HARDENING.md` §5 (BDR-040).
- After PDF roundtrip tests fail: check attachment bytes, then the layered reader (report first, envelope metadata, snapshot/branding/labels), then DecompressionStream inflation. Goldens under `apps/app/tests/fixtures/goldens/step6` are never regenerated without a user decision.
- After PDF roundtrip tests fail: check the attachment bytes (the N-1 scanner reads them in the envelope suites), then the layered reader (report first, envelope metadata, snapshot/branding/labels), then the core's inflation (`pdf/read/inflate.rs`). Goldens under `apps/app/tests/fixtures/goldens/step6` and the R4 digests under `goldens/r4` are never regenerated without a user decision.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
- Rust: native on the Ubuntu development machine (user-level rustup, never a global package, never on the VPS); `pnpm rust:check` and `pnpm wasm:build` run natively, the `:docker` variants reproduce them in the builder image. Before every Rust commit: `pnpm rust:check` green, `pnpm worker:test` green when `crates/worker` changed (Docker only: the sandbox tests and the seccomp derivation never run natively), the ts-rs types under `packages/core-wasm/types` committed, `Cargo.lock` committed. Before a merge: `pnpm check:all`. No CI runs on the forge: a workflow file is never cited as a passed check. The core takes ids, time and bytes as inputs (clippy `disallowed_methods`); the worker child is the only process that decodes untrusted bytes.
- Storage or worker change: `pnpm e2e:avatar` (worker container against the local stack, `packages/supabase/tests/e2e`) in addition to `pnpm worker:test`; `docker compose --profile worker` serves the worker from `.env.worker` (never the app `.env`).
Generated
+443 -6
View File
@@ -8,6 +8,71 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
[[package]]
name = "aes"
version = "0.9.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "35f0f96ce78e38c3dc6d8948aa8163d06385be74000f3c7a95bf1eef35d3ea32"
dependencies = [
"cipher",
"cpubits",
"cpufeatures",
]
[[package]]
name = "alloc-no-stdlib"
version = "2.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
[[package]]
name = "alloc-stdlib"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"
dependencies = [
"alloc-no-stdlib",
]
[[package]]
name = "asn1-rs"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
dependencies = [
"asn1-rs-derive",
"asn1-rs-impl",
"displaydoc",
"nom 7.1.3",
"num-traits",
"rusticata-macros",
"thiserror",
"time",
]
[[package]]
name = "asn1-rs-derive"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
"synstructure 0.13.2",
]
[[package]]
name = "asn1-rs-impl"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "autocfg"
version = "1.5.1"
@@ -20,6 +85,15 @@ version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
[[package]]
name = "bit-vec"
version = "0.9.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
dependencies = [
"serde",
]
[[package]]
name = "bitflags"
version = "2.13.2"
@@ -35,6 +109,25 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "block-padding"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
dependencies = [
"hybrid-array",
]
[[package]]
name = "brotli-decompressor"
version = "5.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
]
[[package]]
name = "bumpalo"
version = "3.20.3"
@@ -59,6 +152,15 @@ version = "1.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
[[package]]
name = "cbc"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896"
dependencies = [
"cipher",
]
[[package]]
name = "cc"
version = "1.8.0"
@@ -77,6 +179,27 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "chacha20"
version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
dependencies = [
"cfg-if",
"cpufeatures",
"rand_core",
]
[[package]]
name = "cipher"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
dependencies = [
"crypto-common",
"inout",
]
[[package]]
name = "const-oid"
version = "0.10.2"
@@ -112,6 +235,18 @@ dependencies = [
"url",
]
[[package]]
name = "core_detect"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
[[package]]
name = "cpubits"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae"
[[package]]
name = "cpufeatures"
version = "0.3.1"
@@ -139,6 +274,26 @@ dependencies = [
"hybrid-array",
]
[[package]]
name = "data-encoding"
version = "2.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
[[package]]
name = "der-parser"
version = "10.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
dependencies = [
"asn1-rs",
"displaydoc",
"nom 7.1.3",
"num-bigint",
"num-traits",
"rusticata-macros",
]
[[package]]
name = "deranged"
version = "0.5.9"
@@ -176,6 +331,29 @@ dependencies = [
"litrs",
]
[[package]]
name = "ecb"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26f2a8b3e564eba0877223dc343703ad0385794e882e6d13f3a4dd5c6b1f41ac"
dependencies = [
"cipher",
]
[[package]]
name = "encoding_rs"
version = "0.8.42"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e985e0451871ad22fb8d2b6b076e2028a502a0d3950998c2c5c0a4f9b5d9679"
dependencies = [
"cfg-if",
"core_detect",
"multiversion_no_op",
"rustversion",
"scopeguard",
"simdutf8",
]
[[package]]
name = "equivalent"
version = "1.0.2"
@@ -186,9 +364,12 @@ checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
name = "faunosteo-core"
version = "0.1.0"
dependencies = [
"lopdf",
"miniz_oxide 0.9.1",
"roxmltree",
"serde",
"serde_json",
"sha2",
"ts-rs",
"url",
]
@@ -198,6 +379,7 @@ name = "faunosteo-wasm"
version = "0.1.0"
dependencies = [
"faunosteo-core",
"serde_json",
"wasm-bindgen",
]
@@ -210,7 +392,9 @@ dependencies = [
"image",
"libc",
"libwebp-sys",
"rcgen",
"rlimit",
"rustls",
"seccompiler",
"serde",
"serde_json",
@@ -279,6 +463,7 @@ dependencies = [
"cfg-if",
"libc",
"r-efi",
"rand_core",
]
[[package]]
@@ -458,6 +643,16 @@ dependencies = [
"hashbrown",
]
[[package]]
name = "inout"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ce983bb6fb399067d101fbfc9e74174e07e9f29a2bc679efefeb8c645819c3f"
dependencies = [
"block-padding",
"hybrid-array",
]
[[package]]
name = "itoa"
version = "1.0.18"
@@ -474,6 +669,12 @@ dependencies = [
"libc",
]
[[package]]
name = "lazy_static"
version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
[[package]]
name = "libc"
version = "0.2.190"
@@ -509,12 +710,55 @@ version = "0.4.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
[[package]]
name = "lopdf"
version = "0.45.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bfffda0fe1ab0157e1a13c14bebd3f28671f2fccb7922f0722ec53926e6922d3"
dependencies = [
"aes",
"bitflags",
"brotli-decompressor",
"cbc",
"ecb",
"encoding_rs",
"flate2",
"getrandom 0.4.3",
"indexmap",
"itoa",
"log",
"md-5",
"nom 8.0.0",
"rand",
"rangemap",
"sha2",
"stringprep",
"thiserror",
"weezl",
]
[[package]]
name = "md-5"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "69b6441f590336821bb897fb28fc622898ccceb1d6cea3fde5ea86b090c4de98"
dependencies = [
"cfg-if",
"digest",
]
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "minimal-lexical"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
[[package]]
name = "miniz_oxide"
version = "0.8.9"
@@ -545,12 +789,56 @@ dependencies = [
"pxfm",
]
[[package]]
name = "multiversion_no_op"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d"
[[package]]
name = "nom"
version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
]
[[package]]
name = "nom"
version = "8.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
dependencies = [
"memchr",
]
[[package]]
name = "num-bigint"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
dependencies = [
"num-integer",
"num-traits",
]
[[package]]
name = "num-conv"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-integer"
version = "0.1.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -560,6 +848,15 @@ dependencies = [
"autocfg",
]
[[package]]
name = "oid-registry"
version = "0.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
dependencies = [
"asn1-rs",
]
[[package]]
name = "once_cell"
version = "1.21.4"
@@ -642,6 +939,42 @@ version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "rand"
version = "0.10.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
dependencies = [
"chacha20",
"getrandom 0.4.3",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[package]]
name = "rangemap"
version = "1.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d"
[[package]]
name = "rcgen"
version = "0.14.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
dependencies = [
"ring",
"rustls-pki-types",
"time",
"x509-parser",
"yasna",
]
[[package]]
name = "ring"
version = "0.17.14"
@@ -674,6 +1007,15 @@ dependencies = [
"memchr",
]
[[package]]
name = "rusticata-macros"
version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
dependencies = [
"nom 7.1.3",
]
[[package]]
name = "rustls"
version = "0.23.46"
@@ -700,9 +1042,9 @@ dependencies = [
[[package]]
name = "rustls-webpki"
version = "0.103.15"
version = "0.103.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281"
dependencies = [
"ring",
"rustls-pki-types",
@@ -715,6 +1057,12 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
[[package]]
name = "scopeguard"
version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
[[package]]
name = "seccompiler"
version = "0.5.0"
@@ -792,6 +1140,12 @@ version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
[[package]]
name = "simdutf8"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"
[[package]]
name = "smallvec"
version = "1.16.3"
@@ -804,6 +1158,17 @@ version = "1.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
[[package]]
name = "stringprep"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
dependencies = [
"unicode-bidi",
"unicode-normalization",
"unicode-properties",
]
[[package]]
name = "subtle"
version = "2.6.1"
@@ -832,6 +1197,17 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "synstructure"
version = "0.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "synstructure"
version = "0.14.0"
@@ -912,6 +1288,12 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
[[package]]
name = "ts-rs"
version = "12.0.1"
@@ -940,12 +1322,33 @@ version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "unicode-bidi"
version = "0.3.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "unicode-normalization"
version = "0.1.26"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d"
dependencies = [
"tinyvec",
]
[[package]]
name = "unicode-properties"
version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
[[package]]
name = "untrusted"
version = "0.9.0"
@@ -1066,13 +1469,19 @@ dependencies = [
[[package]]
name = "webpki-roots"
version = "1.0.9"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9"
dependencies = [
"rustls-pki-types",
]
[[package]]
name = "weezl"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4ca08e5ef825b65b056d9efbd95c8750683f0a6d0466d02e96dc2e4e360f3d2"
[[package]]
name = "winapi-util"
version = "0.1.11"
@@ -1176,6 +1585,34 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
[[package]]
name = "x509-parser"
version = "0.18.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
dependencies = [
"asn1-rs",
"data-encoding",
"der-parser",
"lazy_static",
"nom 7.1.3",
"oid-registry",
"ring",
"rusticata-macros",
"thiserror",
"time",
]
[[package]]
name = "yasna"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
dependencies = [
"bit-vec",
"time",
]
[[package]]
name = "yoke"
version = "0.8.3"
@@ -1196,7 +1633,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"synstructure",
"synstructure 0.14.0",
]
[[package]]
@@ -1217,7 +1654,7 @@ dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
"synstructure",
"synstructure 0.14.0",
]
[[package]]
+3
View File
@@ -30,6 +30,9 @@ url = "2.5.8"
roxmltree = { version = "=0.21.1", default-features = false, features = ["std", "positions"] }
# The CLI in docker/rust-builder.Dockerfile must be this exact version.
wasm-bindgen = "=0.2.129"
# FlateDecode inflation of the PDF attachment (R4): the version `png` already locks through
# flate2; no std, so the same code runs on wasm32.
miniz_oxide = { version = "0.9.1", default-features = false, features = ["with-alloc"] }
image = { version = "0.25.10", default-features = false, features = ["jpeg", "png", "webp"] }
libwebp-sys = "0.14.4"
seccompiler = "0.5.0"
+34 -4
View File
@@ -284,6 +284,16 @@ attachment"; a Step 6 build reads every older PDF (bare v2 and v3). Roll back
only with that limit in mind and tell the practitioners which build produced
their files.
Rollback note (PDF archives, R4): PDFs written by an R4 build (the core's
writer) are read by the R3 build and by release 0.2.0: the frozen copy of
their reader (`packages/core-wasm/tests/n-1/scanner`, O11) and the frozen
Zod schemas (`n-1/domain`) read every R4 fixture in the test suites
(`n-1.reader`, `n-1.scanner`, `archive.envelopes`); the attachment bytes are
the envelope the TypeScript wrote, in contract key order (D-R11). An R4
build reads every older PDF (bare v2, bare v3, Step 6 and R3 envelopes).
The TypeScript PDF engine left the repository at R4.8: a rollback is a
previous image, never a rebuild of the old engine.
---
## Data persistence
@@ -388,8 +398,12 @@ server {
}
server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
# nginx >= 1.25.1: HTTP/2 is its own directive (`listen ... http2` is deprecated).
# nginx 1.24 (Ubuntu 24.04 package) does not know `http2 on;`: there, write
# `listen 443 ssl http2;` and `listen [::]:443 ssl http2;` instead. Check with `nginx -v`.
listen 443 ssl;
listen [::]:443 ssl;
http2 on;
server_name faunosteo.com;
# ssl_certificate + ssl_certificate_key written by certbot
@@ -668,10 +682,26 @@ only, never `eval` or inline scripts (the proof's inline variant was still
blocked). Browser floor for the keyword: Chrome 97, Firefox 102, Safari 16
(the Vite 7 baseline). The `.wasm` file is served as `application/wasm` by
`nginx:1.31-alpine` out of the box; since R2 the image precompresses it and
`docker/nginx.conf` serves the `.wasm.gz` with `gzip_static on;` (372 KB
served for 1.18 MB raw, D-R13 budget 600 KB). A proxy in front must pass
`docker/nginx.conf` serves the `.wasm.gz` with `gzip_static on;` (R4.8
module with the PDF reader, writer and session: 1,535,289 B raw, 519,795 B
gzip -9; R3: 1.18 MB raw, 372 KB served; D-R13 budget 600 KB, report line
550 KB passed at R4.6 and declared). A proxy in front must pass
`Content-Encoding` through and keep the `application/wasm` type.
Since R4 the PDF import runs in a module worker (`/assets/import.worker-*.js`,
a same-origin hashed file that `script-src 'self'` already allows; no
`blob:`, no inline worker): the worker's response carries the same policy, so
the keyword is required for the import too. Without it the import answers
« Le moteur de lecture n'a pas pu être chargé » and nothing else changes. The
CSP needs no other change. Browser support of the import, apart from the
application's floor above: module workers need Firefox 114 or later (Chrome
80, Safari 15); the import already needed Firefox 113 and Safari 16.4 before
R4 (`DecompressionStream`), so Firefox 113 is the one version that loses it
(owner decision OD-1, `docs/development/RUST.md` §10). The worker never
fetches the module when the page's runtime already holds it (the compiled
module is posted), so an import works offline once the editor has loaded
the engine, as before.
---
## Health checks
-1
View File
@@ -38,7 +38,6 @@ COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
COPY apps/app/package.json apps/app/
COPY packages/domain/package.json packages/domain/
COPY packages/anatomy/package.json packages/anatomy/
COPY packages/pdf/package.json packages/pdf/
COPY packages/supabase/package.json packages/supabase/
COPY packages/core-wasm/package.json packages/core-wasm/
+3 -4
View File
@@ -44,7 +44,7 @@ contract.
- Tailwind CSS v4 (CSS-first, no postcss config)
- Zustand 5 (state)
- Zod 3 (schema + runtime validation)
- pdf-lib 1.17 (PDF generation + native attachments)
- PDF reader and writer in the Rust core (`crates/core/src/pdf`, WebAssembly in the app; no pdf-lib since R4.8)
- motion 11 (animations)
- vitest 3 + happy-dom + @testing-library/react
- Supabase (PostgreSQL 17, Auth, RLS) via the pinned CLI; `@supabase/supabase-js` 2; PGlite for Dockerless SQL tests
@@ -95,7 +95,7 @@ pnpm typecheck # TypeScript strict, no emit
pnpm lint # ESLint 9 flat config, 0 warnings
pnpm test:run # vitest run (domain, anatomy, supabase/PGlite, app)
pnpm build # tsc + vite build → apps/app/dist/
pnpm report:compare <pdf|dir>... # archive PDF vs its v3 reading, unresolved items flagged
pnpm report:compare <pdf|dir>... # archive PDF vs its v3 reading, unresolved items flagged (the core's binary; first run compiles)
pnpm rust:check # native: fmt, clippy -D warnings, cargo test, ts-rs export, cargo deny
pnpm wasm:build # native: browser module → packages/core-wasm/pkg (the core-wasm proofs run on it)
pnpm check:all # everything a branch must pass before a merge, in one command (needs Docker for the image stages)
@@ -148,13 +148,12 @@ faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md)
├─ src/state/ Zustand store (Report v3) + persistence adapter + locale store
├─ src/anatomy/ drawing: sanitised asset + annotation layer → inline SVG per view
├─ src/components/ UI primitives, canvas, observation, report
├─ src/pdf/ app side of the PDF: snapshot + branding + browser rasterizer → @faunosteo/pdf engine
├─ src/pdf/ app side of the PDF: snapshot + branding + labels + browser rasterizer → the core's export session
├─ src/lib/ id, dates, assert utilities
├─ src/styles/ Tailwind v4 CSS + design tokens
├─ tests/unit/ vitest tests on the bundled sheet (+ frozen v2 fixtures)
├─ packages/domain/ @faunosteo/domain: canonical sheet document + report document (v3, v2 migration)
├─ packages/anatomy/ @faunosteo/anatomy: legacy importer, curation pipeline, annotation-layer renderer + view composer
├─ packages/pdf/ @faunosteo/pdf: browser-free PDF engine (explicit inputs, archive envelope v1, layered reader)
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness
├─ supabase/ CLI config, SQL migrations, local seed (incl. the equine sheet), pgTAP tests
├─ docker/ entrypoint.sh + nginx.conf
+3 -2
View File
@@ -55,8 +55,9 @@ export default tseslint.config(
},
{
// R2: the application's rules run in the Rust core; its contracts come from
// @faunosteo/core-wasm. The TypeScript domain stays frozen for the PDF engine, the
// pipeline and scripts/ until R4/R5 (RUST_ARCHITECTURE_REVIEW VI.4).
// @faunosteo/core-wasm. The TypeScript domain is no longer a dependency of the
// application (R4.8); it stays frozen for the pipeline until R5
// (RUST_ARCHITECTURE_REVIEW VI.4). The rule keeps the door closed.
files: ['src/**/*.{ts,tsx}'],
rules: {
'no-restricted-imports': [
+2 -7
View File
@@ -11,19 +11,15 @@
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"report:compare": "tsx scripts/compare-reports.ts"
"lint": "eslint . --max-warnings 0"
},
"dependencies": {
"@faunosteo/core-wasm": "workspace:*",
"@faunosteo/domain": "workspace:*",
"@faunosteo/pdf": "workspace:*",
"@faunosteo/supabase": "workspace:*",
"motion": "^11.11.17",
"pdf-lib": "^1.17.1",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-router-dom": "^7.1.1",
"react-router-dom": "^7.18.4",
"zod": "^3.24.1",
"zustand": "^5.0.2"
},
@@ -41,7 +37,6 @@
"eslint-plugin-react-hooks": "^5.1.0",
"globals": "^15.14.0",
"happy-dom": "^20.10.6",
"tsx": "^4.23.15",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vite": "^7.3.6",
-158
View File
@@ -1,158 +0,0 @@
/**
* Archive check: reads the report attached to one or more Faunosteo PDFs and
* prints it next to its v3 reading on the bundled reference sheet.
*
* pnpm report:compare <file.pdf | folder>... [--summary] [--full]
* [--locale fr|en] [--diff a.pdf b.pdf]
*
* A v2 archive PDF is shown legacy id → canonical id, line by line; a v3 PDF
* is checked against the sheet. Items the sheet cannot place are marked
* `!! UNRESOLVED` with the reason. `--diff` compares the v3 content of two
* PDFs (an archive and its re-export after import, typically). By default
* only identifiers, catalog labels, counts and placeholders are printed and
* compared (a text shows as `conclusion (present)`); names and free texts,
* printed and compared, need `--full`.
* Untrusted strings are printed with control characters escaped. It writes
* no output file.
*/
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { basename, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import {
readArchiveDocument,
UnsupportedReportVersionError,
} from '@faunosteo/domain'
import {
ArchiveReadError,
MAX_PDF_BYTES,
readAttachedDocument,
} from '@faunosteo/pdf'
import { compareSheetIndex, type CompareSheetIndex } from './compare/sheet'
import {
compareReport,
diffLines,
esc,
parseArgs,
renderComparison,
renderSummary,
type CliArgs,
type Comparison,
} from './compare/report'
const SEED_DIR = resolve(
fileURLToPath(import.meta.url),
'../../../../supabase/seed/anatomical-sheets/equine/draft',
)
/** pnpm runs the script from apps/app; paths are typed from the caller's folder. */
const CWD = process.env.INIT_CWD ?? process.cwd()
function loadSheet(): CompareSheetIndex {
const json = (name: string) =>
JSON.parse(readFileSync(join(SEED_DIR, name), 'utf8')) as never
// The comparison needs the document and the map, not the drawings.
return compareSheetIndex({
ref: json('sheet-ref.json'),
document: json('document.json'),
migrationMap: json('report-migration-map.json'),
})
}
/** A folder stands for its PDFs; any other argument stays one entry. */
function expandArg(arg: string): string[] {
const path = resolve(CWD, arg)
try {
if (!statSync(path).isDirectory()) return [path]
} catch {
return [path] // reported as a failed entry by compareFile
}
return readdirSync(path)
.filter((f) => f.toLowerCase().endsWith('.pdf'))
.sort()
.map((f) => join(path, f))
}
async function compareFile(
path: string,
sheet: CompareSheetIndex,
args: CliArgs,
): Promise<Comparison> {
const st = statSync(path)
if (!st.isFile()) throw new Error('not a regular file')
if (st.size > MAX_PDF_BYTES) throw new Error('file too large')
const bytes = new Uint8Array(readFileSync(path))
// Byte-scan reader (BLK-009): the PDF object graph is never parsed here.
const raw = await readAttachedDocument(bytes)
try {
const outcome = readArchiveDocument(raw, sheet.sheet.migrationMap)
return compareReport(raw, outcome, sheet, args)
} catch (err) {
if (err instanceof UnsupportedReportVersionError) {
// The version is a number or null: nothing of the attachment is echoed.
throw new Error(`report version ${err.foundVersion} cannot be read`)
}
throw err
}
}
/** The engine's typed read failures, worded without echoing the file. */
const READ_FAILURES: Record<ArchiveReadError['kind'], string> = {
invalid_pdf: 'not a readable PDF',
no_attachment: 'no Faunosteo attachment found',
attachment_stripped:
'attachment stripped (the PDF is stamped as a Faunosteo archive)',
incompatible_version: 'report version cannot be read',
}
/** A missing or unreadable file is a failed entry, not a crash. */
function failureReason(err: unknown): string {
const code = (err as NodeJS.ErrnoException | undefined)?.code
if (code === 'ENOENT') return 'file not found'
if (code === 'EACCES') return 'file not readable'
if (err instanceof ArchiveReadError) return READ_FAILURES[err.kind]
// JSON.parse messages echo a fragment of the attachment.
if (err instanceof SyntaxError) return 'attachment is not valid JSON'
return err instanceof Error ? err.message : String(err)
}
async function main(argv: string[]): Promise<number> {
const args = parseArgs(argv)
const files = args.files.flatMap(expandArg)
if (files.length === 0 || (args.diff && files.length !== 2)) {
console.error(
'usage: pnpm report:compare <file.pdf | folder>... [--summary] [--full] [--locale fr|en] [--diff a.pdf b.pdf]',
)
return 1
}
const sheet = loadSheet()
const results: Comparison[] = []
let failures = 0
for (const file of files) {
const name = esc(basename(file))
try {
const c = await compareFile(file, sheet, args)
results.push(c)
if (!args.diff) {
const lines = args.summary
? [renderSummary(name, c)]
: [...renderComparison(name, c), '']
console.log(lines.join('\n'))
}
} catch (err) {
failures += 1
console.log(`!! ${name}: ${esc(failureReason(err))}`)
}
}
if (args.diff && results.length === 2) {
const diff = diffLines(results[0]!.normalized, results[1]!.normalized)
console.log(diff.length ? diff.join('\n') : 'identical v3 content')
}
return failures ? 2 : 0
}
main(process.argv.slice(2)).then(
(code) => process.exit(code),
(err) => {
console.error(esc(err instanceof Error ? err.message : String(err)))
process.exit(1)
},
)
-386
View File
@@ -1,386 +0,0 @@
import {
pickLabel,
ReportV2Schema,
findingPathKey,
type ArchiveReadOutcome,
type Finding,
type FindingV2,
type ObservationZoneV2,
type Report,
type ReportZone,
} from '@faunosteo/domain'
import type { Locale } from '../../src/i18n/types'
import type { CompareSheetIndex as SheetIndex } from './sheet'
/**
* Pure comparison of a report document found in a PDF with its v3 reading:
* a v2 archive is shown legacy id → canonical id line by line, a v3 report
* is checked against the bundled sheet. Every item the sheet cannot place is
* marked `!! UNRESOLVED` with the reason, nothing is summarised away. A Step 6
* envelope adds one header line saying whether its snapshot was kept.
*/
export const UNRESOLVED = '!! UNRESOLVED'
export interface CompareOptions {
locale: Locale
/** Print names and the real free texts (off by default: placeholders). */
full: boolean
}
export interface Comparison {
/** `v2` when the attachment was migrated, `v3` when read as is. */
source: 'v2' | 'v3'
header: string[]
observations: string[][]
footer: string[]
/** Lines in the v3 vocabulary only, for `--diff` between two PDFs. */
normalized: string[]
counts: Counts
}
export interface Counts {
observations: number
zones: number
unresolvedZones: number
findings: number
unresolvedFindings: number
}
/**
* Escapes Unicode control (C0, DEL, C1) and format characters (bidi
* overrides, zero-width) plus the line and paragraph separators as `\uXXXX`
* (newline and carriage return included): a PDF is untrusted, and a raw
* escape sequence printed to a terminal can rewrite the screen or fake a line.
*/
export function esc(text: string): string {
return text.replace(
/[\p{Cc}\p{Cf}\u2028\u2029]/gu,
(c) => `\\u${c.codePointAt(0)!.toString(16).padStart(4, '0')}`,
)
}
const q = (text: string) => `"${esc(text)}"`
function zoneRef(z: { annotationId: string; viewId: string; side?: string }) {
return esc(`${z.annotationId}@${z.viewId}${z.side ? ' ' + z.side : ''}`)
}
function findingRef(f: { findingZoneId: string; path: readonly string[] }) {
return esc(findingPathKey(f.findingZoneId, f.path))
}
function vertebraeOf(z: { vertebrae?: { region: string; index: number }[] }) {
return z.vertebrae?.length
? ` [${z.vertebrae.map((v) => esc(`${v.region}${v.index}`)).join(', ')}]`
: ''
}
/** Free-text lines: the texts with `full`, else only how many there are. */
function textLines(texts: readonly string[], full: boolean): string[] {
if (texts.length === 0) return []
if (!full) return [`text (${texts.length} entries)`]
return texts.map((t) => `text ${q(t)}`)
}
/** A single free-text field: its content with `full`, else a placeholder. */
function fieldLine(label: string, value: string | undefined, full: boolean) {
if (!value) return []
return [full ? `${label} ${q(value)}` : `${label} (present)`]
}
/** A v3 zone against the sheet: current label, or why it cannot be shown. */
function describeZone(
z: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const ref = `${zoneRef(z)}${vertebraeOf(z)}`
const anno = sheet.annotation(z.annotationId)
if (z.unresolved) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} ${UNRESOLVED} legacy zone kept from the archive`
}
if (!anno || anno.view_id !== z.viewId) {
return `${ref} ${q(z.labelFrSnapshot ?? '')} !! not in the sheet (unflagged)`
}
return `${ref} ${q(pickLabel(sheet.name(anno), locale))}`
}
/** A v3 finding against the sheet: current label, or why it cannot be shown. */
function describeFinding(
f: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const snapshot = q(locale === 'en' ? f.labelEnSnapshot : f.labelFrSnapshot)
const vet = f.requiresVetReferral ? ' (!)' : ''
const side = f.side ? ` ${esc(f.side)}` : ''
const ref = `${findingRef(f)}${side}${vet}`
if (f.unresolved) {
return `${ref} ${snapshot} ${UNRESOLVED} kept with its snapshot`
}
const node = sheet.nodeAt(f.findingZoneId, f.path)
if (!node) return `${ref} ${snapshot} !! not in the sheet (unflagged)`
if (node.children.length > 0) {
return `${ref} ${snapshot} !! points at a category, not a leaf`
}
return `${ref} ${q(pickLabel(node.name, locale))}`
}
/** Legacy zone → migrated zone. */
function describeZoneMigration(
legacy: ObservationZoneV2,
out: ReportZone,
sheet: SheetIndex,
locale: Locale,
): string {
const side = legacy.side ? ` ${legacy.side}` : ''
const detail = legacy.detailSourceId ? '@' + legacy.detailSourceId : ''
const from = `${esc(legacy.boneId + detail + side)}${vertebraeOf(legacy)}`
if (out.unresolved) {
return `${from} ${UNRESOLVED} unknown legacy id, kept as ${zoneRef(out)}`
}
const anno = sheet.annotation(out.annotationId)
const label = anno ? q(pickLabel(sheet.name(anno), locale)) : '!! missing'
return `${from} ${q(out.labelFrSnapshot ?? '')} → ${zoneRef(out)} ${label}`
}
/** Legacy finding → migrated finding, with the fate the map decided. */
function describeFindingMigration(
legacy: FindingV2,
out: Finding,
sheet: SheetIndex,
locale: Locale,
): string {
const map = sheet.sheet.migrationMap.finding_paths
const vet = legacy.requiresVetReferral ? ' (!)' : ''
const legacyKey = findingPathKey(legacy.zoneId, legacy.path)
const key = `${esc(legacyKey)}${vet}`
const snapshot = q(
locale === 'en' ? legacy.labelEnSnapshot : legacy.labelFrSnapshot,
)
if (out.unresolved) {
const why = Object.hasOwn(map, legacyKey)
? 'removed from the sheet, kept with its label'
: 'never in the legacy catalog, kept with its label'
return `${key} ${snapshot} ${UNRESOLVED} ${why}`
}
const node = sheet.nodeAt(out.findingZoneId, out.path)
const label = node ? q(pickLabel(node.name, locale)) : '!! missing'
const target = findingRef(out) === esc(legacyKey) ? 'same' : findingRef(out)
return `${key} ${snapshot} → ${target} ${label}`
}
function observationLines(
obs: Report['observations'][number],
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const lines = [
`[${esc(obs.id)}] severity ${esc(obs.severity ?? 'none')}`,
...obs.zones.map((z) => `zone ${describeZone(z, sheet, opts.locale)}`),
...obs.findings.map(
(f) => `finding ${describeFinding(f, sheet, opts.locale)}`,
),
...textLines(obs.freeTextFindings, opts.full),
...fieldLine('comment ', obs.comment, opts.full),
]
return lines
}
/** The report document inside the attachment: the envelope's, or the bare one. */
function reportDataOf(raw: unknown): unknown {
const isEnvelope =
typeof raw === 'object' &&
raw !== null &&
typeof (raw as { envelopeVersion?: unknown }).envelopeVersion === 'number'
return isEnvelope ? (raw as { report: unknown }).report : raw
}
function migratedObservationLines(
raw: unknown,
report: Report,
sheet: SheetIndex,
opts: CompareOptions,
): string[][] {
const v2 = ReportV2Schema.parse(reportDataOf(raw))
return v2.observations.map((legacy, i) => {
const out = report.observations[i]!
const severity = legacy.severity
? esc(`${legacy.severity} → ${out.severity}`)
: 'none'
const lines = [`[${esc(legacy.id)}] severity ${severity}`]
legacy.zones.forEach((z, j) => {
const line = describeZoneMigration(z, out.zones[j]!, sheet, opts.locale)
lines.push(`zone ${line}`)
})
legacy.findings.forEach((f, j) => {
const line = describeFindingMigration(
f,
out.findings[j]!,
sheet,
opts.locale,
)
lines.push(`finding ${line}`)
})
lines.push(...textLines(legacy.freeTextFindings, opts.full))
lines.push(...fieldLine('comment ', legacy.comment, opts.full))
return lines
})
}
function countsOf(report: Report): Counts {
const zones = report.observations.flatMap((o) => o.zones)
const findings = report.observations.flatMap((o) => o.findings)
return {
observations: report.observations.length,
zones: zones.length,
unresolvedZones: zones.filter((z) => z.unresolved).length,
findings: findings.length,
unresolvedFindings: findings.filter((f) => f.unresolved).length,
}
}
/** The envelope line: present only when the attachment was an archive. */
function archiveLine(outcome: ArchiveReadOutcome): string[] {
if (outcome.archive) return ['archive v1 (snapshot kept)']
if (outcome.snapshotRejected) {
return [`archive v1 (snapshot rejected: ${esc(outcome.snapshotRejected)})`]
}
return []
}
function headerLines(
source: 'v2' | 'v3',
outcome: ArchiveReadOutcome,
sheet: SheetIndex,
opts: CompareOptions,
): string[] {
const { report } = outcome
const ref = sheet.sheet.ref
const sameSheet =
report.sheet.sheetId === ref.sheetId &&
report.sheet.documentSha256 === ref.documentSha256
const sheetLine = sameSheet
? `sheet ${esc(ref.sheetId)} (${sheet.sheet.status}, matches the bundled sheet)`
: `sheet ${esc(report.sheet.sheetId)} !! written on another sheet document (sha ${esc(report.sheet.documentSha256.slice(0, 12))}…)`
const c = countsOf(report)
const lines = [
source === 'v2' ? 'v2 → v3 (migrated)' : 'v3 (read as is)',
...archiveLine(outcome),
sheetLine,
`id ${esc(report.id)} · date ${esc(report.date)} · ${c.observations} observations · ${c.zones} zones (${c.unresolvedZones} unresolved) · ${c.findings} findings (${c.unresolvedFindings} unresolved)`,
]
if (opts.full) {
lines.push(
`practitioner ${q(report.practitioner.name)} · animal ${q(report.animal.name)} · owner ${q(report.owner.name)}`,
)
}
return lines
}
function footerLines(report: Report, full: boolean): string[] {
const appointment = report.nextAppointment
return [
...fieldLine('conclusion', report.conclusion, full),
...fieldLine('recommendations', report.recommendations, full),
...(appointment
? [
full
? `next appointment ${esc(JSON.stringify(appointment))}`
: `next appointment (${appointment.kind})`,
]
: []),
]
}
/**
* `raw` is the attachment as found in the PDF (bare report or envelope),
* `outcome` its layered reading (`readArchiveDocument`); `outcome.migrated`
* tells which vocabulary the lines use.
*/
export function compareReport(
raw: unknown,
outcome: ArchiveReadOutcome,
sheet: SheetIndex,
opts: CompareOptions,
): Comparison {
const { report, migrated } = outcome
const source = migrated ? 'v2' : 'v3'
const v3Lines = report.observations.map((o) =>
observationLines(o, sheet, opts),
)
// Same privacy default as the listing: texts are compared with `--full`.
const normalized = [
...report.observations.flatMap((o) => observationLines(o, sheet, opts)),
...footerLines(report, opts.full),
]
return {
source,
header: headerLines(source, outcome, sheet, opts),
observations: migrated
? migratedObservationLines(raw, report, sheet, opts)
: v3Lines,
footer: footerLines(report, opts.full),
normalized,
counts: countsOf(report),
}
}
export function renderComparison(name: string, c: Comparison): string[] {
return [
`== ${name}`,
...c.header.map((l) => ` ${l}`),
...c.observations.flatMap((lines) =>
lines.map((l, i) => (i === 0 ? ` ${l}` : ` ${l}`)),
),
...c.footer.map((l) => ` ${l}`),
]
}
export function renderSummary(name: string, c: Comparison): string {
const n = c.counts
return `${name} · ${c.source === 'v2' ? 'v2→v3' : 'v3'} · ${n.observations} obs · zones ${n.zones}/${n.unresolvedZones} unresolved · findings ${n.findings}/${n.unresolvedFindings} unresolved`
}
/** Lines of A absent from B and lines of B absent from A, in order. */
export function diffLines(a: string[], b: string[]): string[] {
const inB = new Set(b)
const inA = new Set(a)
return [
...a.filter((l) => !inB.has(l)).map((l) => `- ${l}`),
...b.filter((l) => !inA.has(l)).map((l) => `+ ${l}`),
]
}
export interface CliArgs extends CompareOptions {
files: string[]
summary: boolean
diff: boolean
}
export function parseArgs(argv: string[]): CliArgs {
const args: CliArgs = {
files: [],
locale: 'fr',
full: false,
summary: false,
diff: false,
}
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i]!
if (arg === '--full') args.full = true
else if (arg === '--summary') args.summary = true
else if (arg === '--diff') args.diff = true
else if (arg === '--locale') {
const value = argv[++i]
if (value !== 'fr' && value !== 'en') {
throw new Error('--locale takes fr or en')
}
args.locale = value
} else if (arg.startsWith('--'))
throw new Error(`unknown option ${esc(arg)}`)
else args.files.push(arg)
}
return args
}
-45
View File
@@ -1,45 +0,0 @@
import {
AnatomicalSheetDocumentSchema,
buildSheetIndex,
ReportMigrationMapSchema,
type AnatomicalSheetDocument,
type ReportMigrationMap,
type SheetIndex,
type SheetRef,
} from '@faunosteo/domain'
/**
* The reference sheet as the archive check tool reads it: the frozen TypeScript domain
* (Zod schemas and index), as the application did before R2. The tool moves to the Rust
* core with the PDF reader at R4 (RUST_ARCHITECTURE_REVIEW VI.4); until then it keeps its
* own reading, independent of the application's core runtime.
*/
export interface CompareSheet {
status: 'draft' | 'published'
ref: SheetRef
document: AnatomicalSheetDocument
assets: Readonly<Record<string, string>>
migrationMap: ReportMigrationMap
}
export type CompareSheetIndex = SheetIndex<CompareSheet>
/** The seed files of the reference sheet, parsed and indexed. */
export function compareSheetIndex(seed: {
ref: { sheet_id: string; version_id: string | null; document_sha256: string }
document: unknown
migrationMap: unknown
}): CompareSheetIndex {
return buildSheetIndex({
status: 'draft',
ref: {
sheetId: seed.ref.sheet_id,
versionId: seed.ref.version_id,
documentSha256: seed.ref.document_sha256,
},
document: AnatomicalSheetDocumentSchema.parse(seed.document),
assets: {},
migrationMap: ReportMigrationMapSchema.parse(seed.migrationMap),
})
}
+17 -6
View File
@@ -34,8 +34,10 @@ import { pickLabel } from '@/i18n/pickLocaleLabel'
import type { ViewStates } from '@/anatomy/drawing'
import { exportReportToPdf } from '@/pdf/export'
import { downloadBlob } from '@/lib/download'
import type { ExportWarning } from '@faunosteo/pdf'
import type { RebaseOutcome } from '@faunosteo/core-wasm/types'
import type {
ExportWarning,
RebaseOutcome,
} from '@faunosteo/core-wasm/types'
import { useT } from '@/i18n/useT'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { coreFailureMessage } from '@/core/failure'
@@ -95,6 +97,8 @@ export default function EditorRoute() {
const heldAttempt = useRef<number | null>(null)
const [disclaimer, setDisclaimer] = useState<string | null>(null)
const [exporting, setExporting] = useState(false)
// Leaving the editor mid-export cancels it: the core's session is freed, no file results.
const exportAbort = useRef<AbortController | null>(null)
const [editDraft, setEditDraft] = useState<Identity | null>(null)
// One alert per restore, even if the effect runs again before the re-render.
const rebaseAlerted = useRef(false)
@@ -103,6 +107,10 @@ export default function EditorRoute() {
window.scrollTo({ top: 0, left: 0, behavior: 'auto' })
}, [])
useEffect(() => {
return () => exportAbort.current?.abort()
}, [])
// No report in memory: restore the per-tab draft once the sheet is known.
// A draft rebased on another sheet is announced with its unresolved count,
// an unreadable one is set aside. While the core cannot run, nothing is
@@ -233,14 +241,14 @@ export default function EditorRoute() {
async function onExport(index: SheetIndex) {
if (!report) return
setExporting(true)
const abort = new AbortController()
exportAbort.current = abort
try {
const { pdf, warnings } = await exportReportToPdf(report, index, {
locale,
signal: abort.signal,
})
downloadBlob(
new Blob([pdf as BlobPart], { type: 'application/pdf' }),
`bilan-${report.animal.name}-${report.date}.pdf`,
)
downloadBlob(pdf, `bilan-${report.animal.name}-${report.date}.pdf`)
const missing = missingItemsOf(warnings)
if (missing.length) {
window.alert(
@@ -248,9 +256,12 @@ export default function EditorRoute() {
)
}
} catch (err) {
// A cancelled export (the editor left) ends silently.
if (abort.signal.aborted) return
console.error('PDF export failed', err)
window.alert(coreFailureMessage(t, 'editor.export_failed'))
} finally {
if (exportAbort.current === abort) exportAbort.current = null
setExporting(false)
}
}
+74 -35
View File
@@ -1,5 +1,5 @@
import { useNavigate } from 'react-router-dom'
import { useRef, useState } from 'react'
import { useEffect, useRef, useState } from 'react'
import type {
ArchiveReadOutcome,
RebaseOutcome,
@@ -10,21 +10,23 @@ import { CoreStoppedBanner } from '@/components/report/CoreStoppedNotice'
import ReplaceSessionDialog from '@/components/report/ReplaceSessionDialog'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import {
importAttachment,
ImportError,
MAX_ATTACHMENT_BYTES,
MAX_PDF_BYTES,
readAttachment,
readRescueCopy,
} from '@/pdf/import'
import { coreRuntime, coreStopped } from '@/core/runtime'
import type { ImportSettlement } from '@/core/worker/client'
import { cancelImport, startImport } from '@/core/worker/controller'
import { MAX_COPY_BYTES, MAX_PDF_BYTES } from '@/core/worker/handler'
import { copyRestoreOf, ImportError, pdfImportOf } from '@/core/worker/outcome'
import type { ImportTaskKind } from '@/core/worker/protocol'
import {
isSessionInProgress,
useReportStore,
type ImportedSession,
} from '@/state/reportStore'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadSheetIndex, useSheetAvailability } from '@/sheets/useSheet'
import {
loadSheetBundleText,
loadSheetIndex,
useSheetAvailability,
} from '@/sheets/useSheet'
import { DEFAULT_SPECIES_ID } from './NewReportRoute'
import { useT } from '@/i18n/useT'
import { coreFailureMessage } from '@/core/failure'
@@ -119,6 +121,8 @@ function importErrorMessage(err: unknown, t: Translate): string {
return t('home.import.error_invalid_copy')
case 'core_unavailable':
return coreFailureMessage(t, 'home.import.error_core_unavailable')
case 'generic':
return t('home.import.error_generic')
}
}
@@ -143,20 +147,39 @@ function firstContentByte(head: Uint8Array): number | undefined {
* is JSON (an object) or is named as such; anything else goes the PDF path and its error.
*/
function isRescueCopy(file: File, head: Uint8Array): boolean {
const start = new TextDecoder('latin1').decode(head.slice(0, PDF_MAGIC.length))
const start = new TextDecoder('latin1').decode(
head.slice(0, PDF_MAGIC.length),
)
if (start === PDF_MAGIC) return false
if (firstContentByte(head) === 0x7b) return true
return file.name.toLowerCase().endsWith('.json') || file.type === 'application/json'
return (
file.name.toLowerCase().endsWith('.json') ||
file.type === 'application/json'
)
}
/** The copy's text, refused (never altered) when it is over the cap or not valid UTF-8. */
async function readCopyText(file: File): Promise<string> {
if (file.size > MAX_ATTACHMENT_BYTES) throw new ImportError('invalid_copy')
try {
return new TextDecoder('utf-8', { fatal: true }).decode(await file.arrayBuffer())
} catch {
throw new ImportError('invalid_copy')
/**
* One task in the disposable import worker (R4.3, plan §B.1.5): the page refuses up front
* when its own engine stopped, hands the file (never read here), the sheet payload and
* its compiled module to the worker, and reads the settlement. Diagnostics in DEV only.
*/
async function runImportTask(
task: ImportTaskKind,
file: File,
): Promise<ImportSettlement> {
if (coreStopped()) throw new ImportError('core_unavailable')
const sheet = await loadSheetBundleText(DEFAULT_SPECIES_ID)
if (!sheet) throw new ImportError('core_unavailable')
const module = await (
coreRuntime().compiledModule() ?? Promise.resolve(null)
).catch(() => null)
const settlement = await startImport({ task, file, sheet, module })
// Diagnostics only (never the outcome: it holds the bilan's names), DEV console only.
if (import.meta.env.DEV) {
const diag = settlement.kind === 'result' ? settlement.diag : settlement
console.debug('[import]', task, diag)
}
return settlement
}
export default function HomeRoute() {
@@ -169,48 +192,64 @@ export default function HomeRoute() {
const [busy, setBusy] = useState(false)
const [confirmingReplace, setConfirmingReplace] = useState(false)
const t = useT()
// Leaving Home cancels a running import: its worker is terminated, its result dropped.
useEffect(() => cancelImport, [])
/** A Faunosteo PDF: its attachment, read and rebased by the core on the loaded sheet. */
async function readPdf(file: File): Promise<ImportRead> {
// The engine refuses the same size; checking first keeps a huge file out of memory.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const bytes = new Uint8Array(await file.arrayBuffer())
const attachment = await readAttachment(bytes)
/** The page's own index, loaded after the worker accepted the file, for `hydrateImport`. */
async function mainIndex(): Promise<SheetIndex> {
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) throw new ImportError('core_unavailable')
const { read: outcome, rebase } = importAttachment(attachment, index)
return index
}
/** A Faunosteo PDF: its attachment, read and rebased by the worker's core on the sheet. */
async function readPdf(file: File): Promise<ImportRead> {
// The worker and the core refuse the same size; checking first reads nothing.
if (file.size > MAX_PDF_BYTES) throw new ImportError('invalid_pdf')
const { read: outcome, rebase } = pdfImportOf(
await runImportTask('pdf', file),
)
return {
session: { report: rebase.report, archive: outcome.archive },
index,
index: await mainIndex(),
lines: importMessages(outcome, rebase, t),
}
}
/** A rescue copy: read before any session change, so a refusal leaves the tab untouched. */
async function readCopy(file: File): Promise<ImportRead> {
const text = await readCopyText(file)
const index = await loadSheetIndex(DEFAULT_SPECIES_ID)
if (!index) throw new ImportError('core_unavailable')
const rebase = readRescueCopy(text, index)
if (file.size > MAX_COPY_BYTES) throw new ImportError('invalid_copy')
const { rebase } = copyRestoreOf(await runImportTask('copy', file))
const count = String(rebase.unresolvedZones + rebase.unresolvedFindings)
return {
session: { report: rebase.report, archive: null },
index,
lines: rebase.rebased ? [t('editor.draft_rebased').replace('{count}', count)] : [],
index: await mainIndex(),
lines: rebase.rebased
? [t('editor.draft_rebased').replace('{count}', count)]
: [],
}
}
/** Read, rebase onto the loaded sheet, open; the editor always works on that sheet. */
async function importFile(file: File) {
const head = new Uint8Array(await file.slice(0, SNIFF_BYTES).arrayBuffer())
const read = isRescueCopy(file, head) ? await readCopy(file) : await readPdf(file)
const reportAtPick = useReportStore.getState().report
const read = isRescueCopy(file, head)
? await readCopy(file)
: await readPdf(file)
// The session changed under the import (another tab action): its result is dropped.
if (useReportStore.getState().report !== reportAtPick) return
const opened = hydrateImport(read.session, read.index)
// A tab text that could not be set aside would be overwritten: resolve it first.
if (!opened.ok) {
// A core failure reading the tab's draft is an engine error, not a held text.
if (opened.reason !== 'held') throw new ImportError('core_unavailable')
window.alert(
t(opened.engine ? 'session.held_blocked_engine' : 'session.held_blocked'),
t(
opened.engine
? 'session.held_blocked_engine'
: 'session.held_blocked',
),
)
navigate('/editor')
return
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

+17 -8
View File
@@ -10,20 +10,29 @@ export function absoluteUrl(path: string): string {
/** Sentinel origin: anything that resolves elsewhere is not a path. */
const PROBE_ORIGIN = 'http://next.invalid'
/** The value parsed against the sentinel origin, or null when it escapes it. */
function probe(value: string): URL | null {
try {
const url = new URL(value, PROBE_ORIGIN)
return url.origin === PROBE_ORIGIN ? url : null
} catch {
return null
}
}
/**
* The `next` query value is only honoured when it is a same-origin path.
* Resolving it against a sentinel origin catches every escape the URL
* parser knows (scheme, `//host`, `/\host`, tab/newline-stripped forms);
* the returned value is rebuilt from the parsed parts, never the raw string.
* Normalisation can itself produce `//host` (`/..//host`, `/%2e%2e//host`),
* so the rebuilt value must survive the same test as an internal path.
*/
export function safeNextPath(raw: string | null, fallback = APP_HOME_PATH) {
if (!raw || !raw.startsWith('/')) return fallback
let url: URL
try {
url = new URL(raw, PROBE_ORIGIN)
} catch {
return fallback
}
if (url.origin !== PROBE_ORIGIN) return fallback
return url.pathname + url.search + url.hash
const url = probe(raw)
if (!url) return fallback
const path = url.pathname + url.search + url.hash
if (path.startsWith('//') || !probe(path)) return fallback
return path
}
+4 -1
View File
@@ -1,6 +1,9 @@
import { useConfig } from '@/app/providers/ConfigProvider'
import { useT } from '@/i18n/useT'
import pawsInHarmonyUrl from '@/assets/brand/paws-in-harmony.svg?url'
// Bundled copy of zenquality.fr/assets/logo-horizontal-1024.png: the
// production CSP (`img-src 'self' data: blob:`) refuses an external image.
import zenQualityUrl from '@/assets/brand/zenquality-logo-horizontal.png?url'
export default function Footer() {
const cfg = useConfig()
@@ -22,7 +25,7 @@ export default function Footer() {
className="inline-flex items-center"
>
<img
src="https://zenquality.fr/assets/logo-horizontal-1024.png"
src={zenQualityUrl}
alt="ZenQuality"
className="h-6 w-auto"
loading="lazy"
+228
View File
@@ -0,0 +1,228 @@
import {
isWorkerMessage,
PROTOCOL_VERSION,
type ImportDiag,
type ImportTaskKind,
type WorkerMessage,
} from './protocol'
import { CHUNK_BYTES, chunkSource, type ChunkSource } from './reader'
import { PausableTimer, type Visibility, documentVisibility } from './timers'
/**
* The page side of one import (R4.3, plan §B.1.5 items 1, 3 and 5): creates the worker
* in a try/catch (a `SecurityError` is synchronous), installs the listeners before posting,
* arms the start timer until `ready` then the task timer, feeds the file chunk by chunk
* (one travelling buffer, each chunk acknowledged before the next), settles once on the
* first of `result`, `failed`, an `error` event, a read failure, a timer, or a cancel, and
* terminates the worker in every case. Everything after the first settlement is ignored.
*/
/** What `new Worker(…)` gives, narrowed to what the client uses (a test fake fits). */
export interface WorkerLike {
postMessage(message: unknown, transfer?: Transferable[]): void
terminate(): void
onmessage: ((event: MessageEvent) => void) | null
onerror: ((event: ErrorEvent) => void) | null
onmessageerror: ((event: MessageEvent) => void) | null
}
export interface ImportTaskInput {
task: ImportTaskKind
file: File
sheet: string
module: WebAssembly.Module | null
}
/**
* `worker_unavailable`: the worker could not be created, failed before `ready`, or did not
* answer `ready` in time; `crashed`: a trap or an `error` event during the task;
* `timeout`: the task timer; `read`: the file could not be read; `engine`: the module
* refused the sheet or failed otherwise during the task; `cancelled`: the page gave up.
*/
export type ImportFailureReason =
| 'worker_unavailable'
| 'crashed'
| 'timeout'
| 'read'
| 'engine'
| 'cancelled'
export type ImportSettlement =
| { kind: 'result'; out: string; diag: ImportDiag }
| { kind: 'failed'; reason: ImportFailureReason; detail: string }
export interface ImportClientOptions {
spawn: () => WorkerLike
/** Until `ready`: the module's fetch, compile and instantiation. */
startTimeoutMs: number
/** From `ready` to the result (plan §B.3: 20 s hypothesis, set at J1). */
taskTimeoutMs: number
visibility?: Visibility
/** Test seam: the file's chunks. */
source?: (file: File) => ChunkSource
}
export interface ImportRun {
settled: Promise<ImportSettlement>
/** Terminates the worker and settles `cancelled` unless already settled. */
cancel(): void
}
/** The failure reason of a `failed` message, per §B.1.8. */
function reasonOf(phase: 'start' | 'task', kind: string): ImportFailureReason {
if (phase === 'start') return 'worker_unavailable'
if (kind === 'trap') return 'crashed'
if (kind === 'read') return 'read'
return 'engine'
}
/** One import's moving parts, settled once. */
class ImportClient {
private worker: WorkerLike | null = null
private timer: PausableTimer | null = null
private source: ChunkSource | null = null
private awaitingAck: ((bytes: ArrayBuffer) => void) | null = null
private ready = false
private done = false
private resolve!: (settlement: ImportSettlement) => void
readonly settled = new Promise<ImportSettlement>((resolve) => {
this.resolve = resolve
})
constructor(
private readonly input: ImportTaskInput,
private readonly options: ImportClientOptions,
) {}
start(): void {
try {
this.worker = this.options.spawn()
} catch (error) {
this.fail(
'worker_unavailable',
error instanceof Error ? error.name : 'spawn failed',
)
return
}
this.worker.onmessage = (event) => this.onMessage(event.data)
// An `error` event is never masked: it settles the import (and reaches the console).
this.worker.onerror = (event) =>
this.fail(this.ready ? 'crashed' : 'worker_unavailable', event.message)
this.worker.onmessageerror = () =>
this.fail(this.ready ? 'engine' : 'worker_unavailable', 'messageerror')
this.arm(this.options.startTimeoutMs, 'worker_unavailable')
const { task, file, sheet, module } = this.input
try {
this.worker.postMessage({
v: PROTOCOL_VERSION,
type: 'task',
task,
size: file.size,
sheet,
module,
})
} catch (error) {
// A clone the engine refuses (the Module, say) must not leave an orphan worker.
this.fail(
'worker_unavailable',
error instanceof Error ? error.name : 'post failed',
)
}
}
cancel(): void {
this.fail('cancelled', 'cancelled')
}
private onMessage(data: unknown): void {
if (this.done || !isWorkerMessage(data)) return
this.dispatch(data)
}
private dispatch(message: WorkerMessage): void {
switch (message.type) {
case 'ready':
if (this.ready) return
this.ready = true
this.arm(this.options.taskTimeoutMs, 'timeout')
void this.feed()
return
case 'ack':
this.awaitingAck?.(message.bytes)
this.awaitingAck = null
return
case 'result':
this.settle({ kind: 'result', out: message.out, diag: message.diag })
return
case 'failed':
this.fail(reasonOf(message.phase, message.kind), message.detail)
}
}
/** Reads the file chunk by chunk into one buffer the worker hands back after each. */
private async feed(): Promise<void> {
this.source = (this.options.source ?? chunkSource)(this.input.file)
let buffer = new ArrayBuffer(CHUNK_BYTES)
try {
for (;;) {
const chunk = await this.source.next(buffer)
if (this.done) return
if (chunk === null) break
buffer = await this.send(chunk.bytes, chunk.length)
if (this.done) return
}
this.worker?.postMessage({ v: PROTOCOL_VERSION, type: 'end' })
} catch (error) {
this.fail(
'read',
error instanceof Error ? `${error.name}: ${error.message}` : 'read',
)
}
}
/** Posts a chunk (transferred) and resolves with its buffer once acknowledged. */
private send(bytes: ArrayBuffer, length: number): Promise<ArrayBuffer> {
return new Promise((resolve) => {
this.awaitingAck = resolve
this.worker?.postMessage(
{ v: PROTOCOL_VERSION, type: 'chunk', bytes, length },
[bytes],
)
})
}
private arm(ms: number, reason: ImportFailureReason): void {
this.timer?.clear()
const visibility = this.options.visibility ?? documentVisibility
this.timer = new PausableTimer(
ms,
() => this.fail(reason, `${reason} after ${ms} ms`),
visibility,
)
}
private fail(reason: ImportFailureReason, detail: string): void {
this.settle({ kind: 'failed', reason, detail })
}
private settle(settlement: ImportSettlement): void {
if (this.done) return
this.done = true
this.timer?.clear()
this.timer = null
this.worker?.terminate()
this.worker = null
void this.source?.cancel()
this.source = null
this.resolve(settlement)
}
}
export function runImportTask(
input: ImportTaskInput,
options: ImportClientOptions,
): ImportRun {
const client = new ImportClient(input, options)
client.start()
return { settled: client.settled, cancel: () => client.cancel() }
}
+72
View File
@@ -0,0 +1,72 @@
import workerUrl from './import.worker?worker&url'
import {
runImportTask,
type ImportRun,
type ImportSettlement,
type ImportTaskInput,
} from './client'
import type { WorkerLike } from './client'
/**
* One import at a time for the page (R4.3, plan §B.1.5 items 6 and 7): a new start
* cancels the running one, leaving Home cancels it, and the worker script is prefetched
* once the editor has loaded the engine so that a later offline import can start.
*/
/** Until `ready`: a cold fetch, compile and instantiation on a slow device. */
export const IMPORT_START_TIMEOUT_MS = 10_000
/** From `ready` to the result (plan §B.3: 20 s hypothesis, confirmed or moved at J1). */
export const IMPORT_TIMEOUT_MS = 20_000
type Spawn = () => WorkerLike
const spawnWorker: Spawn = () =>
new Worker(workerUrl, { type: 'module', name: 'faunosteo-import' })
let spawn: Spawn = spawnWorker
let running: ImportRun | null = null
let prefetched = false
/** Starts an import; a running one is cancelled first (its result dropped). */
export function startImport(input: ImportTaskInput): Promise<ImportSettlement> {
running?.cancel()
const run = runImportTask(input, {
spawn,
startTimeoutMs: IMPORT_START_TIMEOUT_MS,
taskTimeoutMs: IMPORT_TIMEOUT_MS,
})
running = run
void run.settled.then(() => {
if (running === run) running = null
})
return run.settled
}
/** Cancels the running import, if any (leaving Home, a second pick). */
export function cancelImport(): void {
running?.cancel()
running = null
}
/**
* Warms the HTTP cache with the worker chunk (an immutable `/assets/` file) so that an
* import works offline once the editor has loaded the engine, as it does today. Best
* effort: a failure changes nothing.
*/
export function prefetchImportWorker(): void {
if (
prefetched ||
typeof Worker === 'undefined' ||
typeof fetch !== 'function'
)
return
prefetched = true
fetch(workerUrl, { credentials: 'same-origin' })
.then((response) => response.body?.cancel())
.catch(() => undefined)
}
/** Test seam: run the worker logic in-process instead of a real `Worker`. */
export function setImportWorkerSpawn(next: Spawn | null): void {
spawn = next ?? spawnWorker
}
+172
View File
@@ -0,0 +1,172 @@
import type { GlueFileBytes, GlueSheetHandle } from '@faunosteo/core-wasm'
import { closedRefusal } from '@faunosteo/core-wasm'
import {
describeError,
failureKindOf,
isPageMessage,
PROTOCOL_VERSION,
type ChunkMessage,
type ImportTaskMessage,
type WorkerFailurePhase,
type WorkerMessage,
} from './protocol'
/**
* The import worker's logic (R4.3, plan §B.1.5 items 2 and 4), apart from the worker
* global so that vitest runs it in-process on the Node module: the engine is injected.
* One task per worker: instantiate, answer `ready`, build the sheet handle, sink the
* chunks the page reads (one copy, in the module's memory), run the core on `end`, answer
* `result`; every throwable becomes one `failed` with its phase and kind.
*/
/** What the glue gives once instantiated. */
export interface WorkerEngine {
SheetHandle: new (bundle: string) => GlueSheetHandle
FileBytes: new (expected: number) => GlueFileBytes
/** The instance's linear memory, for the diag. */
memory: WebAssembly.Memory | null
}
export type EngineLoader = (
module: WebAssembly.Module | null,
) => Promise<WorkerEngine>
/** The caps the worker checks before reserving a byte (the core and the sink enforce them too). */
export const MAX_PDF_BYTES = 50 * 1024 * 1024
export const MAX_COPY_BYTES = 16 * 1024 * 1024
export type Post = (message: WorkerMessage, transfer?: Transferable[]) => void
/** The core's failure envelope, for the caps the worker applies itself. */
function refusal(kind: string, detail: string): string {
return JSON.stringify({ ok: false, kind, detail })
}
/** The sheet handle, or an error named `SheetRefused` carrying the module's refusal. */
function sheetHandle(engine: WorkerEngine, sheet: string): GlueSheetHandle {
try {
return new engine.SheetHandle(sheet)
} catch (error) {
const detail = closedRefusal(error)
if (detail === null) throw error
const refused = new Error(detail)
refused.name = 'SheetRefused'
throw refused
}
}
/** One task's state, from the task message to its settlement. */
class ImportTask {
private engine: WorkerEngine | null = null
private handle: GlueSheetHandle | null = null
private sink: GlueFileBytes | null = null
private chunks = 0
private settled = false
private readonly started = performance.now()
constructor(
private readonly task: ImportTaskMessage,
private readonly load: EngineLoader,
private readonly post: Post,
) {}
/** Instantiates, answers `ready`, reserves the sink; a cap refusal settles at once. */
async start(): Promise<void> {
let phase: WorkerFailurePhase = 'start'
try {
this.engine = await this.load(this.task.module)
this.post({ v: PROTOCOL_VERSION, type: 'ready' })
phase = 'task'
this.handle = sheetHandle(this.engine, this.task.sheet)
const cap = this.task.task === 'pdf' ? MAX_PDF_BYTES : MAX_COPY_BYTES
if (this.task.size > cap) {
this.result(refusal(this.kind(), 'over the size cap'))
return
}
this.sink = new this.engine.FileBytes(this.task.size)
} catch (error) {
this.fail(phase, error)
}
}
/** Sinks one chunk and hands its buffer back; a refused push means the size changed. */
chunk(message: ChunkMessage): void {
if (this.settled || !this.sink) return
const view = new Uint8Array(message.bytes, 0, message.length)
if (!this.sink.push(view)) {
this.sink.free()
this.sink = null
this.result(refusal(this.kind(), 'size changed while reading'))
return
}
this.chunks += 1
this.post({ v: PROTOCOL_VERSION, type: 'ack', bytes: message.bytes }, [
message.bytes,
])
}
/** Runs the core on the gathered bytes. */
end(): void {
if (this.settled || !this.sink || !this.handle) return
try {
const sink = this.sink
this.sink = null
const out =
this.task.task === 'pdf'
? this.handle.import_pdf_bytes(sink)
: this.handle.restore_copy_bytes(sink)
this.result(out)
} catch (error) {
this.fail('task', error)
}
}
private kind(): string {
return this.task.task === 'pdf' ? 'invalid_pdf' : 'invalid'
}
private result(out: string): void {
this.settled = true
const linearBytes = this.engine?.memory?.buffer.byteLength ?? null
const diag = {
ms: performance.now() - this.started,
linearBytes,
chunks: this.chunks,
}
this.post({ v: PROTOCOL_VERSION, type: 'result', out, diag })
}
private fail(phase: WorkerFailurePhase, error: unknown): void {
this.settled = true
this.post({
v: PROTOCOL_VERSION,
type: 'failed',
phase,
kind: failureKindOf(error),
detail: describeError(error),
})
}
}
/**
* The handler of the page's messages: `load` instantiates the module (the posted one, or
* fetched), `post` sends the answers. Messages outside the protocol are ignored.
*/
export function createWorkerHandler(
load: EngineLoader,
post: Post,
): (data: unknown) => Promise<void> {
let task: ImportTask | null = null
return async (data) => {
if (!isPageMessage(data)) return
if (data.type === 'task') {
if (task) return
task = new ImportTask(data, load, post)
await task.start()
} else if (data.type === 'chunk') {
task?.chunk(data)
} else {
task?.end()
}
}
}
+46
View File
@@ -0,0 +1,46 @@
/// <reference lib="webworker" />
import init, {
FileBytes,
SheetHandle,
} from '@faunosteo/core-wasm/pkg/faunosteo_wasm.js'
import wasmUrl from '@faunosteo/core-wasm/pkg/faunosteo_wasm_bg.wasm?url'
import { createWorkerHandler, type WorkerEngine } from './handler'
import { describeError, PROTOCOL_VERSION } from './protocol'
/**
* The import worker entry (R4.3, plan §B.1.5 item 2): the glue is imported statically and
* bundled into this chunk (a same-origin hashed asset the production CSP allows, no
* `import()`, no recovery logic); the module is the compiled one the page posts, else the
* asset fetched here. The listener is installed before any await; the whole life runs
* inside the handler's try/catch, with `unhandledrejection` as a backstop: every throwable
* reaches the page as one `failed` message. The page terminates the worker in every case.
*/
const scope = self as unknown as DedicatedWorkerGlobalScope
const loadEngine = async (
module: WebAssembly.Module | null,
): Promise<WorkerEngine> => {
const exports = (await init({ module_or_path: module ?? wasmUrl })) as {
memory?: WebAssembly.Memory
}
return { SheetHandle, FileBytes, memory: exports.memory ?? null }
}
const handle = createWorkerHandler(loadEngine, (message, transfer = []) =>
scope.postMessage(message, transfer),
)
scope.onmessage = (event: MessageEvent<unknown>) => {
void handle(event.data)
}
scope.onunhandledrejection = (event: PromiseRejectionEvent) => {
scope.postMessage({
v: PROTOCOL_VERSION,
type: 'failed',
phase: 'task',
kind: 'other',
detail: describeError(event.reason),
})
}
+115
View File
@@ -0,0 +1,115 @@
import type { ArchiveImport, DraftRestore } from '@faunosteo/core-wasm/types'
import type { ImportSettlement, ImportTaskInput } from './client'
/**
* What the import worker's settlement means for the page (R4.3, plan §B.1.8): the core's
* outcome envelope mapped to the page's import error kinds, and the worker's own failures
* classified so that a technical error, a resource overflow or a timeout is never shown as
* a corrupt PDF (OD-5: `generic` for a PDF crash or timeout, `core_unavailable` for a copy).
*/
export type ImportErrorKind =
| 'invalid_pdf'
| 'no_attachment'
| 'attachment_stripped'
| 'incompatible_version'
| 'lone_surrogate'
| 'invalid_copy'
| 'core_unavailable'
| 'generic'
export class ImportError extends Error {
constructor(
readonly kind: ImportErrorKind,
/** The report version found, for `incompatible_version`. */
readonly foundVersion: number | null = null,
/** The technical reason, for the DEV console only. */
readonly detail = '',
) {
super(kind)
this.name = 'ImportError'
}
}
interface Envelope<T> {
ok: boolean
value?: T
kind?: string
found?: number
detail?: string
}
/** The envelope text, or `core_unavailable` when it is not one (never a trusted shape). */
function parseEnvelope<T>(out: string): Envelope<T> {
try {
const parsed: unknown = JSON.parse(out)
if (typeof parsed === 'object' && parsed !== null && 'ok' in parsed) {
return parsed as Envelope<T>
}
} catch {
// Not JSON: the module answered garbage, treated as an engine failure below.
}
throw new ImportError('core_unavailable', null, 'unreadable envelope')
}
/** `SheetHandle.import_pdf` failures, one to one with today's kinds. */
function pdfError(envelope: Envelope<unknown>): ImportError {
switch (envelope.kind) {
case 'invalid_pdf':
case 'no_attachment':
case 'attachment_stripped':
case 'lone_surrogate':
return new ImportError(envelope.kind, null, envelope.detail)
case 'incompatible_version':
return new ImportError('incompatible_version', envelope.found ?? null)
case 'invalid':
// The rebase refused the loaded sheet's reference: today's generic message.
return new ImportError('generic', null, envelope.detail)
default:
return new ImportError('core_unavailable', null, envelope.detail)
}
}
/** Kinds that mean the copy itself cannot be read (`reportStore.UNREADABLE_DRAFT_KINDS`). */
const UNREADABLE_COPY = new Set([
'invalid',
'unsupported_version',
'lone_surrogate',
])
function copyError(envelope: Envelope<unknown>): ImportError {
if (UNREADABLE_COPY.has(envelope.kind ?? '')) {
return new ImportError('invalid_copy', null, envelope.detail)
}
return new ImportError('core_unavailable', null, envelope.detail)
}
/** The worker's own failures, by task (OD-5). */
function workerError(
task: ImportTaskInput['task'],
settlement: ImportSettlement,
): ImportError {
if (settlement.kind !== 'failed') throw new Error('not a failure')
const { reason, detail } = settlement
if (reason === 'read') return new ImportError('generic', null, detail)
if (task === 'pdf' && (reason === 'crashed' || reason === 'timeout')) {
return new ImportError('generic', null, detail)
}
return new ImportError('core_unavailable', null, detail)
}
/** The imported archive, or the ImportError the page shows. */
export function pdfImportOf(settlement: ImportSettlement): ArchiveImport {
if (settlement.kind === 'failed') throw workerError('pdf', settlement)
const envelope = parseEnvelope<ArchiveImport>(settlement.out)
if (!envelope.ok || envelope.value === undefined) throw pdfError(envelope)
return envelope.value
}
/** The restored copy, or the ImportError the page shows. */
export function copyRestoreOf(settlement: ImportSettlement): DraftRestore {
if (settlement.kind === 'failed') throw workerError('copy', settlement)
const envelope = parseEnvelope<DraftRestore>(settlement.out)
if (!envelope.ok || envelope.value === undefined) throw copyError(envelope)
return envelope.value
}
+155
View File
@@ -0,0 +1,155 @@
/**
* Messages between the page and the import worker (R4.3, plan §B.1.5), tagged `v: 1`.
* The page posts one task, then the file chunk by chunk, then `end`; the worker answers
* `ready` once its instance runs, `ack` per chunk, then one `result` or one `failed`.
* Anything after the first settlement is ignored by the page.
*/
export const PROTOCOL_VERSION = 1
export type ImportTaskKind = 'pdf' | 'copy'
export interface ImportTaskMessage {
v: typeof PROTOCOL_VERSION
type: 'task'
task: ImportTaskKind
/** The picked file's size: the worker reserves it and refuses more. */
size: number
/** The bundled sheet payload text the page's runtime builds its handle from. */
sheet: string
/** The compiled module of the page's runtime when it holds one; else the worker fetches. */
module: WebAssembly.Module | null
}
/**
* One chunk of the file, read on the page's thread into a buffer the worker hands back
* with `ack` (both transferred, never copied): the page holds one chunk at a time, the
* worker's sink the only whole copy. Measured at R4.3a: reading a file inside a WebKit
* worker costs about 180 MiB whatever the method; read on the page and streamed, 106.
*/
export interface ChunkMessage {
v: typeof PROTOCOL_VERSION
type: 'chunk'
bytes: ArrayBuffer
length: number
}
/** The page read the whole file: the worker runs the core. */
export interface EndMessage {
v: typeof PROTOCOL_VERSION
type: 'end'
}
export type PageMessage = ImportTaskMessage | ChunkMessage | EndMessage
export interface WorkerReadyMessage {
v: typeof PROTOCOL_VERSION
type: 'ready'
}
/** The chunk is in the sink; its buffer comes back for the next read. */
export interface WorkerAckMessage {
v: typeof PROTOCOL_VERSION
type: 'ack'
bytes: ArrayBuffer
}
export interface WorkerResultMessage {
v: typeof PROTOCOL_VERSION
type: 'result'
/** The outcome envelope text of the core (`{"ok":true,…}` or `{"ok":false,"kind":…}`). */
out: string
diag: ImportDiag
}
/** Printed in DEV only, never sent anywhere. */
export interface ImportDiag {
ms: number
linearBytes: number | null
chunks: number
}
export type WorkerFailurePhase = 'start' | 'task'
/**
* `trap`: a `WebAssembly.RuntimeError`, or an engine stack overflow (`RangeError`,
* `InternalError`); `read`: the file could not be read; `sheet`: the bundled sheet was
* refused by the module; `other`: anything else (a glue or network failure at start).
*/
export type WorkerFailureKind = 'trap' | 'read' | 'sheet' | 'other'
export interface WorkerFailedMessage {
v: typeof PROTOCOL_VERSION
type: 'failed'
phase: WorkerFailurePhase
kind: WorkerFailureKind
/** Error name and first message line, for the DEV console only. */
detail: string
}
export type WorkerMessage =
| WorkerReadyMessage
| WorkerAckMessage
| WorkerResultMessage
| WorkerFailedMessage
const WORKER_TYPES = new Set(['ready', 'ack', 'result', 'failed'])
const PAGE_TYPES = new Set(['task', 'chunk', 'end'])
function ofProtocol(data: unknown, types: Set<string>): boolean {
if (typeof data !== 'object' || data === null) return false
const record = data as { v?: unknown; type?: unknown }
return (
record.v === PROTOCOL_VERSION &&
typeof record.type === 'string' &&
types.has(record.type)
)
}
/** True for a message of this protocol, from a worker of the same build. */
export function isWorkerMessage(data: unknown): data is WorkerMessage {
return ofProtocol(data, WORKER_TYPES)
}
/** True for a well-formed message of this protocol, from the page. */
export function isPageMessage(data: unknown): data is PageMessage {
if (!ofProtocol(data, PAGE_TYPES)) return false
const record = data as {
type: string
size?: unknown
bytes?: unknown
length?: unknown
}
if (record.type === 'task') return isByteCount(record.size)
if (record.type === 'chunk') {
return (
record.bytes instanceof ArrayBuffer &&
isByteCount(record.length) &&
(record.length as number) <= record.bytes.byteLength
)
}
return true
}
function isByteCount(value: unknown): boolean {
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
}
/** Error name and first message line, bounded, for a `failed` message. */
export function describeError(error: unknown): string {
const name = error instanceof Error ? error.name : 'Error'
const message = error instanceof Error ? error.message : String(error)
return `${name}: ${message}`.split('\n')[0]!.slice(0, 200)
}
/** The failure kind of a throwable, per §B.1.5 item 2. */
export function failureKindOf(error: unknown): WorkerFailureKind {
if (error instanceof WebAssembly.RuntimeError) return 'trap'
if (!(error instanceof Error)) return 'other'
if (error.name === 'RangeError' || error.name === 'InternalError')
return 'trap'
if (error.name === 'NotReadableError' || error.name === 'NotFoundError')
return 'read'
if (error.name === 'SheetRefused') return 'sheet'
return 'other'
}
+60
View File
@@ -0,0 +1,60 @@
/**
* The page's read of the picked file, one chunk at a time into a buffer that travels to
* the worker and back (R4.3a measurement: a file read inside a WebKit worker costs about
* 180 MiB whatever the method; read here, 106, and 14 on the page alone). A BYOB reader
* fills the buffer the worker handed back; without BYOB support (happy-dom), the default
* reader's chunks are copied into it. Nothing here parses a byte.
*/
export const CHUNK_BYTES = 1024 * 1024
export interface ChunkSource {
/** The next chunk's length in `buffer`, or null at the end; `buffer` is consumed. */
next(
buffer: ArrayBuffer,
): Promise<{ bytes: ArrayBuffer; length: number } | null>
cancel(): Promise<void>
}
type ByobReader = ReadableStreamBYOBReader
type DefaultReader = ReadableStreamDefaultReader<Uint8Array>
function byobSource(reader: ByobReader): ChunkSource {
return {
async next(buffer) {
const { done, value } = await reader.read(new Uint8Array(buffer))
if (done || !value) return null
return { bytes: value.buffer as ArrayBuffer, length: value.byteLength }
},
cancel: () => reader.cancel().catch(() => undefined),
}
}
/** The default reader's chunks copied into the travelling buffer, split when longer. */
function defaultSource(reader: DefaultReader): ChunkSource {
let pending: Uint8Array | null = null
return {
async next(buffer) {
if (!pending || pending.byteLength === 0) {
const { done, value } = await reader.read()
if (done || !value) return null
pending = value
}
const length = Math.min(pending.byteLength, buffer.byteLength)
new Uint8Array(buffer, 0, length).set(pending.subarray(0, length))
pending = pending.subarray(length)
return { bytes: buffer, length }
},
cancel: () => reader.cancel().catch(() => undefined),
}
}
/** A chunk source over `file`, BYOB when the engine offers it. */
export function chunkSource(file: File): ChunkSource {
const stream = file.stream()
try {
return byobSource(stream.getReader({ mode: 'byob' }))
} catch {
return defaultSource(stream.getReader())
}
}
+74
View File
@@ -0,0 +1,74 @@
/**
* A one-shot timer that stops counting while the page is hidden (R4.3, plan §B.1.5 item
* 3): a phone that backgrounds the tab must not time an import out on return. The
* visibility source is injected so tests drive it.
*/
export interface Visibility {
hidden(): boolean
/** Calls `listener` on every change; returns the unsubscribe function. */
onChange(listener: () => void): () => void
}
export const documentVisibility: Visibility = {
hidden: () =>
typeof document !== 'undefined' && document.visibilityState === 'hidden',
onChange: (listener) => {
if (typeof document === 'undefined') return () => {}
document.addEventListener('visibilitychange', listener)
return () => document.removeEventListener('visibilitychange', listener)
},
}
export class PausableTimer {
private remainingMs: number
private startedAt: number | null = null
private handle: ReturnType<typeof setTimeout> | null = null
private readonly unsubscribe: () => void
constructor(
durationMs: number,
private readonly onElapsed: () => void,
private readonly visibility: Visibility = documentVisibility,
private readonly now: () => number = () => performance.now(),
) {
this.remainingMs = durationMs
this.unsubscribe = visibility.onChange(() => this.sync())
this.sync()
}
/** Stops the timer for good; a timer never fires after it. */
clear(): void {
this.pause()
this.unsubscribe()
this.remainingMs = Number.POSITIVE_INFINITY
}
private sync(): void {
if (this.visibility.hidden()) this.pause()
else this.resume()
}
private resume(): void {
if (this.handle !== null || !Number.isFinite(this.remainingMs)) return
this.startedAt = this.now()
this.handle = setTimeout(() => {
this.handle = null
this.remainingMs = 0
this.unsubscribe()
this.onElapsed()
}, this.remainingMs)
}
private pause(): void {
if (this.handle === null) return
clearTimeout(this.handle)
this.handle = null
if (this.startedAt !== null) {
this.remainingMs = Math.max(
0,
this.remainingMs - (this.now() - this.startedAt),
)
}
}
}
+13 -6
View File
@@ -1,12 +1,19 @@
import type { Rasterizer } from '@faunosteo/pdf'
/**
* The browser side of the engine's rasterizer adapter: the engine has fixed
* the pixel size, this module only stamps it on the SVG root and lets the
* browser draw the SVG through an Image / canvas pair, which renders exactly
* what the practitioner sees in the inline anatomy canvas.
* The browser side of the core's raster requests (R4.6; the engine's adapter
* before): the core has fixed the pixel size, this module only stamps it on
* the SVG root and lets the browser draw the SVG through an Image / canvas
* pair, which renders exactly what the practitioner sees in the inline
* anatomy canvas.
*/
export interface RasterSize {
widthPx: number
heightPx: number
}
/** Draws `svg` at `size` as a PNG. */
export type Rasterizer = (svg: string, size: RasterSize) => Promise<Uint8Array>
const SVG_NS = 'http://www.w3.org/2000/svg'
const PNG_SIGNATURE = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
+159 -25
View File
@@ -1,33 +1,142 @@
import type { Report } from '@faunosteo/core-wasm/types'
import {
defaultPdfLabels,
exportReportArchive,
type ExportInput,
type ExportWarning,
} from '@faunosteo/pdf'
openExportSession,
type CoreExportSession,
type CoreOutcome,
} from '@faunosteo/core-wasm'
import type {
ExportInput,
ExportWarning,
RasterRequest,
Report,
} from '@faunosteo/core-wasm/types'
import { coreRuntime } from '@/core/runtime'
import type { Locale } from '@/i18n/types'
import type { SheetIndex } from '@/services/sheetIndex'
import { loadBranding } from './branding'
import { browserRasterizer } from './browserRasterizer'
import { defaultPdfLabels } from './labels'
export interface PdfExportOptions {
locale: Locale
/** Aborting frees the session (the editor leaving mid-export); no file results. */
signal?: AbortSignal
}
export interface PdfExportResult {
pdf: Uint8Array
/** Non-fatal engine warnings: a logo or a view that failed to embed. */
/** The file, from the parts the core handed out (never concatenated in memory). */
pdf: Blob
/** Non-fatal warnings: a logo or a view that failed to embed. */
warnings: ExportWarning[]
}
/** A core call the export could not go past: its closed kind, for the DEV console. */
export class ExportFailure extends Error {
constructor(
public readonly kind: string,
detail?: string,
) {
super(detail ? `${kind}: ${detail}` : kind)
this.name = 'ExportFailure'
}
}
function unwrap<T>(outcome: CoreOutcome<T>): T {
if (!outcome.ok) throw new ExportFailure(outcome.kind, outcome.detail)
return outcome.value
}
function assertNotAborted(signal: AbortSignal | undefined): void {
if (signal?.aborted) throw new DOMException('export aborted', 'AbortError')
}
/** Where the time went, for the DEV console and the browser harness (User Timing). */
interface ExportTiming {
startedAt: number
coreMs: number
rasterMs: number
requests: number
}
/** Runs a core call and charges its time. */
function timed<T>(timing: ExportTiming, call: () => T): T {
const started = performance.now()
try {
return call()
} finally {
timing.coreMs += performance.now() - started
}
}
/**
* Exports the report as an archive PDF through the engine: the core builds
* the snapshot of the loaded sheet the pages are drawn from and the
* attachment carries (R2), the branding comes from the bundled logos, the
* browser rasterises the views, the TypeScript engine writes the file (the
* writer moves to the core at R4). The core's report and snapshot are the
* same JSON contracts the engine's Zod types describe. Warnings are logged
* and returned for the caller to surface.
* One `performance.measure('faunosteo:export')` entry with the split in its detail:
* nothing the page shows, what the harness reads. Absent where User Timing lacks the
* options form.
*/
function publishTiming(timing: ExportTiming, parts: number, bytes: number): void {
try {
performance.measure('faunosteo:export', {
start: timing.startedAt,
end: performance.now(),
detail: {
coreMs: timing.coreMs,
rasterMs: timing.rasterMs,
requests: timing.requests,
parts,
bytes,
},
})
} catch {
// An older engine: no measure, nothing else changes.
}
}
/**
* One batch of the session's requests rasterised under `Promise.all`, as the engine did:
* a raster that fails is reported as it rejects (the warning order the engine recorded),
* the others are given in request order once the batch has settled (the embedding order,
* so the file's bytes do not depend on which raster finished first). The PNG bytes are
* copied into the core and dropped as each `addRaster` returns.
*/
async function answerBatch(
session: CoreExportSession,
requests: RasterRequest[],
signal: AbortSignal | undefined,
timing: ExportTiming,
): Promise<void> {
timing.requests += requests.length
const rasterStarted = performance.now()
const settled = await Promise.all(
requests.map(async (request) => {
try {
const png = await browserRasterizer(request.svg, {
widthPx: request.widthPx,
heightPx: request.heightPx,
})
return { key: request.key, png }
} catch {
assertNotAborted(signal)
unwrap(timed(timing, () => session.rasterFailed(request.key)))
return { key: request.key, png: null }
}
}),
)
timing.rasterMs += performance.now() - rasterStarted
for (const { key, png } of settled) {
if (!png) continue
assertNotAborted(signal)
unwrap(timed(timing, () => session.addRaster(key, png)))
}
}
/**
* Exports the report as an archive PDF through the core's session (R4.6, plan §B.1.6):
* the core builds the snapshot of the loaded sheet the pages are drawn from and the
* attachment carries, the branding comes from the bundled logos, the labels from
* `labels.ts`, the export time from the clock; the core then asks for each raster it
* needs (the SVG logos, then the views of each observation), the browser draws it, and
* the core writes the file as the rasters arrive. The session is freed whatever happens.
* A refused input or a core failure throws (`ExportFailure`, or the `AbortError` of a
* cancelled export); warnings are returned for the caller to surface.
*/
export async function exportReportToPdf(
report: Report,
@@ -35,18 +144,43 @@ export async function exportReportToPdf(
opts: PdfExportOptions,
): Promise<PdfExportResult> {
const snapshot = index.ops.snapshot(report)
if (!snapshot.ok) throw new Error(`snapshot failed: ${snapshot.kind}`)
const result = await exportReportArchive({
report: report as ExportInput['report'],
sheet: snapshot.value as ExportInput['sheet'],
if (!snapshot.ok) throw new ExportFailure(snapshot.kind, snapshot.detail)
const input: ExportInput = {
report,
sheetSnapshot: snapshot.value,
branding: await loadBranding(),
labels: defaultPdfLabels,
locale: opts.locale,
rasterizer: browserRasterizer,
exportedAt: new Date(),
})
for (const warning of result.warnings) {
console.warn('PDF export warning', warning)
exportedAt: new Date().toISOString(),
}
assertNotAborted(opts.signal)
const timing: ExportTiming = {
startedAt: performance.now(),
coreMs: 0,
rasterMs: 0,
requests: 0,
}
const text = JSON.stringify(input)
const session = unwrap(
timed(timing, () => openExportSession(coreRuntime(), text)),
)
try {
for (;;) {
assertNotAborted(opts.signal)
const step = unwrap(timed(timing, () => session.next()))
if (step.step === 'done') break
await answerBatch(session, step.requests, opts.signal, timing)
}
const parts = unwrap(timed(timing, () => session.finish()))
const warnings = unwrap(session.warnings())
for (const warning of warnings) {
console.warn('PDF export warning', warning)
}
const pdf = new Blob(parts as BlobPart[], { type: 'application/pdf' })
publishTiming(timing, parts.length, pdf.size)
if (import.meta.env.DEV) console.info('PDF export', timing)
return { pdf, warnings }
} finally {
session.free()
}
return { pdf: result.pdf, warnings: result.warnings }
}
-103
View File
@@ -1,103 +0,0 @@
import type { ArchiveImport, RebaseOutcome } from '@faunosteo/core-wasm/types'
import {
ArchiveReadError,
readAttachedDocument,
type ArchiveReadErrorKind,
} from '@faunosteo/pdf'
import type { SheetIndex } from '@/services/sheetIndex'
import { UNREADABLE_DRAFT_KINDS } from '@/state/reportStore'
export { MAX_ATTACHMENT_BYTES, MAX_PDF_BYTES } from '@faunosteo/pdf'
/**
* `lone_surrogate`: the attachment escapes a lone UTF-16 surrogate, which the
* core cannot read without altering it (L1): refused, the file untouched.
* `invalid_copy`: a file offered as a rescue copy that this build cannot read.
*/
export type ImportErrorKind =
| ArchiveReadErrorKind
| 'core_unavailable'
| 'lone_surrogate'
| 'invalid_copy'
/**
* Localization-agnostic import error. Carries a kind discriminant + an
* optional foundVersion so the caller (UI layer) can resolve the
* user-facing message via the active i18n dict.
*/
export class ImportError extends Error {
constructor(
public readonly kind: ImportErrorKind,
public readonly foundVersion?: number | null,
) {
super(kind)
this.name = 'ImportError'
}
}
/**
* Step 1, no core needed: the JSON a Faunosteo PDF carries, located by the
* engine's byte scan (BLK-009; the scanner moves to the core at R4). Engine
* failures become ImportError kinds, one to one.
*/
export async function readAttachment(pdfBytes: Uint8Array): Promise<unknown> {
try {
return await readAttachedDocument(pdfBytes)
} catch (err) {
if (err instanceof ArchiveReadError) {
throw new ImportError(err.kind, err.foundVersion)
}
throw err
}
}
/**
* Step 2, in the core on the loaded sheet: the layered reading of the
* attachment (report first, v2 migrated through the sheet's map, then the
* envelope kept or its snapshot dropped with a reason) and the rebase onto
* that sheet. An unknown numeric report version is `incompatible_version`,
* a text the core would alter `lone_surrogate`, any other unreadable content
* `no_attachment`, as the engine reported them.
*/
export function importAttachment(
attachment: unknown,
index: SheetIndex,
): ArchiveImport {
const outcome = index.ops.importArchive(attachment)
if (outcome.ok) return outcome.value
switch (outcome.kind) {
case 'incompatible_version':
throw new ImportError('incompatible_version', outcome.found ?? null)
case 'no_attachment':
throw new ImportError('no_attachment')
case 'lone_surrogate':
throw new ImportError('lone_surrogate')
case 'core_unavailable':
case 'internal':
throw new ImportError('core_unavailable')
default:
throw new Error(`import failed: ${outcome.kind}`)
}
}
/** Both steps on a sheet already loaded in the core. */
export async function importReportFromPdf(
pdfBytes: Uint8Array,
index: SheetIndex,
): Promise<ArchiveImport> {
return importAttachment(await readAttachment(pdfBytes), index)
}
/**
* A rescue copy (`JSON.stringify(report)`, the byte format of the tab's draft)
* read by the core's draft restore, no archive beside it. Content the core
* refuses is `invalid_copy`; any other failure is the engine's or the sheet's.
*/
export function readRescueCopy(text: string, index: SheetIndex): RebaseOutcome {
const outcome = index.ops.restoreDraft(text, null)
if (outcome.ok) return outcome.value.rebase
if (UNREADABLE_DRAFT_KINDS.has(outcome.kind)) {
throw new ImportError('invalid_copy')
}
throw new ImportError('core_unavailable')
}
+67
View File
@@ -0,0 +1,67 @@
import type { PdfLabelSet, PdfLabels } from '@faunosteo/core-wasm/types'
/**
* The static wording of the PDF (section headings, metadata), frozen into every archive
* the export writes (R4.6: moved verbatim from `packages/pdf/src/i18n`, same key order,
* which is the order every shipped attachment carries; the app dictionaries hold no
* `pdf.*` key). A wording change here changes new exports only: an old archive keeps the
* labels it was written with.
*/
const fr: PdfLabels = {
'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHÈSE',
'pdf.title.conclusion': 'Conclusion',
'pdf.section.zones': 'ZONES',
'pdf.section.findings_prefix': 'CONSTATS — ',
'pdf.section.free_findings': 'CONSTATS LIBRES',
'pdf.section.severity': 'SÉVÉRITÉ',
'pdf.section.comment': 'COMMENTAIRE',
'pdf.section.conclusion': 'CONCLUSION',
'pdf.section.recommendations': 'RECOMMANDATIONS',
'pdf.section.next_appointment': 'PROCHAIN RENDEZ-VOUS',
'pdf.view.general': 'VUE GÉNÉRALE',
'pdf.view.detail_prefix': 'VUE DÉTAIL — ',
'pdf.empty': '—',
'pdf.owner_prefix': 'Propriétaire : ',
'pdf.siret_prefix': 'SIRET ',
'pdf.title.suffix.bilan': 'Bilan ostéo — ',
'pdf.subject': "Bilan d'ostéopathie animalière",
'severity.mild': 'légère',
'severity.moderate': 'modérée',
'severity.severe': 'sévère',
'lateral.left': 'Gauche',
'lateral.right': 'Droite',
'footer.powered_by': 'Propulsé par',
'footer.in_partnership': 'En partenariat avec',
}
const en: PdfLabels = {
'pdf.eyebrow.observation': 'OBSERVATION',
'pdf.eyebrow.synthesis': 'SYNTHESIS',
'pdf.title.conclusion': 'Conclusion',
'pdf.section.zones': 'ZONES',
'pdf.section.findings_prefix': 'FINDINGS — ',
'pdf.section.free_findings': 'FREE FINDINGS',
'pdf.section.severity': 'SEVERITY',
'pdf.section.comment': 'COMMENT',
'pdf.section.conclusion': 'CONCLUSION',
'pdf.section.recommendations': 'RECOMMENDATIONS',
'pdf.section.next_appointment': 'NEXT APPOINTMENT',
'pdf.view.general': 'GENERAL VIEW',
'pdf.view.detail_prefix': 'DETAIL VIEW — ',
'pdf.empty': '—',
'pdf.owner_prefix': 'Owner: ',
'pdf.siret_prefix': 'SIRET ',
'pdf.title.suffix.bilan': 'Osteo report — ',
'pdf.subject': 'Animal osteopathic report',
'severity.mild': 'mild',
'severity.moderate': 'moderate',
'severity.severe': 'severe',
'lateral.left': 'Left',
'lateral.right': 'Right',
'footer.powered_by': 'Powered by',
'footer.in_partnership': 'In partnership with',
}
export const defaultPdfLabels: PdfLabelSet = { fr, en }
+18 -2
View File
@@ -1,6 +1,7 @@
import { useEffect, useState } from 'react'
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
import { coreRuntime } from '@/core/runtime'
import { prefetchImportWorker } from '@/core/worker/controller'
import { SheetOps } from '@/core/sheetOps'
import { SheetIndex } from '@/services/sheetIndex'
import {
@@ -50,10 +51,13 @@ async function loadIntoCore(speciesId: string): Promise<SheetLoad> {
const data = session.call<SheetIndexData>('index_data', '')
if (data.ok) {
const index = new SheetIndex(data.value, new SheetOps(session))
// The engine is loaded: warm the import worker's chunk for a later offline import.
prefetchImportWorker()
return { status: 'ready', index }
}
return {
status: data.kind === 'invalid_sheet' ? 'invalid_sheet' : 'core_unavailable',
status:
data.kind === 'invalid_sheet' ? 'invalid_sheet' : 'core_unavailable',
}
}
@@ -73,6 +77,17 @@ export function loadSheet(speciesId: string): Promise<SheetLoad> {
return pending
}
/**
* The bundled payload as the text the core's `SheetHandle` reads, for the import worker
* (R4.3): the same text the page's own session was built from. Null without a sheet.
*/
export async function loadSheetBundleText(
speciesId: string,
): Promise<string | null> {
const bundle = await provider.getReferenceSheet(speciesId)
return bundle ? JSON.stringify(bundle) : null
}
/** The ready index, or null (tests and callers that need the sheet or nothing). */
export async function loadSheetIndex(
speciesId: string,
@@ -99,7 +114,8 @@ export function useSheet(speciesId: string | undefined): SheetState {
void loadSheet(speciesId).then((load) => {
if (cancelled) return
if (load.status === 'ready' || load.status === 'none') setState(load)
else if (load.status === 'invalid_sheet') setState({ status: load.status, retry })
else if (load.status === 'invalid_sheet')
setState({ status: load.status, retry })
else setState({ status: 'core_unavailable', retry })
})
return () => {
+25
View File
@@ -36,3 +36,28 @@ under `apps/app/src/assets/brand`, rasteriser stubbed to a 2×1 PNG).
Never regenerate these files without a user decision; the Step 6 engine must
reproduce them. Generation, once: `MAKE_GOLDEN=1 corepack pnpm vitest run
tests/unit/pdf.goldens.test.ts` from `apps/app`.
## R4 freeze (2026-10-18)
What the TypeScript PDF engine and reader produced right before the Rust port,
frozen on branch `feature/rust-r4-pdf-core` (`docs/development/RUST.md` §10.1
lists every oracle with its commit). The generators (the `r4.*-oracles` vitest
suites of `packages/pdf` and `apps/app`) ran behind `MAKE_R4_ORACLES=1` and were
deleted with the TypeScript engine at R4.8 (2026-10-19): the files below are
frozen for good and checked by the cargo suites (`crates/core/tests/pdf_*.rs`);
only `r4/reports` (O13, `r4.synthetic-reports.test.ts`) and the R4 digests
(`goldens/r4/pdf.*.sha256`, cargo) keep a generator.
| Path | Content |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `r4/reports/{L,CAP}.json` | Synthetic Report v3 on the draft: 60 observations / 120 views (L) and 500 / 1,000 (CAP), the export memory inputs of plan §B.4 (O13). |
| `goldens/r4/draw.*.json` | Every drawing call of the export (text, image, line, rectangle, link) at full precision, per page and in call order, for the 12 Step 6 report × locale × logo combinations (O1). |
| `pdf/r3/` | The 12 PDFs the R3-era engine produced for those combinations, the store-path export with its `report.json`, and `real/v2full-obs1.fr.logos.pdf` with its two browser PNGs and manifest: the byte references of the writer port (O2). |
| `goldens/r4/pdf.*.sha256` | Digests of the Rust writer's own output on the 14 O2 runs (not an oracle of the TypeScript: the proof that the wasm module and the application path write the native bytes). Frozen at R4.5; rewritten once at R4.6 when the writer became incremental (catalog and page tree written last, upper-case hex strings as pdf-lib), every O2 comparison and the poppler render unchanged. `MAKE_R4_ORACLES=1 cargo test --test pdf_serialize r4_output_digests_are_frozen` rewrites them, never to hide a difference with O2. |
| `pdf/step6/envelope.*.pdf` | Three envelope PDFs from before R2 (O3). |
| `pdf/r4/tolerance/` | 51 PDFs, valid and hostile, with today's import outcome and message in `crates/core/tests/oracles/r4/tolerance.json` (O8). |
| `pdf/r4/read/`, `pdf/r4/inflate/` | 155 reader inputs and 24 zlib framing inputs, the bytes behind `read.json` and `inflate.json`; a `<slug>.gen.json` describes a large input by concatenation (O7, O9). |
Synthetic data only, no real bilan. Never regenerate these files to make a
test pass: a difference between the Rust port and an oracle is reported and
decided (plan §A.3), or it is a bug in the port.
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
2bf8290a85caa5c7e51fee3804de647858633b9cb1d29c950d50e9ce91ae0f18
@@ -0,0 +1 @@
6a405c4579dffaa06625ee363f406def86f70783e74551441b394b35ffb6b4d0
@@ -0,0 +1 @@
03b7e41957e39a68e9349231186710a05e4e0b92b1e791879401e78b5c073993
@@ -0,0 +1 @@
3f89ff74fcec00b79d143a6e435bdb3fd70a81371daf5c73918997c703aabd9e
@@ -0,0 +1 @@
87f7a6095e38164ee7b06d452fb5eb00a266ffd6da4d77fa84999052ee8396c3
@@ -0,0 +1 @@
400652e30e0d85d6bf1fbec68630bed743b147745d55d7c3b25000d821b7b447
@@ -0,0 +1 @@
73580fb43b3505356547e6a1ed18c5412eca7427aacc9daf356b9bcf7f1f9f78
@@ -0,0 +1 @@
d4b6bc2af9286ebe870198e14ab60e82e54f48ee6027ee16dfee8b442caa2821
@@ -0,0 +1 @@
08a962fb15dbdf9a1064fa176a7c674b882d14d9321344fe4ded7480ce963f99
@@ -0,0 +1 @@
284d4a3b579da2c0cad3f90ca96909ca4901856387669d35d8949c16e81305e1
@@ -0,0 +1 @@
503ec265cab6d5c8a776fae458cf782c3bb51db3a9c0edf06e93b2365c41350e
@@ -0,0 +1 @@
cdac37b198552778e9afbc62a3b74a7868c61cd9c43800d41a689a389f2b6077
@@ -0,0 +1 @@
0da6e80c849c040ca3584c208320412ddf6d2131fd9836e14c0584b44e2c49fd
@@ -0,0 +1 @@
828c8250593af1133738843489205242e80804c9ebee76cdeda22bea75406188
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+30
View File
@@ -0,0 +1,30 @@
{
"note": "v2full reduced to its first observation (obs-1, main view), every other field unchanged: the full report weighed 3 MB in real rasters.",
"calls": [
{
"index": 0,
"svgSha256": "c342c54fae8e69d90cbe90f4abf233b4aaa388e2d96d54a47fd7c73295b6c89a",
"widthPx": 1200,
"heightPx": 263,
"png": "raster-0.png",
"pngSha256": "38f30384e816271f3186ee3f94410d50975176db610ea9d86a3ad0c352fde4fd",
"subject": {
"kind": "logo",
"slot": "partner"
}
},
{
"index": 1,
"svgSha256": "a9a3155c827838af46edd583452e8d8106c3ce09da272afaaf37c3cb36af2c11",
"widthPx": 1200,
"heightPx": 943,
"png": "raster-1.png",
"pngSha256": "c4af684450f54dadf87208560a3ae7f758446f01a5a7f435b6d06c5df59083dd",
"subject": {
"kind": "view",
"observationId": "obs-1",
"viewId": "main"
}
}
]
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 522 KiB

Binary file not shown.
Binary file not shown.
+266
View File
@@ -0,0 +1,266 @@
{
"version": 3,
"id": "fixture-demo-v3",
"createdAt": "2026-10-11T09:30:00.000Z",
"date": "2026-10-11",
"practitioner": {
"contact": "secretariat@example.test",
"name": "Dr. Claire Dupont-Martin"
},
"animal": {
"speciesId": "equine",
"name": "Mistral",
"breed": "Selle Français",
"age": "9 ans"
},
"owner": {
"name": "Jean Martin"
},
"sheet": {
"sheetId": "503dc301-a8b1-50d4-9e44-0919b2fc2916",
"versionId": null,
"documentSha256": "27c7383c445c73dc2001ebf4794a3ea63d416910bbbaa0d7848dd720de7c2660"
},
"observations": [
{
"id": "obs-demo-1",
"zones": [
{
"annotationId": "c7-t1",
"viewId": "main",
"labelFrSnapshot": "Charnière C7-T1 (cervico-thoracique)",
"labelEnSnapshot": "C7-T1 junction (cervicothoracic)"
},
{
"annotationId": "t18-l1",
"viewId": "main",
"labelFrSnapshot": "Charnière T18-L1 (thoraco-lombaire)",
"labelEnSnapshot": "T18-L1 junction (thoracolumbar)"
}
],
"findings": [
{
"findingZoneId": "c7-t1",
"path": [
"c7-t1-dysfunctions",
"segmental",
"restriction-flexion"
],
"labelFrSnapshot": "Restriction en flexion",
"labelEnSnapshot": "Flexion restriction"
},
{
"findingZoneId": "c7-t1",
"path": [
"c7-t1-dysfunctions",
"segmental",
"restriction-extension"
],
"labelFrSnapshot": "Restriction en extension",
"labelEnSnapshot": "Extension restriction"
}
],
"freeTextFindings": [],
"severity": "mild",
"comment": "Réagit à la palpation de la charnière."
},
{
"id": "obs-demo-2",
"zones": [
{
"annotationId": "hip",
"viewId": "main",
"side": "left",
"labelFrSnapshot": "Hanche (coxo-fémorale)",
"labelEnSnapshot": "Hip joint"
},
{
"annotationId": "hip",
"viewId": "main",
"side": "right",
"labelFrSnapshot": "Hanche (coxo-fémorale)",
"labelEnSnapshot": "Hip joint"
}
],
"findings": [
{
"findingZoneId": "hip",
"path": [
"hip-dysfunctions",
"articular",
"restriction-flexion"
],
"labelFrSnapshot": "Restriction en flexion",
"labelEnSnapshot": "Flexion restriction",
"side": "left"
},
{
"findingZoneId": "hip",
"path": [
"hip-dysfunctions",
"articular",
"restriction-abduction-adduction"
],
"labelFrSnapshot": "Restriction en abduction / adduction",
"labelEnSnapshot": "Abduction / adduction restriction",
"side": "right"
}
],
"freeTextFindings": [],
"severity": "moderate",
"comment": ""
},
{
"id": "obs-demo-3",
"zones": [
{
"annotationId": "cervical",
"viewId": "main",
"vertebrae": [
{
"region": "C",
"index": 3
},
{
"region": "C",
"index": 4
}
],
"labelFrSnapshot": "Vertèbres cervicales",
"labelEnSnapshot": "Cervical vertebrae"
}
],
"findings": [
{
"findingZoneId": "cervical",
"path": [
"cervical-dysfunctions",
"segmental",
"localized-fixation"
],
"labelFrSnapshot": "Fixation segmentaire localisée (C2–C7)",
"labelEnSnapshot": "Localized segmental fixation (C2–C7)"
}
],
"freeTextFindings": [],
"severity": "severe",
"comment": "Fixation nette en latéroflexion droite."
},
{
"id": "obs-demo-4",
"zones": [
{
"annotationId": "atm",
"viewId": "head",
"labelFrSnapshot": "Articulation temporo-mandibulaire (ATM)",
"labelEnSnapshot": "Temporomandibular joint (TMJ)"
},
{
"annotationId": "frontal",
"viewId": "head",
"labelFrSnapshot": "Frontal",
"labelEnSnapshot": "Frontal bone"
}
],
"findings": [
{
"findingZoneId": "frontal",
"path": [
"frontal-consultation-reasons",
"head-rubbing"
],
"labelFrSnapshot": "Frottements répétés de la tête rapportés",
"labelEnSnapshot": "Reported repeated head rubbing",
"requiresVetReferral": true
},
{
"findingZoneId": "atm",
"path": [
"atm-dysfunctions",
"articular",
"restriction-opening"
],
"labelFrSnapshot": "Restriction à l'ouverture",
"labelEnSnapshot": "Opening restriction"
}
],
"freeTextFindings": [],
"comment": ""
},
{
"id": "obs-demo-5",
"zones": [
{
"annotationId": "sacroiliac",
"viewId": "main",
"side": "right",
"labelFrSnapshot": "Articulation sacro-iliaque",
"labelEnSnapshot": "Sacroiliac joint"
},
{
"annotationId": "occipital",
"viewId": "head",
"labelFrSnapshot": "Occipital",
"labelEnSnapshot": "Occipital bone"
}
],
"findings": [],
"freeTextFindings": [
"Sensibilité au garrot",
"Tension du ligament nuchal"
],
"severity": "mild",
"comment": "Compensation probable."
},
{
"id": "obs-demo-6",
"zones": [
{
"annotationId": "lumbar",
"viewId": "main",
"vertebrae": [
{
"region": "L",
"index": 2
},
{
"region": "L",
"index": 3
}
],
"labelFrSnapshot": "Vertèbres lombaires",
"labelEnSnapshot": "Lumbar vertebrae"
},
{
"annotationId": "l6-s1",
"viewId": "main",
"labelFrSnapshot": "Charnière L6-S1 (lombo-sacrée)",
"labelEnSnapshot": "L6-S1 junction (lumbosacral joint)"
}
],
"findings": [
{
"findingZoneId": "lumbar",
"path": [
"lumbar-dysfunctions",
"segmental",
"restriction-extension"
],
"labelFrSnapshot": "Restriction en extension",
"labelEnSnapshot": "Extension restriction"
}
],
"freeTextFindings": [
"Raideur lombaire au pas"
],
"comment": ""
}
],
"conclusion": "Dysfonction cervico-thoracique avec compensation du bassin et tension crânienne associée.",
"recommendations": "Repos 3 jours puis reprise progressive ; contrôle vétérinaire pour les frottements de tête.",
"localAnnotations": [],
"nextAppointment": {
"kind": "date",
"date": "2026-11-20"
}
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loaded 100 of 715 files, more files were not shown because too many files have changed in this diff. Show more