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

+15
View File
@@ -0,0 +1,15 @@
import { CoreRuntime } from '@faunosteo/core-wasm'
import { nodeCoreRuntime } from '@faunosteo/core-wasm/node'
/** A loaded runtime on the shipped build (the package's Node source). */
export function testCoreRuntime(): Promise<CoreRuntime> {
return nodeCoreRuntime('pkg')
}
/** A runtime whose module never loads (CSP refusal, network failure). */
export function unavailableCoreRuntime(): CoreRuntime {
return new CoreRuntime({
compile: () => Promise.reject(new WebAssembly.CompileError('blocked')),
importGlue: () => Promise.reject(new TypeError('blocked')),
})
}
+12 -14
View File
@@ -1,10 +1,7 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
readReportDocument,
ReportSchema,
type Report,
} from '@faunosteo/domain'
import type { Report } from '@faunosteo/core-wasm/types'
import { importAttachment } from '@/pdf/import'
import type { SheetIndex } from '@/services/sheetIndex'
import { FIXTURES_DIR } from './goldens'
import {
@@ -16,7 +13,9 @@ import {
/**
* The three reports the Step 6 goldens and the R2 envelope freeze are drawn
* from: the Step 5 v2 archive fixture migrated, the v3 demo report, and a v2
* report whose sphenoid and ssb findings the migration cannot place.
* report whose sphenoid and ssb findings the migration cannot place. Since
* R2 they are read the way the application reads an attachment: the core's
* layered reading (v3 parsed, v2 migrated through the sheet's map).
*/
export const GOLDEN_REPORTS = ['v2full', 'demo', 'v2unresolved'] as const
@@ -38,21 +37,20 @@ function buildV2Unresolved(sheet: SheetIndex) {
(l) => l.zoneId === 'sphenoid' || l.zoneId === 'ssb',
)
const resolved = leaves.find((l) => l.zoneId === 'frontal')!
return readReportDocument(
return importAttachment(
leavesAsV2Report([...unresolvedFamilies, resolved]),
sheet.sheet.migrationMap,
)
sheet,
).read
}
export function buildGoldenReports(sheet: SheetIndex): GoldenReports {
const v2unresolved = buildV2Unresolved(sheet)
return {
reports: {
v2full: readReportDocument(
readJson('report-v2.full.json'),
sheet.sheet.migrationMap,
).report,
demo: ReportSchema.parse(readJson('report-v3.demo.json')),
v2full: importAttachment(readJson('report-v2.full.json'), sheet).read
.report,
demo: importAttachment(readJson('report-v3.demo.json'), sheet).read
.report,
v2unresolved: v2unresolved.report,
},
unresolvedOfV2Unresolved: v2unresolved.unresolvedFindings,
+9 -2
View File
@@ -17,8 +17,11 @@ import type {
Observation,
Report,
SheetSnapshot,
} from '@faunosteo/domain'
} from '@faunosteo/core-wasm/types'
import { composeHighlightedViewSvg } from '@faunosteo/pdf'
/** The engine's own (Zod-inferred) types of the same JSON contracts. */
type EngineView = Parameters<typeof composeHighlightedViewSvg>
import { nologosBranding } from './sheet'
/**
@@ -241,7 +244,11 @@ export function snapshotView(
observation: Observation,
viewId: string,
): ViewSnapshot {
const svg = composeHighlightedViewSvg(sheet, viewId, observation)
const svg = composeHighlightedViewSvg(
sheet as EngineView[0],
viewId,
observation as EngineView[2],
)
const root = new DOMParser().parseFromString(
svg,
'image/svg+xml',
+54 -24
View File
@@ -1,21 +1,15 @@
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { resolve } from 'node:path'
import {
AnatomicalSheetDocumentSchema,
ReportV2Schema,
type AnatomicalSheetDocument,
type FindingCategory,
type FindingNode,
type ObservationV2,
type ReportV2,
} from '@faunosteo/domain'
import type { LocalizedText } from '@faunosteo/core-wasm/types'
/**
* The legacy catalog as the application's archive knew it: every leaf of the
* generated baseline (`legacy-import/document.json`) becomes a Report v2
* finding, grouped in one observation per zone. Mirrors the anatomy package
* helper of the same name; both read the committed seed, never a copy.
* helper of the same name; both read the committed seed, never a copy. The
* baseline is read as its authoring form (leaves carry no `children` key);
* the core reads the v2 report built from it.
*/
const BASELINE = resolve(
@@ -23,6 +17,18 @@ const BASELINE = resolve(
'../../../../../supabase/seed/anatomical-sheets/equine/legacy-import/document.json',
)
/** A category or node of the baseline in its authoring form. */
interface BaselineNode {
id: string
name: LocalizedText
requires_vet_referral?: boolean
children?: BaselineNode[]
}
export interface LegacyBaseline {
finding_zones: { id: string; categories: BaselineNode[] }[]
}
export interface LegacyLeaf {
zoneId: string
path: string[]
@@ -30,25 +36,49 @@ export interface LegacyLeaf {
vet: boolean
}
export function loadLegacyBaseline(): AnatomicalSheetDocument {
return AnatomicalSheetDocumentSchema.parse(
JSON.parse(readFileSync(BASELINE, 'utf8')),
)
/** A Report v2 document as the deployed application wrote it (input of the migration). */
export interface ReportV2Fixture {
version: 2
id: string
createdAt: string
date: string
practitioner: { name: string }
animal: { speciesId: string; name: string }
owner: { name: string }
observations: {
id: string
zones: unknown[]
findings: {
zoneId: string
path: string[]
labelFrSnapshot: string
labelEnSnapshot: string
requiresVetReferral?: true
}[]
freeTextFindings: string[]
comment: string
}[]
conclusion: string
recommendations: string
}
export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
export function loadLegacyBaseline(): LegacyBaseline {
return JSON.parse(readFileSync(BASELINE, 'utf8')) as LegacyBaseline
}
export function legacyLeaves(doc: LegacyBaseline): LegacyLeaf[] {
const out: LegacyLeaf[] = []
const walk = (
zoneId: string,
nodes: readonly (FindingCategory | FindingNode)[],
nodes: readonly BaselineNode[],
prefix: string[],
) => {
for (const node of nodes) {
const path = [...prefix, node.id]
if (node.children.length > 0) walk(zoneId, node.children, path)
const children = node.children ?? []
if (children.length > 0) walk(zoneId, children, path)
else {
const vet =
'requires_vet_referral' in node && node.requires_vet_referral
const vet = node.requires_vet_referral === true
out.push({ zoneId, path, name: node.name, vet })
}
}
@@ -57,8 +87,8 @@ export function legacyLeaves(doc: AnatomicalSheetDocument): LegacyLeaf[] {
return out
}
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
const byZone = new Map<string, ObservationV2>()
export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2Fixture {
const byZone = new Map<string, ReportV2Fixture['observations'][number]>()
for (const leaf of leaves) {
let obs = byZone.get(leaf.zoneId)
if (!obs) {
@@ -76,10 +106,10 @@ export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
path: leaf.path,
labelFrSnapshot: leaf.name.fr,
labelEnSnapshot: leaf.name.en || leaf.name.fr,
...(leaf.vet ? { requiresVetReferral: true } : {}),
...(leaf.vet ? { requiresVetReferral: true as const } : {}),
})
}
return ReportV2Schema.parse({
return {
version: 2,
id: 'all-leaves',
createdAt: '2026-10-10T00:00:00Z',
@@ -90,5 +120,5 @@ export function leavesAsV2Report(leaves: LegacyLeaf[]): ReportV2 {
observations: [...byZone.values()],
conclusion: '',
recommendations: '',
})
}
}
+70 -15
View File
@@ -1,16 +1,20 @@
import {
buildSheetSnapshot,
ENVELOPE_FORMAT,
ENVELOPE_VERSION,
REPORT_VERSION,
type Branding,
type Observation,
type Report,
type ReportArchiveEnvelope,
} from '@faunosteo/domain'
import type {
Branding,
FindingCategory,
FindingNode,
Observation,
Report,
ReportArchiveEnvelope,
SheetSnapshot,
} from '@faunosteo/core-wasm/types'
import { defaultPdfLabels } from '@faunosteo/pdf'
import type { SheetIndexData } from '@faunosteo/core-wasm/types'
import type { ReportMigrationMap } from '@faunosteo/core-wasm/n-1'
import { coreRuntime } from '@/core/runtime'
import { SheetOps } from '@/core/sheetOps'
import { bundledSheetProvider, type BundledSheetData } from '@/sheets/provider'
import { loadSheetIndex } from '@/sheets/useSheet'
import type { SheetIndex } from '@/services/sheetIndex'
import { SheetIndex } from '@/services/sheetIndex'
/** The bundled reference draft (vitest runs the sheet-bundle plugin in draft mode). */
export async function loadTestSheet(): Promise<SheetIndex> {
@@ -28,7 +32,7 @@ export function minimalReport(
patch: Partial<Report> = {},
): Report {
return {
version: REPORT_VERSION,
version: 3,
id: 'r1',
createdAt: '2026-10-10T10:00:00Z',
date: '2026-10-10',
@@ -63,19 +67,70 @@ export function nologosBranding(): Branding {
}
}
/** The snapshot of `sheet` an archive of `report` carries, built by the core. */
export function sheetSnapshot(
sheet: SheetIndex,
report: Report,
): SheetSnapshot {
const outcome = sheet.ops.snapshot(report)
if (!outcome.ok) throw new Error(`snapshot failed: ${outcome.kind}`)
return outcome.value
}
/** A valid Step 6 envelope for `report`, snapshotted on `sheet` (no logos). */
export function archiveEnvelope(
sheet: SheetIndex,
report: Report,
): ReportArchiveEnvelope {
return {
format: ENVELOPE_FORMAT,
envelopeVersion: ENVELOPE_VERSION,
format: 'faunosteo-report-archive',
envelopeVersion: 1,
exportedAt: '2026-10-11T12:00:00.000Z',
locale: 'fr',
report,
sheetSnapshot: buildSheetSnapshot(sheet.sheet, report),
sheetSnapshot: sheetSnapshot(sheet, report),
branding: nologosBranding(),
labels: defaultPdfLabels,
}
}
/** The bundled migration map, for the frozen N-1 readers (the core keeps its own copy). */
export async function bundledMigrationMap(): Promise<ReportMigrationMap> {
return (await bundledSheet()).migrationMap as ReportMigrationMap
}
/**
* The category or node at a path of a finding zone (first match at each level, as the
* core's walk), read from the parsed document: the tests' view of what `hasNode` answers.
*/
export function findingNodeAt(
sheet: SheetIndex,
zoneId: string,
path: readonly string[],
): FindingCategory | FindingNode | undefined {
if (path.length === 0) return undefined
let nodes: readonly (FindingCategory | FindingNode)[] =
sheet.findingZone(zoneId)?.categories ?? []
let node: FindingCategory | FindingNode | undefined
for (const segment of path) {
node = nodes.find((n) => n.id === segment)
if (!node) return undefined
nodes = node.children
}
return node
}
/** The bundled payload as the provider hands it to the core. */
export async function bundledSheet(): Promise<BundledSheetData> {
const bundle = await bundledSheetProvider.getReferenceSheet('equine')
if (!bundle) throw new Error('bundled sheet missing: run pnpm import:equine')
return bundle
}
/** Another sheet loaded in the core (a revised catalog), outside the provider's cache. */
export function sheetFromBundle(bundle: BundledSheetData): SheetIndex {
const session = coreRuntime().sheet(JSON.stringify(bundle))
const data = session.call<SheetIndexData>('index_data', '')
if (!data.ok) throw new Error(`sheet refused by the core: ${data.kind}`)
return new SheetIndex(data.value, bundle.assets, new SheetOps(session))
}