feat(app): R2 switch — the application runs its domain rules in the Rust core

Consumers now fed by the core (crates/core through @faunosteo/core-wasm):
- the sheet: the bundled payload is parsed and indexed by the core
  (SheetHandle, SheetIndexData); SheetIndex reads precomputed tables only;
- the store: new report, add / remove / move observation, draft restore
  (v2 migration + rebase) through the core, actions answering { ok };
- the editor click chain (zone.click), laterality and vertebra pickers
  (zone.add_sides, vertebra.initial / sync / select), the findings picker
  (finding.toggle by clicked leaf position), zone removal;
- the import: engine byte scan (TypeScript until R4), then the core's
  layered reading and rebase in one call; the export: the core builds the
  sheet snapshot, the frozen TypeScript engine writes the PDF (R4).
Lazy core: Home and the new-report form read the sheet availability from
the bundle and load the module on import / submit only; the auth shell
never references it. Degraded states (core_unavailable, invalid_sheet)
show the validated notice with a retry and never redirect or touch the
draft; an unreadable draft or archive is set aside under
osteo:quarantine:* (only content kinds; a failed write keeps it in place
and the editor stays), a rebase that flags items keeps the raw pre-rebase
draft. Four strings, wording validated by the owner.
Deleted: services/zoneInteraction.ts and its suite (13 cases ported to
cargo), the TypeScript Finding builder and vertebra selection rules of the
pickers, store rules, persistence parsing, hydrateReport. ESLint forbids
@faunosteo/domain in apps/app/src; the report:compare CLI keeps the frozen
domain until R4 (scripts/compare/sheet.ts). App suite 313/313 on the real
core (24 new tests: quarantine, degraded editor, core failures, N-1
reader); step6 goldens and the frozen envelopes unchanged.
This commit is contained in:
bchanot committed 2026-10-14 00:41:34 +02:00
1 parent 794dfd9d0b
commit 74fcb37564
65 files changed
+2227 -1678

No files matched your search

