From 4c6c5151f89c7743c0451fa8887fe0ff346f5dcf Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 11 Oct 2026 11:59:08 +0200 Subject: [PATCH] docs: step 6 implementation contract (types, envelope v1, read, rebase, session, messages, goldens) + BDR-039 --- .claude/memory/decisions.md | 8 + .../2026-10-11-step-06-phase-0-freeze.md | 27 ++ .../development/STEP6_PDF_ARCHIVE_ANALYSIS.md | 373 ++++++++++++++++++ 3 files changed, 408 insertions(+) create mode 100644 .claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index 53a23fd2..ebea0aba 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -327,3 +327,11 @@ Status: closed. Sheet source: `SheetProvider` interface; Step 5 implementation = Vite virtual module `virtual:faunosteo-sheet` built from the seed draft (`vite/sheet-bundle.ts`), mode `SHEET_BUNDLE=draft|none`, default draft for dev server, none for builds/CI/Docker (`--build-arg SHEET_BUNDLE=draft` = explicit preview) → unvalidated draft never ships by accident (D2). Markers: pure renderer `@faunosteo/anatomy/render` (element tree, no DOM) reproduces legacy look (hitbox r + twin r−12, opacities 0.65/0.5, spine 0.3, trigger 0.06 dashed); colours = document data (`categories[].color`, additive `annotations[].color` for the head shades, schema_version stays 2 for additive optional fields); same renderer feeds `draft/review/app-.svg` for visual checks. Report v3 in packages/domain: `(annotationId, viewId)` zones with label snapshots, `(findingZoneId, path)` findings, severity codes, `sheet {sheetId, versionId|null, documentSha256}`, `unresolved: true` for what migration cannot place, `localAnnotations: []` reserved. Migration map generated by the pipeline from applier records (replay renames/moves/removals + unique re-homing): 792 nodes → 571/180/7/34. Interaction = pure service + reducers (BDR-019 kept); store = v3 + persistence adapter (v2 draft migrated on restore). D4 applied: registry, matchers, SVG parser, editors, pathology-editor, public species assets deleted; legacy sources moved to `supabase/seed/.../legacy-sources/` (importer input). Alt rejected: copying the draft into apps/app (duplication, drift); runtime fetch of `/sheets/*.json` (still public, no gain); UUID annotation ids (BDR-031); converting v3→v2 for attachments (lossy); per-view colour table in the app (horse knowledge in generic code). Status: closed; awaiting user validation of Step 5. + +--- + +## BDR-039 | 2026-10-11 | Step 6: autonomous PDF archives — lean-document snapshot, envelope v1, archived branding + labels, explicit rebase + +User-validated design (docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II). Attachment = envelope v1 `{format, envelopeVersion, exportedAt, locale, report v3, sheetSnapshot, branding, labels}` in one `osteo-report.json`, SVG inline as text. Snapshot = `{status, ref, document, assets}` where document = valid lean `AnatomicalSheetDocument` (all views/annotations/categories/regions, finding zones kept by id, trees pruned to used paths with ancestor labels, references emptied) → reuses sheet index, layer renderer, 21 integrity rules; no dedicated schema. Branding (logos base64/svg, credits, URLs) + label dict (fr+en) archived so future logo/wording changes never alter a re-render (user D7 adjustment). Engine `packages/pdf`: explicit inputs `{report, sheet, branding, labels, locale, rasterizer, exportedAt}`, no DOM lib, xmldom composition promoted from curation app-review, Rasterizer adapter (browser Image/canvas; resvg devDep for tests), per-view/per-logo degradation, export-side validation (caps, integrity, sheet invariant). Read = layered: report first (v3/v2 existing dispatch), envelope metadata tolerant, snapshot strict → `snapshotRejected` enum, report never lost; `attachment_stripped` via Info.Keywords stamp. Session: imported archive kept immutable (`osteo:archive`), working copy rebased explicitly on the loaded sheet (`rebaseReportOnSheet`, unresolved flags + labels from archived snapshot) (user D8 adjustment); re-export of the kept archive = technical support only, UX submitted after step. No CLI, no page change, no original v2 JSON re-embedded. +Alt rejected: dedicated SheetSnapshotSchema (rewrites lookups, loses integrity rules); separate embedded files per asset (first-EmbeddedFile reader, stripping risk); pruning views/annotations (saves ~0 KB, breaks trigger titles); snapshot discarded on import (user: keep for faithful re-read); crypto hash check of assets (self-referential; sha copied from catalog manifest as provenance pointer instead). +Status: open (implementation in progress on feature/step-06-pdf-archives). diff --git a/.claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md b/.claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md new file mode 100644 index 00000000..9c12007e --- /dev/null +++ b/.claude/tasks/contracts/2026-10-11-step-06-phase-0-freeze.md @@ -0,0 +1,27 @@ +# CONTRACT — step-06 phase 0 freeze +- date: 2026-10-11 | flow: ship-feature (executor) | branch: feature/step-06-pdf-archives +- status: active +- spec: docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md Part II (§17 goldens, §13 types for naming only) + +## REQUEST (IMMUTABLE) +Freeze the current PDF pipeline behaviour before any refactor: new fixtures, goldens generated once with the current code, characterisation tests of the two routes. Production code under apps/app/src is NOT modified in this phase. + +## ACCEPTANCE CRITERIA +1. Fixture `apps/app/tests/fixtures/report-v3.demo.json`: valid Report v3 on the bundled draft (ids taken from draft/document.json), 6 observations covering: main view zones, head view zone, a spine zone with vertebrae, a bilateral zone with left and right sides, a vet-referral leaf (`requiresVetReferral: true`), a leaf whose label holds an en dash (U+2013), free-text findings, severities, comment, conclusion, recommendations, nextAppointment; `sheet` = the draft ref. + CHECK: cd apps/app && corepack pnpm vitest run tests/unit/pdf.goldens.test.ts 2>&1 | tail -3 + EXPECT: Tests .* passed +2. Goldens under `apps/app/tests/fixtures/goldens/step6/` exactly as spec §17 (text/images/links per report × locale × logo mode, views per report), generated by `MAKE_GOLDEN=1 corepack pnpm vitest run tests/unit/pdf.goldens.test.ts`, then asserted by the same file without the flag. Reports: v2full, demo, v2unresolved. Logo modes: nologos, logos. + CHECK: ls apps/app/tests/fixtures/goldens/step6 | wc -l + EXPECT: >= 20 +3. Fixture `apps/app/tests/fixtures/report-v3.bare.pdf`: the demo report exported by the current code (rasteriser stubbed 1×1, no logos), produced by the same MAKE_GOLDEN run; `tests/fixtures/README.md` documents the new files and the rule "never regenerate without a user decision". + CHECK: test -s apps/app/tests/fixtures/report-v3.bare.pdf && echo ok + EXPECT: ok +4. Characterisation tests `tests/unit/routes.HomeRoute.import.test.tsx` and `tests/unit/routes.EditorRoute.export.test.tsx` as spec §17 (import mocked at module level; alert text with count; the three current error kinds + generic; navigation to /editor; export call shape; download name; failure alert). + 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 + EXPECT: Tests .* passed ; 0 + +## FILE SCOPE +apps/app/tests/** only (new test files, fixtures, goldens, helpers, README). No change under apps/app/src, packages/**, docs/**. diff --git a/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md b/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md index e6722ce0..635605d8 100644 --- a/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md +++ b/docs/development/STEP6_PDF_ARCHIVE_ANALYSIS.md @@ -617,3 +617,376 @@ Definition of Done: no fetch and no DOM in `packages/pdf` (compile, lint, tests); T1–T15 green; Phase 0 goldens reproduced in both logo modes; demo envelope < 250 KB stored and raw; `docs/PDF-FORMAT.md` complete; v2 fixtures import and re-export; rebase alert shown when the draft changed. + +--- + +# Part II — Implementation contract (validated 2026-10-11) + +The user validated Part I on 2026-10-11 with three adjustments, recorded here +as the binding contract for the executors. Where Part I and Part II differ, +Part II wins. + +## 12. Validated adjustments + +- **D7 (branding).** The engine receives its branding explicitly and never + fetches. The archive **also stores the branding used at export** (logos, + partner credits, URLs, fallback texts) and the **label dictionary** (both + locales), so a future logo, wording or configuration change cannot alter + the reproduction of an old archive. Compact and safe representation, no + duplicated resource inside the envelope. Cost measured and reported. +- **D8 (imported snapshot).** The archive carried by an imported PDF is + **kept in the session**, immutable. Two operations are distinct in the + architecture: (1) re-read or re-export an archive from its own snapshot, + branding and labels, no rebase; (2) resume a bilan for editing on the + current sheet: an explicit rebase on a **working copy**, historical labels + of unresolvable items preserved. No new significant UI in this step: the + technical support (store, persistence, engine API) ships and the UX choice + for operation (1) is submitted to the user after the step. +- **D10, D12.** No change to the pages. No `report:reexport` CLI. +- **D13 (messages).** Explicit FR/EN messages for: an archive imported with + its snapshot; a snapshot rejected while the report was recovered; a rebase + with its count; a stripped attachment. A partial or degraded import is + never presented as a perfect restoration. +- **D1, D4, D6** as recommended in §9. + +## 13. Types (TypeScript, authoritative) + +All JSON contracts below are **camelCase**, like Report v3 and `SheetRef`; +the `AnatomicalSheetDocument` inside keeps its own snake_case schema. + +```ts +// packages/domain/src/archive/snapshot.ts +export interface SheetSnapshotRef { // sheet-ref.json, camelCase + sheetId: string; versionId: string | null; documentSha256: string /^[0-9a-f]{64}$/; + schemaVersion: number; speciesId: string; +} +export interface SheetSnapshotAsset { svgAssetId: string; sha256: string | null; svg: string } +export interface SheetSnapshot { + status: 'draft' | 'published'; + ref: SheetSnapshotRef; + document: AnatomicalSheetDocument; // lean, valid (schema v2, strict) + assets: SheetSnapshotAsset[]; +} +export const SheetSnapshotSchema: z.ZodType // strict + caps (§15) +export function buildSheetSnapshot(sheet: SnapshotSource, report: Report): SheetSnapshot +export interface SnapshotSource { // what LoadedSheet provides + status: 'draft' | 'published'; ref: SheetSnapshotRef; document: AnatomicalSheetDocument; + assets: Readonly>; // svg text by svgAssetId + assetHashes?: Readonly>; // sha256 by svgAssetId (seed manifest) +} +export function assertSnapshot(snapshot: SheetSnapshot): SheetSnapshot + // SheetSnapshotSchema.parse, validateSheetDocument(document) has no 'error' issue, + // every view resolves (own asset or parent chain) to an asset present in `assets`, + // document depth pre-check; throws SnapshotError(reason: SnapshotRejection) +export type SnapshotRejection = 'unsupported_envelope' | 'schema' | 'caps' | 'integrity' | 'sheet_mismatch' + +// packages/domain/src/archive/envelope.ts +export const ENVELOPE_FORMAT = 'faunosteo-report-archive' +export const ENVELOPE_VERSION = 1 +export interface ReportArchiveEnvelope { + format: typeof ENVELOPE_FORMAT; envelopeVersion: 1; + exportedAt: string; // ISO timestamp + locale: 'fr' | 'en'; + report: Report; // v3, as exported (never rebased) + sheetSnapshot: SheetSnapshot; + branding: Branding; + labels: PdfLabelSet; +} +export const ReportArchiveEnvelopeSchema: z.ZodType + // metadata object is NOT strict (unknown keys ignored within v1); report, sheetSnapshot, + // branding, labels are parsed by their own schemas +export type ArchiveOrigin = 'envelope_v1' | 'bare_v3' | 'v2' +export interface ArchiveReadOutcome { + report: Report; origin: ArchiveOrigin; migrated: boolean; + unresolvedZones: number; unresolvedFindings: number; // from the v2 migration + archive: ReportArchiveEnvelope | null; // the validated envelope, when accepted + snapshotRejected?: SnapshotRejection; // envelope present but snapshot dropped +} +export function readArchiveDocument(data: unknown, map: ReportMigrationMap): ArchiveReadOutcome + // throws UnsupportedReportVersionError (existing) when the REPORT version is unknown + +// packages/domain/src/archive/branding.ts +export type ImageAsset = { kind: 'png'; base64: string } | { kind: 'svg'; svg: string } +export interface Credit { logo: ImageAsset | null; url: string; fallbackText: string } +export interface Branding { + siteUrl: string; + headerLogo: ImageAsset | null; // today /assets/faunosteo_logo_horizontal-512.png + footerLogo: ImageAsset | null; // today /assets/faunosteo-horizontal-com-512.png + poweredBy: Credit | null; // today ZenQuality PNG, https://zenquality.fr, 'zenquality.fr' + partner: Credit | null; // today Paws SVG, instagram URL, '@paws.iin.harmony' +} +export const BrandingSchema: z.ZodType // strict; base64 ≤ 512 KiB, svg ≤ 256 KiB, + // url http(s) only ≤ 2048, fallbackText ≤ 128 + +// packages/domain/src/archive/labels.ts +export const PDF_LABEL_KEYS = [ /* exactly the keys read by apps/app/src/pdf at HEAD: */ + 'pdf.empty','pdf.eyebrow.observation','pdf.eyebrow.synthesis','pdf.owner_prefix', + 'pdf.section.comment','pdf.section.conclusion','pdf.section.findings_prefix', + 'pdf.section.free_findings','pdf.section.next_appointment','pdf.section.recommendations', + 'pdf.section.severity','pdf.section.zones','pdf.siret_prefix','pdf.subject', + 'pdf.title.conclusion','pdf.title.suffix.bilan','pdf.view.detail_prefix','pdf.view.general', + 'severity.mild','severity.moderate','severity.severe','lateral.left','lateral.right', + 'footer.powered_by','footer.in_partnership' ] as const +export type PdfLabels = Record<(typeof PDF_LABEL_KEYS)[number], string> +export interface PdfLabelSet { fr: PdfLabels; en: PdfLabels } +export const PdfLabelSetSchema // strict, every key required, values ≤ 256 chars + +// packages/domain/src/report/rebase.ts +export interface RebaseOutcome { report: Report; unresolvedZones: number; unresolvedFindings: number; rebased: boolean } +export function rebaseReportOnSheet(report: Report, index: SheetIndex, archived: SheetSnapshot | null): RebaseOutcome + // rebased=false and report returned as is when report.sheet.documentSha256 === index.sheet.ref.documentSha256 + // else: zone with unknown annotationId or unknown viewId → unresolved: true, label snapshots + // filled from `archived` annotation names when absent; finding with no nodeAt(zoneId, path) + // → unresolved: true; items already unresolved stay; report.sheet = index.sheet.ref + +// packages/domain/src/anatomical-sheet/sheet-index.ts (moved from apps/app/src/services/sheetIndex.ts) +export interface SheetIndexSource { ref: SheetSnapshotRef-compatible { documentSha256 }; document: AnatomicalSheetDocument; assets: Readonly> } +export { buildSheetIndex, pickLabel, isObservable, type SheetIndex, type ObservableAnnotation } + // SheetIndex.sheet is typed as the source given; LoadedSheet satisfies it; SheetSnapshot does + // through a one-line adapter (assets array → record). `pickLabel` takes 'fr' | 'en'. + +// packages/pdf/src/index.ts +export type PdfLocale = 'fr' | 'en' +export type Rasterizer = (svg: string, size: { widthPx: number; heightPx: number }) => Promise +export interface ExportInput { + report: Report; sheet: SheetSnapshot; branding: Branding; labels: PdfLabelSet; + locale: PdfLocale; rasterizer: Rasterizer; exportedAt: Date; +} +export type ExportWarning = + | { kind: 'view_raster_failed'; observationId: string; viewId: string } + | { kind: 'logo_failed'; slot: 'headerLogo' | 'footerLogo' | 'poweredBy' | 'partner' } +export interface ExportResult { pdf: Uint8Array; envelope: ReportArchiveEnvelope; warnings: ExportWarning[] } +export function exportReportArchive(input: ExportInput): Promise + // throws ArchiveExportError(kind: 'snapshot_invalid' | 'snapshot_too_large' | 'sheet_mismatch' | 'too_many_pages') +export function exportFromEnvelope(env: ReportArchiveEnvelope, opts: { locale: PdfLocale; rasterizer: Rasterizer; exportedAt: Date }): Promise + // = exportReportArchive({ report: env.report, sheet: env.sheetSnapshot, branding: env.branding, labels: env.labels, ...opts }) +export type ArchiveReadErrorKind = 'invalid_pdf' | 'no_attachment' | 'attachment_stripped' | 'incompatible_version' +export class ArchiveReadError extends Error { kind: ArchiveReadErrorKind; foundVersion?: number | null } +export function readReportArchive(pdfBytes: Uint8Array, map: ReportMigrationMap): Promise +export function readAttachedDocument(pdfDoc: PDFDocument): Promise // raw JSON, for the compare CLI +export const MAX_PDF_BYTES, MAX_ATTACHMENT_BYTES +export const defaultPdfLabels: PdfLabelSet // verbatim copy of today's FR/EN strings +export const PDF_KEYWORD = 'faunosteo-archive/1' // Info.Keywords stamp +``` + +## 14. Behaviour + +**Export** (`exportReportArchive`): (1) `assertSnapshot(sheet)`; (2) refuse +when `report.sheet.documentSha256 !== sheet.ref.documentSha256` +(`sheet_mismatch`); (3) refuse `report.observations.length > 500` or any +observation with more than 8 distinct view ids (`too_many_pages`); (4) build +the envelope `{ format, envelopeVersion: 1, exportedAt, locale, report, +sheetSnapshot: sheet, branding, labels }`, serialise pretty (indent 2), refuse +above `MAX_ATTACHMENT_BYTES` (`snapshot_too_large`); (5) metadata: title, +author, subject (labels), creation and modification dates = `exportedAt`, +`setKeywords([PDF_KEYWORD])`; (6) fonts; (7) branding images: PNG → `embedPng` +(base64 decoded with `atob`), SVG → sanitise + rasterise at width 1200 px +(today's rule) → `embedPng`; each slot fails alone with a `logo_failed` +warning; (8) observation pages: rasterise every view of an observation in +parallel, then embed in view order (main first); a raster failure gives a +page without that image and a `view_raster_failed` warning; (9) conclusion +page, footer on every page, attach the envelope bytes as `osteo-report.json` +(`application/json`, description `Faunosteo report archive v1`, dates +`exportedAt`, `AFRelationship.Data`); (10) `save()`. + +**Label policy** (§3.1, unchanged wording): zone name = snapshot annotation +name by id (trigger: opened view's name), else report zone snapshot in the +locale (other locale as fallback), else the id; finding group heading = +snapshot finding-zone name by id, else the id upper-cased; finding text and +`(!)` from the report; views = unique view ids of the observation present in +the snapshot, main first; `unresolved` never consulted; every printed string +goes through `safeText` (§15). + +**View SVG** (`packages/pdf/src/svg/view.ts`): asset text refused if it +contains `; halo: boolean } }) => Element`: +set `viewBox` from `viewBoxOf(view)` when present, remove `width`/`height`, +render the layer tree; with `highlight`: keep only layer elements whose +annotation id is selected, set `fill="#b85a3f"`, `fill-opacity="0.85"`, and +`filter="url(#osteo-halo)"` when `halo`, emit no `data-*` attribute, keep +``; when `halo`, ensure `<defs>` (created as first child when absent) +holds the `osteo-halo` filter exactly as `observationPage.ts:157-197` +(x/y −100%, width/height 300%, `filterUnits="userSpaceOnUse"`, blurs 18 and 8, +merge wide×3 + tight×2 + SourceGraphic); append the layer `<g>` last. + +**Read** (`readReportArchive`): size cap → `PDFDocument.load` (`invalid_pdf` +on failure) → attachment: the Filespec whose `/F` starts with `osteo-report`, +else the first `EmbeddedFile`, inflating `FlateDecode` streams under the cap +(`inflateFlate`, kept) → none: `attachment_stripped` when +`getKeywords()` contains `faunosteo-archive`, else `no_attachment` → cap → +`JSON.parse` → `readArchiveDocument(data, map)`: +1. locate the report: `data.report` when `typeof data.envelopeVersion === 'number'`, else `data`; +2. `readReportDocument(report, map)` (existing: v3 parsed, v2 migrated, other + → `UnsupportedReportVersionError(found)` → `incompatible_version`); +3. bare → `{ origin: 'bare_v3' | 'v2', archive: null }`; envelope with + `envelopeVersion !== 1` → `archive: null, snapshotRejected: 'unsupported_envelope'`; + envelope v1 → parse metadata + `sheetSnapshot` + `branding` + `labels`; + `BrandingSchema`/`PdfLabelSetSchema` failure → `'schema'`; + `assertSnapshot` failure → its reason; snapshot ref ≠ `report.sheet` → + `'sheet_mismatch'`; success → `archive` = the validated envelope. +Every other JSON failure → `no_attachment` as today. + +**App session** (`reportStore.ts`, `persistence.ts`): +- state `{ report: Report | null; archive: ReportArchiveEnvelope | null; activeObservationIndex }`; +- `hydrateReport(report)` kept (archive → null); new + `hydrateImport({ report, archive })`; `initReport` and `reset` clear `archive`; +- persistence: `osteo:draft` as today; `osteo:archive` written on + `hydrateImport`/`reset`/`initReport` only (not on every edit), restored with + the draft; `ArchivePersistence` beside `ReportPersistence`; +- `restoreDraft(index: SheetIndex)` loads the draft then rebases it on the + index when its sha differs (counts returned to the caller). +- `HomeRoute`: `readReportArchive` through `apps/app/src/pdf/import.ts` + (maps `ArchiveReadError` kinds to `ImportError` kinds, four kinds now) → + `rebaseReportOnSheet(outcome.report, index, outcome.archive?.sheetSnapshot ?? null)` + → `hydrateImport({ report: rebased, archive: outcome.archive })` → one + `window.alert` composed of the applicable lines (see §16) → `/editor`. +- `EditorRoute` export: `exportReportArchive({ report, sheet: buildSheetSnapshot(index.sheet, report), branding: await loadBranding(), labels: defaultPdfLabels, locale, rasterizer: browserRasterizer, exportedAt: new Date() })`; + download name unchanged; `warnings` logged with `console.warn`. +- The kept `archive` is exposed by the store for operation (1); no UI uses it + in this step (UX choice submitted after). + +**Branding in the app** (`apps/app/src/pdf/branding.ts`): `loadBranding(): +Promise<Branding>` fetches the four `public/` files by their current URLs +(each failure → slot `null` + `console.warn`, as today), PNG → base64, +Paws SVG kept as `{ kind: 'svg', svg }`; constants: `siteUrl +'https://faunosteo.com'`, poweredBy `{ url: 'https://zenquality.fr', +fallbackText: 'zenquality.fr' }`, partner `{ url: +'https://www.instagram.com/paws.iin.harmony', fallbackText: '@paws.iin.harmony' }`. +`// shortcut:` the site URL and partner constants live here until the config +carries them. + +**Bundle** (`vite/sheet-bundle.ts`, `sheets/provider.ts`): the payload gains +`assetHashes: Record<svg_asset_id, sha256>` from `assets.json`; `LoadedSheet` +gains `assetHashes`; `ref` gains `schemaVersion` and `speciesId` so it is a +`SheetSnapshotRef` (`SheetRef` of the report stays the 3-field subset). + +## 15. Caps, sanitiser, text + +| Item | Cap | +|---|---| +| PDF file | 50 MiB (existing) | +| attachment, raw and inflated | 16 MiB (existing) | +| snapshot assets | ≤ 4, each ≤ 2 MiB, total ≤ 6 MiB | +| snapshot document | ≤ 64 views, ≤ 1,024 annotations, ≤ 8,192 finding nodes, depth ≤ 8, labels ≤ 512 chars | +| branding | PNG base64 ≤ 512 KiB each, SVG ≤ 256 KiB, URLs http(s) ≤ 2,048 chars | +| report at export | ≤ 500 observations, ≤ 8 views per observation | +| sanitiser | ≤ 20,000 elements, nesting ≤ 64, ≤ 256 `<use>`, `stdDeviation` ≤ 100 | +| raster | width 1200 px, aspect clamped to [0.2, 2.0] | + +Sanitiser (`packages/pdf/src/svg/sanitize.ts`, `sanitizeSvgRoot(root: +Element): { removed: string[] }`, DOM Level 2 only: `childNodes`, +`attributes`, `removeAttribute`, `removeChild`, `tagName`): + +- elements kept: `svg g path circle ellipse rect line polyline polygon defs + linearGradient radialGradient stop filter feGaussianBlur feMerge feMergeNode + feOffset feFlood feComposite feBlend feColorMatrix clipPath mask title desc + switch use`; anything else is removed with its subtree (incl. `style`, + `script`, `image`, `a`, `foreignObject`, `text`, `feImage`, `feTurbulence`, + `feConvolveMatrix`, `animate*`, `set`); +- attributes kept: `id class d cx cy r rx ry x y x1 y1 x2 y2 dx dy width height + points transform viewBox version preserveAspectRatio fill fill-opacity + fill-rule stroke stroke-width stroke-linecap stroke-linejoin stroke-opacity + stroke-dasharray stroke-dashoffset stroke-miterlimit opacity filter + clip-path clip-rule mask display visibility color gradientUnits + gradientTransform spreadMethod offset stop-color stop-opacity stdDeviation + in in2 result mode operator k1 k2 k3 k4 flood-color flood-opacity type + values color-interpolation-filters filterUnits primitiveUnits + systemLanguage font-family font-size font-weight xmlns xmlns:xlink + xlink:href href style`; any other attribute (incl. every `on*`) is removed; +- `href`/`xlink:href` must match `^#[A-Za-z_][\w.:-]*$`; every `url(` in any + attribute value must be `url(#…)`; a `style` attribute containing `url(` + not followed by `#`, `expression(`, `@import`, `javascript:` or `behavior:` + is removed; `stdDeviation` above the cap is clamped; +- counters: elements, depth, `<use>`; over a cap → throws `SvgRejectedError`. +- `horse.svg` and `Paws_in_harmony.svg` must pass with `removed: []` and a + serialisation byte-identical to the parsed input (test). + +Text: `safeText(s: string): string` strips `\p{Cc}\p{Cf}