+42 -32
View File
@@ -1,33 +1,39 @@
import {
readReportDocument,
ReportArchiveEnvelopeSchema,
type Report,
type ReportArchiveEnvelope,
type ReportMigrationMap,
} from '@faunosteo/domain'
import type { Report, ReportArchiveEnvelope } from '@faunosteo/core-wasm/types'
/**
* Where the session lives between renders. The report draft is mirrored on
* every change; the archive an import brought along (the envelope of a
* Step 6 PDF) is written only when the session starts or ends, so a stale
* draft can still be rebased with the labels of its original sheet. One
* implementation today (per-tab sessionStorage); the Supabase and outbox
* adapters of later steps implement the same interfaces.
* draft can still be rebased with the labels of its original sheet. The
* texts are read raw: the core parses them (R2), and a text the running
* build cannot read is set aside under a quarantine key instead of being
* dropped. One implementation today (per-tab sessionStorage); the Supabase
* and outbox adapters of later steps implement the same interfaces.
*/
export interface ReportPersistence {
load(map: ReportMigrationMap): Report | null
/** The raw draft text, null when there is none. */
loadText(): string | null
save(report: Report | null): void
}
export interface ArchivePersistence {
load(): ReportArchiveEnvelope | null
loadText(): string | null
save(archive: ReportArchiveEnvelope | null): void
}
export const DRAFT_KEY = 'osteo:draft'
export const ARCHIVE_KEY = 'osteo:archive'
/** Unreadable texts and the pre-rebase draft, newest only (R2 plan rev 2). */
export const QUARANTINE_KEYS = {
draft: 'osteo:quarantine:draft',
archive: 'osteo:quarantine:archive',
draftPreRebase: 'osteo:quarantine:draft-pre-rebase',
} as const
export type QuarantineSlot = keyof typeof QUARANTINE_KEYS
function storage(): Storage | null {
return typeof sessionStorage === 'undefined' ? null : sessionStorage
}
@@ -47,33 +53,37 @@ function writeOrRemove(key: string, value: unknown): void {
}
}
/**
* Copies `raw` into its quarantine slot, then removes `source` (when given)
* only if that copy succeeded: a full storage keeps the text where it was.
* Returns whether the text is now in quarantine.
*/
export function quarantine(
slot: QuarantineSlot,
raw: string,
source?: string,
): boolean {
const store = storage()
if (!store) return false
try {
store.setItem(QUARANTINE_KEYS[slot], raw)
} catch (err) {
if (import.meta.env.DEV) console.warn(`${slot} not set aside`, err)
return false
}
if (source) store.removeItem(source)
return true
}
export const sessionStoragePersistence: ReportPersistence = {
load(map) {
const raw = storage()?.getItem(DRAFT_KEY)
if (!raw) return null
try {
return readReportDocument(JSON.parse(raw), map).report
} catch (err) {
if (import.meta.env.DEV) console.warn('osteo:draft ignored', err)
return null
}
},
loadText: () => storage()?.getItem(DRAFT_KEY) ?? null,
save(report) {
writeOrRemove(DRAFT_KEY, report)
},
}
export const sessionStorageArchivePersistence: ArchivePersistence = {
load() {
const raw = storage()?.getItem(ARCHIVE_KEY)
if (!raw) return null
try {
const parsed = ReportArchiveEnvelopeSchema.safeParse(JSON.parse(raw))
return parsed.success ? parsed.data : null
} catch {
return null
}
},
loadText: () => storage()?.getItem(ARCHIVE_KEY) ?? null,
save(archive) {
writeOrRemove(ARCHIVE_KEY, archive)
},
+15 -2
View File
@@ -1,4 +1,17 @@
import { PractitionerSchema, type Practitioner } from '@faunosteo/domain'
import { z } from 'zod'
import type { Practitioner } from '@faunosteo/core-wasm/types'
/**
* Prefill of the practitioner form (D-R7: form validation stays TypeScript, the core is
* not loaded on the new-report page): the cached value is used only when it still has the
* shape of the report's practitioner (name required, the rest optional text).
*/
const CachedPractitionerSchema: z.ZodType<Practitioner> = z.object({
name: z.string().min(1),
cabinet: z.string().optional(),
contact: z.string().optional(),
siret: z.string().optional(),
})
const STORAGE_KEY = 'osteo:lastPractitioner'
@@ -8,7 +21,7 @@ export function readCachedPractitioner(): Practitioner | undefined {
if (!raw) return undefined
try {
const data = JSON.parse(raw)
const parsed = PractitionerSchema.safeParse(data)
const parsed = CachedPractitionerSchema.safeParse(data)
return parsed.success ? parsed.data : undefined
} catch {
return undefined
+149 -123
View File
@@ -1,21 +1,25 @@
import { create } from 'zustand'
import {
rebaseReportOnSheet,
REPORT_VERSION,
type Animal,
type NextAppointment,
type Observation,
type Owner,
type Practitioner,
type RebaseOutcome,
type Report,
type ReportArchiveEnvelope,
type SheetRef,
} from '@faunosteo/domain'
import type {
Animal,
NewReportDraft,
NextAppointment,
Observation,
Owner,
Practitioner,
RebaseOutcome,
Report,
ReportArchiveEnvelope,
SheetRef,
} from '@faunosteo/core-wasm/types'
import type { CoreOutcome } from '@faunosteo/core-wasm'
import { reportOps } from '@/core/reportOps'
import { generateId } from '@/lib/id'
import { nowIso } from '@/lib/dates'
import type { SheetIndex } from '@/services/sheetIndex'
import {
ARCHIVE_KEY,
DRAFT_KEY,
quarantine,
sessionStorageArchivePersistence,
sessionStoragePersistence,
type ArchivePersistence,
@@ -23,45 +27,60 @@ import {
} from './persistence'
/**
* In-memory report document (v3) and its editing actions. Observation-level
* zone rules live in services/zoneInteraction; the store only replaces
* documents. The per-tab draft is mirrored through the persistence adapter
* and restored once the sheet is known; a draft written on another revision
* of the sheet is rebased on restore. The archive an import brought along
* (STEP6 §14 "App session") is kept beside the report for later operations
* and written only when the session starts or ends.
* In-memory report document (v3) and its editing actions. Every report that
* enters the store comes from the core (R2): a new report, a restored draft,
* an import; the observation list rules (add, remove, move) run in the core
* too, and the editor's reducers hand back core-built observations. Form
* values (identity, texts, an observation's comment, severity or free
* findings) are plain assignments. An action whose core call fails changes
* nothing and answers `{ ok: false }`; the caller tells the practitioner.
* The per-tab draft is mirrored through the persistence adapter and restored
* once the sheet is known; the archive an import brought along is kept
* beside the report and written only when the session starts or ends.
*/
/** What a new report needs before the store stamps version, id and dates. */
export type NewReportDraft = Omit<
Report,
'version' | 'id' | 'createdAt' | 'sheet' | 'localAnnotations'
>
export type { NewReportDraft }
export interface ImportedSession {
report: Report
archive: ReportArchiveEnvelope | null
}
export interface ActionResult {
ok: boolean
}
/** What a draft restore did; `null` from the action when there was nothing to restore. */
export type RestoreResult =
| { kind: 'restored'; rebase: RebaseOutcome }
/** The draft is unreadable by this build: set aside under a quarantine key. */
| { kind: 'quarantined' }
/**
* The draft is unreadable but could not be set aside (storage full): it stays in
* `osteo:draft`, and the caller must not start anything that would overwrite it.
*/
| { kind: 'unreadable_kept' }
/** The core failed: nothing read, nothing written, the draft is where it was. */
| { kind: 'core_unavailable' }
export interface ReportStore {
report: Report | null
/** The envelope of the imported archive, as exported; null otherwise. */
archive: ReportArchiveEnvelope | null
activeObservationIndex: number
initReport: (draft: NewReportDraft, sheet: SheetRef) => void
hydrateReport: (report: Report) => void
/** Opens an imported report (already rebased) with its archive. */
initReport: (draft: NewReportDraft, sheet: SheetRef) => ActionResult
/** Opens an imported report (read and rebased by the core) with its archive. */
hydrateImport: (session: ImportedSession) => void
/**
* Restores the per-tab draft on the loaded sheet, rebasing it when it was
* written on another revision; a no-op when a report is already open.
* Returns the rebase outcome, null when nothing was restored.
* written on another revision; a no-op (null) when a report is already open
* or there is no draft.
*/
restoreDraft: (index: SheetIndex) => RebaseOutcome | null
addObservation: () => void
removeObservation: (index: number) => void
moveObservationUp: (index: number) => void
moveObservationDown: (index: number) => void
restoreDraft: (index: SheetIndex) => RestoreResult | null
addObservation: () => ActionResult
removeObservation: (index: number) => ActionResult
moveObservationUp: (index: number) => ActionResult
moveObservationDown: (index: number) => ActionResult
updateObservation: (index: number, obs: Observation) => void
setActiveObservation: (index: number) => void
setPractitioner: (next: Practitioner) => void
@@ -73,47 +92,68 @@ export interface ReportStore {
reset: () => void
}
export function emptyObservation(): Observation {
return {
id: generateId(),
zones: [],
findings: [],
freeTextFindings: [],
comment: '',
}
}
/** A fresh v3 document: the store stamps version, id, dates and the sheet. */
function newReport(draft: NewReportDraft, sheet: SheetRef): Report {
return {
...draft,
version: REPORT_VERSION,
id: generateId(),
createdAt: nowIso(),
sheet,
observations:
draft.observations.length === 0
? [emptyObservation()]
: draft.observations,
localAnnotations: [],
}
}
function swapped(list: Observation[], i: number, j: number): Observation[] {
const next = [...list]
;[next[i], next[j]] = [next[j]!, next[i]!]
return next
}
type Patch = Partial<
Pick<ReportStore, 'report' | 'archive' | 'activeObservationIndex'>
>
type Setter = (fn: (s: ReportStore) => Patch | ReportStore) => void
type Getter = () => ReportStore
const OK: ActionResult = { ok: true }
const FAILED: ActionResult = { ok: false }
function onReport(set: Setter, update: (r: Report, s: ReportStore) => Patch) {
set((s) => (s.report ? update(s.report, s) : s))
}
/** Applies a core-built report with its active index; nothing changes on failure. */
function applyCore(
set: Setter,
get: Getter,
run: (report: Report) => CoreOutcome<Report>,
active: (next: Report, s: ReportStore) => number,
): ActionResult {
const state = get()
if (!state.report) return OK
const outcome = run(state.report)
if (!outcome.ok) return FAILED
set(() => ({
report: outcome.value,
activeObservationIndex: active(outcome.value, state),
}))
return OK
}
/** Reads the draft through the core; unreadable content goes to quarantine, never away. */
function restore(
index: SheetIndex,
persistence: ReportPersistence,
archives: ArchivePersistence,
): { result: RestoreResult; patch?: Patch } | null {
const draft = persistence.loadText()
if (draft === null) return null
const archiveText = archives.loadText()
const outcome = index.ops.restoreDraft(draft, archiveText)
if (!outcome.ok) {
// Only an unreadable draft is set aside; a core or sheet failure leaves it in place.
if (outcome.kind !== 'invalid' && outcome.kind !== 'unsupported_version') {
return { result: { kind: 'core_unavailable' } }
}
const setAside = quarantine('draft', draft, DRAFT_KEY)
return { result: { kind: setAside ? 'quarantined' : 'unreadable_kept' } }
}
const { rebase, archive, archiveRejected } = outcome.value
if (archiveRejected && archiveText !== null) {
quarantine('archive', archiveText, ARCHIVE_KEY)
}
if (rebase.rebased && rebase.unresolvedZones + rebase.unresolvedFindings > 0) {
quarantine('draftPreRebase', draft)
}
return {
result: { kind: 'restored', rebase },
patch: { report: rebase.report, archive, activeObservationIndex: 0 },
}
}
export function createReportStore(
persistence: ReportPersistence,
archives: ArchivePersistence,
@@ -129,78 +169,64 @@ export function createReportStore(
archive: null,
activeObservationIndex: 0,
initReport: (draft, sheet) =>
set(
withArchive(
{ report: newReport(draft, sheet), activeObservationIndex: 0 },
null,
),
),
hydrateReport: (report) =>
set(withArchive({ report, activeObservationIndex: 0 }, null)),
initReport: (draft, sheet) => {
const outcome = reportOps.newReport({
draft,
sheet,
id: generateId(),
createdAt: nowIso(),
observationId: generateId(),
})
if (!outcome.ok) return FAILED
set(withArchive({ report: outcome.value, activeObservationIndex: 0 }, null))
return OK
},
hydrateImport: ({ report, archive }) =>
set(withArchive({ report, activeObservationIndex: 0 }, archive)),
restoreDraft: (index) => {
if (get().report) return null
const draft = persistence.load(index.sheet.migrationMap)
if (!draft) return null
const archive = archives.load()
const rebase = rebaseReportOnSheet(
draft,
index,
archive?.sheetSnapshot ?? null,
)
set({ report: rebase.report, archive, activeObservationIndex: 0 })
return rebase
const restored = restore(index, persistence, archives)
if (!restored) return null
if (restored.patch) set(restored.patch)
return restored.result
},
addObservation: () =>
onReport(set, (r) => {
const observations = [...r.observations, emptyObservation()]
return {
report: { ...r, observations },
activeObservationIndex: observations.length - 1,
}
}),
applyCore(
set,
get,
(r) => reportOps.addObservation(r, generateId()),
(next) => next.observations.length - 1,
),
removeObservation: (index) =>
onReport(set, (r, s) => {
const observations = r.observations.filter((_, i) => i !== index)
const active = Math.min(
s.activeObservationIndex,
Math.max(0, observations.length - 1),
)
return {
report: { ...r, observations },
activeObservationIndex: active,
}
}),
applyCore(
set,
get,
(r) => reportOps.removeObservation(r, index),
(next, s) =>
Math.min(
s.activeObservationIndex,
Math.max(0, next.observations.length - 1),
),
),
moveObservationUp: (index) =>
onReport(set, (r) =>
index <= 0
? {}
: {
report: {
...r,
observations: swapped(r.observations, index - 1, index),
},
},
applyCore(
set,
get,
(r) => reportOps.moveObservation(r, index, 'up'),
(_, s) => s.activeObservationIndex,
),
moveObservationDown: (index) =>
onReport(set, (r) =>
index >= r.observations.length - 1
? {}
: {
report: {
...r,
observations: swapped(r.observations, index, index + 1),
},
},
applyCore(
set,
get,
(r) => reportOps.moveObservation(r, index, 'down'),
(_, s) => s.activeObservationIndex,
),
updateObservation: (index, obs) =>