` except +none, then replaces every code point that +`Encodings.WinAnsi.canEncodeUnicodeCodePoint` (from +`@pdf-lib/standard-fonts`) refuses by `?`; used by `wrapLines`, every +`drawText` and `widthOfTextAtSize` in the engine; en and em dashes survive. +`formatDate` in the engine returns the input unchanged when it is not +`YYYY-MM-DD`. + +## 16. Messages (FR / EN keys, app dicts) + +| Key | FR | EN | +|---|---|---| +| `home.import.archive_ok` | Archive Faunosteo importée : bilan et instantané de la fiche d'origine conservés. | Faunosteo archive imported: report and the original sheet snapshot kept. | +| `home.import.snapshot_rejected` | Bilan récupéré, mais l'instantané de la fiche d'origine a été rejeté ({reason}) : cette archive ne pourra pas être reproduite telle quelle. | Report recovered, but the original sheet snapshot was rejected ({reason}): this archive cannot be reproduced as is. | +| `home.import.snapshot_reason.unsupported_envelope` | archive d'une version plus récente | archive from a newer version | +| `home.import.snapshot_reason.schema` | contenu invalide | invalid content | +| `home.import.snapshot_reason.caps` | taille ou complexité excessive | size or complexity over the limits | +| `home.import.snapshot_reason.integrity` | fiche incohérente | inconsistent sheet | +| `home.import.snapshot_reason.sheet_mismatch` | fiche différente de celle du bilan | sheet differs from the report's | +| `home.import.rebased` | Bilan ouvert sur la fiche actuelle, différente de celle de l'archive. Éléments non retrouvés : {count} (conservés avec leurs libellés). | Report opened on the current sheet, which differs from the archive's. Items not found: {count} (kept with their labels). | +| `home.import.error_attachment_stripped` | Ce PDF Faunosteo a perdu ses données embarquées (pièce jointe supprimée par un lecteur ou un optimiseur). Utilisez le fichier d'origine. | This Faunosteo PDF lost its embedded data (attachment removed by a viewer or an optimiser). Use the original file. | + +Alert composition after a successful import, lines joined by a blank line: +`migrated` (existing v2 message, when `origin === 'v2'` and counts > 0) · +`archive_ok` (when `archive` kept) · `snapshot_rejected` (when +`snapshotRejected`) · `rebased` (whenever the rebase ran, count may be 0). +No alert when nothing applies (bare v3 on the same sheet, as today). + +## 17. Goldens (Phase 0, frozen with the current code) + +Files under `apps/app/tests/fixtures/goldens/step6/`, JSON, numbers rounded +to 2 decimals, generated once by a `MAKE_GOLDEN=1` run of the golden test +file itself (`pdf.goldens.test.ts`: in generation mode it writes, otherwise it +asserts), and never regenerated without a user decision. + +- `text.<report>.<locale>.<logos>.json`: ordered `{ page, text, x, y, size, font }` + from a `PDFPage.prototype.drawText` spy (page = index of `this` in + `pdfDoc.getPages()` after save; font = `options.font.name`). +- `images.<report>.<logos>.json`: ordered `{ page, x, y, width, height }` from + a `drawImage` spy. +- `links.<report>.<logos>.json`: `{ page, rect, uri }` of every `/Annot /Link` + read back from the saved PDF. +- `views.<report>.json`: per `(observationId, viewId)`: `{ viewBox, halo, + highlighted: [{ tag, cx, cy, r, points, d, fill, fillOpacity, filter }], + nonHighlightedVisible: 0, dataAttributes: 0, titles }` from + `highlightedViewSvg` parsed with `DOMParser` (hidden markers are + `display="none"` today and absent in the engine: both count as not visible). +- Reports: `v2full` (migrated `report-v2.full.json`), `demo` + (`report-v3.demo.json`, new fixture: 6 observations covering main and head + views, vertebrae, bilateral sides, a vet-referral leaf, a leaf whose label + holds an en dash, free text, severity, next appointment), `v2unresolved` + (built with `tests/helpers/legacyLeaves.ts`: one observation per unresolved + leaf family, sphenoid and ssb, plus one resolved leaf). +- Logo modes: `nologos` (fetch 404) and `logos` (fetch stub serving the real + bytes of the four `public/` files; `rasterizeSvg` mocked to a fixed 2×1 PNG + so the partner logo width is deterministic). +- `report-v3.bare.pdf`: the demo report exported by the current code + (`nologos`), import fixture only. + +Characterisation tests written in Phase 0 and kept green unchanged: +`routes.HomeRoute.import.test.tsx` (v2 alert with count, four error kinds to +messages, navigation; `importReportFromPdf` mocked) and +`routes.EditorRoute.export.test.tsx` (export called with report, index and +locale; download name `bilan-<animal>-<date>.pdf`; failure alert). Phase 4 +adapts only the mocked module path and the call-shape assertion of T13 to the +engine API, nothing else. + +## 18. Executors and phases + +One executor per phase, closed contract in `.claude/tasks/contracts/`, TDD, +no commit (the orchestrator commits), report with test counts. Phases 1 and 2 +run in parallel. Verifier and security gates after Phase 5 and on request. + +| Phase | Owner | Exit | +|---|---|---| +| 0 freeze | executor | goldens + fixtures + T12/T13 committed, app suite green | +| 1 domain | executor | archive/{snapshot,envelope,branding,labels}, sheet-index moved, rebase, bundle hashes; domain + app suites green | +| 2 anatomy | executor | compose.ts, review drawing golden unchanged; anatomy suite green | +| 3 engine | executor | packages/pdf complete, T1 T3–T11 green, xmldom bundle size measured | +| 4 app | executor | routes, store, persistence, branding, messages; T2 T12–T15 green; old code removed | +| 5 docs + gates | orchestrator + verifier + security | docs, check, docker, EVAL |