Files
faunosteo/.claude/audits/R5_PIPELINE_INVENTORY.md
T

35 KiB
Raw Blame History

R5 inventory: the TypeScript anatomy pipeline (packages/anatomy)

Root: /home/bchanot/Documents/faunosteo (paths repo-relative). Branch feature/rust-r5-pipeline-core cut at 9c0117a. Read-only analysis by an analyzer agent (one in-memory probe of the pipeline functions for §4.3), saved by the orchestrator. Runtime: Node 24.21.0, ICU 78.3, Unicode 17.0.

Summary

  1. packages/anatomy has 43 source files and 4,897 lines: legacy 1,842, curation 2,329, render 553, cli 119, root 54. Tests are 2,553 lines; the upload script is 99.
  2. The runtime libraries are Prettier 3.8.3, @xmldom/xmldom 0.9.12 and Zod 3.25.76, plus node:crypto, node:fs and node:util. Prettier and xmldom are declared as devDependencies but used at runtime.
  3. There are 18 generated files. Ten go through Prettier: 7 JSON and 3 Markdown. Five go through the xmldom XMLSerializer (horse.svg and 4 review SVGs). One is a raw SQL template, and two are byte copies of the legacy SVGs.
  4. documentSha256 is the sha256 of the UTF-8 bytes of the Prettier-formatted draft/document.json, trailing newline included (pipeline.ts:159-165,185, ids.ts:15-17). Checked equal to the sha256 of the committed file. equine_draft.sql does not carry it; it embeds the document text instead.
  5. That hash is pinned in 18 tracked files (seed, crate oracles, app goldens, R4 PDFs). Any byte change in the draft document cascades to all of them.
  6. Measured on today's data, Prettier changes only Markdown table padding (134, 863 and 52 lines in the three reports). For JSON it changes layout only: short arrays collapsed onto one line and a trailing newline. The data is identical after re-parsing.
  7. The JSON key order is JS insertion order of the working document, which is never re-parsed by Zod. For example, review_status is appended last on annotations by the B/C review rule.
  8. UUIDs are built from the first 16 bytes of sha256(name), with the version nibble set to 5 and variant bits 10. Names are faunosteo:asset:<sha> and faunosteo:sheet:equine:v1 (gives 503dc301…). Both checked.
  9. JS-specific hazards: number printing, Math.round, Number('') = 0; Unicode \s, split(':', 2), NFD plus toLowerCase; UTF-16 sorting and slicing; xmldom's />, escaping and namespace rules; Prettier's printNumber and its string-width function. None uses dates or randomness, and nothing calls localeCompare.
  10. Tests: 111 declarations, 131 cases once it.each rows are expanded. The golden test compares the exact text of every generated file; no comparison works on parsed trees.
  11. Five tests depend on the TS render/ code. Three use it directly (render.layer, render.compose, r3.layer-oracles). Two use it through renderDraftArtifacts → app-review → composeViewSvg (seed.golden, curation.pipeline).
  12. 22 source files import @faunosteo/domain. Only 5 runtime symbols are used: the document schema, validateSheetDocument, the schema version, the stable-id pattern and ReferenceSchema. All already have Rust counterparts from R2.
  13. @faunosteo/anatomy has no code consumer outside itself, only the root import:equine script. @faunosteo/domain is imported only by packages/anatomy.
  14. Deleting the packages breaks things beyond imports: Rust tests read packages/domain/tests/fixtures/report-v2.{full,minimal}.json, and apps/app/tests/unit/r4.census.test.ts:80-90 asserts xmldom sits under packages/anatomy.
  15. Open decision: the D-R5 hash rule as written (hash the bytes Rust emits) versus the owner's amendment in BDR-045 (a canonical-JSON fingerprint, decision "prepared for R5").

1. Package and tooling

  • packages/anatomy/package.json: exports . → src/index.ts and ./render → src/render/index.ts (:10-13); script import:equine = tsx src/cli/import-equine.ts (:20); dependencies @faunosteo/domain workspace and zod ^3.24.1 (:22-25); @xmldom/xmldom ^0.9.8 and prettier ^3.4.2 are devDependencies (:28, :31), yet src/format.ts and src/legacy/svg.ts import them at runtime, as do curation/{assets,overlay,app-review}.ts.
  • Lockfile (importer packages/anatomy): zod 3.25.76, @xmldom/xmldom 0.9.12, prettier 3.8.3, tsx 4.23.15, typescript 5.9.3, vitest 3.2.7, @types/node 20.19.41. Each of prettier and xmldom has a single version in the whole lockfile.
  • vitest.config.ts: environment node, globals, include tests/**/*.test.ts. tsconfig.json: ES2022, bundler resolution, strict, noEmit, covers src and tests. eslint.config.js: typescript-eslint recommended.
  • Root wiring: package.json:28 import:equine = pnpm --filter @faunosteo/anatomy import:equine; package.json:36 assets:upload → packages/supabase/package.json:21 node scripts/upload-sheet-assets.ts (Node's native type stripping, not tsx).
  • Prettier options (src/format.ts:9-19) are identical to the root .prettierrc.json. Root format = prettier --write . (package.json:24). .prettierignore does not exclude supabase/seed/**, so a root format run also rewrites the generated .json and .md files.

2. Lines of code (wc -l)

Area Files Lines
src/legacy 15 1,842
src/curation 19 2,329
src/render 5 553
src/{index,format,markdown}.ts 3 54
src/cli/import-equine.ts 1 119
src total 43 4,897
tests (16 suites + helpers.ts + fixtures/mini-sheet.ts) 18 2,553
packages/supabase/scripts/upload-sheet-assets.ts 1 99

3. Modules (path (lines): exports with line, inputs → outputs, external deps)

3.1 Shared and entry

Module Exports In → Out Deps
index.ts (3) re-exports legacy, curation, render
format.ts (30) formatJson:21, formatMarkdown:28 value → Prettier(JSON.stringify(v,null,2), parser json); text → Prettier markdown prettier
markdown.ts (21) cell:6, table:11, code:19 null → -; escapes | and LF only; tables unpadded (Prettier pads them)
cli/import-equine.ts (119) none (main) repo → writes legacy-import/ and draft/; prints 2 summary lines node:fs/promises, node:path, node:url

CLI behaviour: REPO_ROOT is 4 levels up (:32). Strings are written with writeFile(…,'utf8'), otherwise copyFile (:37-44). removeStale deletes every file in the two folders that the run did not produce (:47-55). The legacy folder gets renderArtifacts output plus the two SVG copies (:104-107). The draft folder gets renderDraftArtifacts output plus assets/<file> = cleanedSvg (:108-111).

3.2 legacy/ (importer, Step 4b)

Module Exports In → Out Deps
sources.ts (54) EQUINE_SOURCE_PATHS:10, EQUINE_{LEGACY_IMPORT,CURATION,DRAFT}_DIR:20,23,26, readEquineSources:32 root → SVG bytes, catalog text, vertebrae text node:fs, node:path
types.ts (115) Anomaly, AssetRecord, LegacyIdMap, ImportResult, … types domain (types)
ids.ts (54) sha256Hex:15, deterministicUuid:19, assetIdFromSha256:33, sheetIdFor:37, slugify:42, isStableId:52 node:crypto, domain STABLE_ID_PATTERN
svg.ts (116) parseAnnotatedSvg:94 SVG text → viewBox, one record per data-anno-id (first element wins, elementCount), anomalies xmldom DOMParser
vertebrae.ts (51) parseVertebralFormula:16, vertebralRegions:45 vertebrae.ts text, parsed with regexes (not imported) → counts, "varies A–B"
regions.ts (46) inferRegionCode:36 FR then EN label → code/root; root table :8-14
categories.ts (98) normaliseCategoryId:37, mapCategories:82 annotations → categories in first-seen order; 2 slug fixes :14-17; authored labels :20-29
catalog.ts (249) parseLegacyCatalog:73, categoryKind:81, countTree:169, assertNothingDropped:206, mapCatalog:233 pathologies.json → lean finding zones (optional keys only when present); throws if output count ≠ input
catalog-checks.ts (102) catalogAnomalies:96 foreign prefix, anamnesis variants, cross-zone duplicates
annotations.ts (207) zoneNameKey:37, mapAnnotation:184 annotation + map fr\nen → zone → input annotation, row, region, anomalies
authored-labels.ts (41) authoredLabelAnomalies:30 document → label.authored anomalies
importer.ts (343) importEquineLegacy:313, MAIN/HEAD_VIEW_ID:50-51 EquineLegacyInput → ImportResult domain schema and validate
report.ts (325) renderImportReport:310 ImportResult → French markdown, 9 sections, trailing \n
artifacts.ts (22) renderArtifacts:13 ImportResult → 4 formatted texts format.ts

Facts about the importer: the document written is the unparsed input form (importer.ts:322); the Zod parse (:317) only feeds validateSheetDocument (:341). Two guards throw: annotations read ≠ written (:223-228), and inline sources present (:234-239). The trigger id is ${opensDetail}-trigger (annotations.ts:117); an observable annotation's id is the zone id, or slugify(name.en) as a fallback (:171). The slugify fallbacks never fire on today's data: legacy-id-map.json has finding_nodes: {}, and all 26 observables resolve to a zone.

3.3 curation/ (Steps 4c and 5)

Module Exports In → Out Deps
schema.ts (172) OpSchema:101, ChangeSchema:110, ChangesetSchema:132, ReferencesFileSchema:141, needsConfirmation:164, changeSummary:168, ASSET_CHANGE_ID:29 strict Zod; priority default medium (:119); level C needs a question (:123-126); duplicate ids refused (:128-148) zod, domain ReferenceSchema
sources.ts (38) readEquineCuration:26 curation/{references,changes}.json → parsed node:fs
targets.ts (195) parseTarget:58, formatTarget:73, locate:131, zoneFindings:151, allFindings:158, findingScope:167, childList:185, childPrefix:192 target grammar (:2-5) over plain JSON
fields.ts (80) SETTABLE table (:9-43), splitField:45, readField:62, writeField:72 dot paths; missing intermediate objects created
ops.ts (225) applyOp:209, assertDeclared:184 set, rename, add, remove, move, cite → in-place edits plus records node:util isDeepStrictEqual
rename.ts (57) propagateRename:54 link table (:14-23) and citations
types.ts (49) ChangeRecord, record:35 structuredClone of before/after; undefined → null
apply.ts (134) applyChangeset:122, curatedIssues:103 baseline + references + changeset → document + records; B/C changes → to_confirm (:46-73) domain schema and validate
assets.ts (59) stripLegacyAnnotations:24, cleanedAsset:38, parseViewBox:49 removes every [data-anno-id] element, and the root style when it equals the legacy value exactly (:17, :31-33) xmldom parse and serialise
migration-map.ts (178) buildReportMigrationMap:127 baseline, final, legacyIdMap, records, sheet ref → map + stats
stats.ts (133) documentStats:77, statRows:113 document → counts and French rows
changelog.ts (132) renderChangelog:119, compactValue:29, recordSubject:38 records + stats → markdown
review-report.ts (206) renderReviewReport:201 10 fixed sections
labels.ts (29) KIND/LEVEL/PRIORITY_LABELS, LEVELS French labels
overlay.ts (214) overlayMarkers:49, renderReviewOverlay:185 cleaned SVG + before/after documents + view → review SVG xmldom, node:util
app-review.ts (26) renderAppReviewDrawing:20 cleaned SVG + document + view → composeViewSvg → text xmldom, render/compose
seed.ts (125) renderDraftSeedSql:114, DOCUMENT_DOLLAR_TAG:13, DRAFT_CHANGE_NOTE:19 sheetId, assets, documentJson → SQL
pipeline.ts (224) buildEquineDraft:112, renderDraftArtifacts:181, file-name constants (:41, :155-156) see §4
index.ts (53) re-exports

Facts about the curation pipeline: CHG-000 (the asset step: 3 set ops, pipeline.ts:68-104) is prepended, and an authored CHG-000 is refused (:106-110). The references file replaces the document registry before any change (apply.ts:128). curatedIssues runs twice (apply.ts:132, pipeline.ts:135). The real changeset has 45 changes, CHG-001 to CHG-045: 14 A, 22 B, 9 C; 11 carry a question; 34 set an explicit priority. It holds 687 ops: 587 set, 45 cite, 33 rename, 18 add, 4 remove, 0 move. It cites 48 references. move is exercised only by tests.

3.4 render/ (frozen TS renderer; R3 counterpart in crates/core/src/anatomy/{layer,compose}.rs)

Module Exports Role
layer.ts (261) renderAnnotationLayer:232, styleForView:75, viewBoxOf:258, MAIN/DETAIL_VIEW_STYLE:49,53, FALLBACK_COLOR:59 document + view (+ states) → LayerElement tree
dom.ts (38) createLayerElement:24, SVG_NS:9 tree → DOM via createElementNS/setAttribute
serialize.ts (25) serializeLayer:13 escapes & < > " only; called only by tests
compose.ts (196) composeViewSvg:54, highlightLayer:82, HALO_FILTER_ID:20 sets viewBox, removes width/height, appends the layer last; the halo <defs> is created as the first child
index.ts (33) re-exports

The pipeline's only consumer of render/ is curation/app-review.ts:3.

4. Generated artifacts

4.1 Producers

Text is written by import-equine.ts:41 (utf8).

File Bytes Producer Inputs Formatting
legacy-import/document.json 224,109 artifacts.ts:17 result.document JSON.stringify(v,null,2) → Prettier json
legacy-import/legacy-id-map.json 1,323 artifacts.ts:18 result.legacyIdMap same
legacy-import/assets.json 408 artifacts.ts:19 result.assets same
legacy-import/IMPORT-REPORT.md 22,402 artifacts.ts:20 → report.ts:310 ImportResult Prettier markdown
legacy-import/assets/Horse.svg, Horse_head.svg 145,770 / 139,079 import-equine.ts:63-74 legacy-sources copyFile (byte copy)
draft/document.json 302,794 pipeline.ts:185, :203 draft.document formatJson
draft/assets.json 203 pipeline.ts:204 draft.assets formatJson
draft/sheet-ref.json 217 pipeline.ts:205-211 ref, schema_version, species_id formatJson
draft/report-migration-map.json 85,627 pipeline.ts:187-194, :212 → migration-map.ts:127 baseline, final, legacyIdMap, records, ref, main formatJson
draft/CHANGELOG.md 1,114,533 pipeline.ts:195-200, :215 → changelog.ts:119 records, statsBefore/After, migration stats Prettier markdown
draft/REVIEW-REPORT.md 108,015 pipeline.ts:201, :216 → review-report.ts:201 changes, records, document, statsBefore, legacy anomalies Prettier markdown
draft/review/annotations-{main,head}.svg 141,278 / 137,275 pipeline.ts:141-153 → overlay.ts:185 cleanedSvg, baseline, draft, view xmldom XMLSerializer, raw
draft/review/app-{main,head}.svg 146,232 / 139,462 pipeline.ts:168-178 → app-review.ts:20 → compose.ts:54 cleanedSvg, draft, view xmldom XMLSerializer, raw
draft/equine_draft.sql 607,446 pipeline.ts:217-222 → seed.ts:114 sheetId, assets, documentJson, change note string template, raw, ends \n
draft/assets/horse.svg 132,997 import-equine.ts:110 ← assets.ts:24 Horse.svg, decoded as fatal UTF-8 xmldom XMLSerializer, raw

Authored inputs (never generated): legacy-sources/: Horse.svg 145,770, Horse_head.svg 139,079, pathologies.json 174,156, vertebrae.ts 303; curation/: changes.json 226,769, references.json 17,766.

4.2 JSON shapes

  • pathologies.json: {schema_version:"2.0", scope_disclaimer, species{3}, zones{26}}.
  • changes.json: {changes[45]}. Each change has id, level, kind, title, rationale, reference_ids, [question], [priority], ops.
  • references.json: {references[48]}; keys id, type, citation, url, doi.
  • document.json: {schema_version, species_id, name, description, scope_disclaimer, attribution, vertebral_config, references, categories[5], views[2], annotations, finding_zones}; legacy-import: 27 annotations, 26 finding zones; draft: 28 annotations, 27 finding zones.
  • legacy-id-map.json: {views{1}, annotations{27}, categories{5}, finding_nodes{0}, assets{2}}.
  • assets.json: [{file, sha256, byte_size, svg_asset_id}] (2 legacy, 1 draft).
  • sheet-ref.json: {sheet_id, version_id:null, document_sha256, schema_version:2, species_id}, snake_case.
  • report-migration-map.json: {schema_version:1, sheet{sheetId, versionId, documentSha256}, main_view_id, views{head:"head"}, annotations{27×{id, name{fr,en}}}, finding_paths{792, 34 null}}; sheet is camelCase.

4.3 What Prettier changes (measured in memory by the probe)

Markdown: only table cell padding and separator widths change: IMPORT-REPORT 134 lines, CHANGELOG 863, REVIEW-REPORT 52. No other line changes, and the line counts are identical. Column widths come from Prettier's string-width function (prettier 3.8.3 plugins/markdown.js): an all-ASCII string counts its length; otherwise, per code point, C0/C1 controls, U+0300–036F and U+FE00–FE0F count 0, East Asian Wide/Fullwidth characters and emoji count 2, everything else counts 1.

JSON: the data is identical after re-parsing; only layout changes: arrays of primitives collapse onto one line when they fit in 80 columns ("authors": ["Faunosteo"], [1655, 545]); objects stay expanded, because JSON.stringify put a newline after {; a trailing \n is added.

Numbers: Prettier prints JSON numbers through printNumber (lowercase, e+21 becomes e21, leading zeros of the exponent and trailing zeros stripped). There are 0 exponent-form numbers in the JSON today, 29 fractional values in draft/document.json.

4.4 xmldom 0.9.12 serialisation facts

  • The XML declaration and whitespace text nodes round-trip: horse.svg keeps 703 lines and starts with <?xml version="1.0" encoding="UTF-8"?>.
  • Attributes keep document order. Values are escaped on <>&"\t\n\r (&lt; &gt; &amp; &quot; &#9; &#10; &#13;). Text nodes are escaped on <&>.
  • A childless element is self-closed as /> with no space. Observed: <g id="osteo-overlays"> became <g id="osteo-overlays"/> once its children were stripped.
  • A namespace declaration is written only when not already in scope, so layer children carry no xmlns.
  • Nothing follows the root: the files end with </svg>. Nodes added for the layer and overlay are appended with no whitespace between them.
  • The inputs contain no NBSP, tab, CR or BOM, and no comment in horse.svg.

5. Identities and hashes

  • documentSha256: documentJson = await formatJson(draft.document) (pipeline.ts:185), then sha256Hex(documentJson) (pipeline.ts:159-165); sha256Hex hashes the string as UTF-8 (ids.ts:15-17); the same string is written as draft/document.json (pipeline.ts:203). Verified: 27c7383c…2660 matches both the committed file and the probe's recomputation.
  • Carried in sheet-ref.json document_sha256 (pipeline.ts:208) and report-migration-map.json sheet.documentSha256 (pipeline.ts:192 → migration-map.ts:162).
  • equine_draft.sql does not carry it. It embeds $equine_doc$ + documentJson.trimEnd() + $equine_doc$::jsonb (seed.ts:79) twice, in the insert (:82-95) and the converge statement (:101-112). It also embeds the cleaned asset sha256 (seed.ts:61).
  • The hash is pinned in 18 tracked files: draft/{sheet-ref,report-migration-map}.json; crates/core/tests/oracles/{editor,migration-map.draft,report-v3.demo}.json; crates/core/tests/oracles/r4/{compare/compare,text,tolerance}.json; apps/app/tests/fixtures/report-v3.demo.json; apps/app/tests/fixtures/goldens/r2/envelope.{demo,v2full,v2unresolved}.fr.nologos.json; apps/app/tests/fixtures/pdf/r3/store-path.report.json; apps/app/tests/fixtures/pdf/r4/read/scan.{crlf-unspaced-type-params,indirect-length,wrong-direct-length}.pdf; apps/app/tests/fixtures/r4/reports/{CAP,L}.json. (The fingerprint census counts 99 PDFs once the compressed attachments are inflated.)
  • UUIDs (ids.ts:19-31): first 16 bytes of sha256(UTF-8 name); byte 6 = (b & 0x0f) | 0x50; byte 8 = (b & 0x3f) | 0x80; lowercase 8-4-4-4-12. Names faunosteo:asset:<sha256 hex> (:33-35) and faunosteo:sheet:<species>:v<n> (:37-39). Verified: sheet 503dc301-a8b1-50d4-9e44-0919b2fc2916, horse.svg 7f767f74-3b36-51a7-8465-52dd7e2ead4a.
  • Other hashes: legacy asset sha = raw file bytes (importer.ts:67-75); cleaned asset sha = TextEncoder().encode(cleanedSvg) (pipeline.ts:118); source digests (pathologies.json, vertebrae.ts) = sha256 of the decoded then re-encoded text (importer.ts:77-80).

6. JavaScript-specific behaviours (a Rust port could reproduce these differently)

Object key insertion order drives every JSON artifact. The draft document is the working form and is never re-parsed. An edited key stays in place and a new key is appended (fields.ts:76-79). review_status is appended last by the B/C rule (apply.ts:57): the draft's annotation keys end …, vertebral_region_code, review_status. Added items keep the key order authored in changes.json (ops.ts:150). References follow the Zod schema order, with url/doi defaulting to null (packages/domain/src/anatomical-sheet/schema.ts:200-207). ChangeSummary follows Zod output order: priority sits at its schema position, and question is omitted when absent.

JSON.parse rules: integer-like keys iterate first (catalog.ts:240; catalog-checks.ts:14-16,42,72; migration-map.ts:137-138,150); today there are 0 integer-like zone keys and 0 integer-like legacy ids. A duplicate key keeps the last value.

Map/Set insertion order: svg.ts:97 first element per id, in document order; categories.ts:71-79 first seen, the name filled later without moving the entry; also catalog-checks.ts:41,71, overlay.ts:54,72, migration-map.ts:152.

Object identity: apply.ts:36-43,53 key a Map/Set by item object; ops.ts:38 (!== self) and ops.ts:159,176 (indexOf(item)) compare identity.

Sorting: catalog-checks.ts:78 count descending, then < on strings (UTF-16 code-unit order; the helper at :64-67 is misnamed byCodePoint); review-report.ts:153-164 priority rank, then id compared with <. The sort is stable; there is no localeCompare in src.

Number to string (ECMAScript rules): format.ts:22 and changelog.ts:33 (JSON.stringify); annotations.ts:61 and the report.ts tables; layer.ts:99-107,171-175,260; overlay.ts:82-84,91,105,113,131,139-143,168,193; seed.ts:62. Rust has crates/core/src/json.rs js_number:18, to_js_pretty:171, to_js_compact:200; serde_json is built with preserve_order and float_roundtrip. There is no equivalent of Prettier's layout.

Floating-point arithmetic: layer.ts:171 max(2, r − 12); overlay.ts:105 cy − r − 4; :109-113 centroid = sum ÷ n; :131 fontSize/8; :168 y + (i+1)·fontSize·1.3 left to right; :201 Math.round(width/90), where a −x.5 value rounds toward +∞, unlike Rust's f64::round.

Number() parsing: svg.ts:54-56 Number(null) and Number('') give 0, whitespace trimmed, hex and exponents accepted; svg.ts:37-47 and assets.ts:50-53 .trim().split(/[\s,]+/).map(Number) (a leading comma yields a 0 entry, an odd point count drops the last number); overlay.ts:197-199 splits without trim.

Regex classes: \s is Unicode whitespace, NBSP and U+FEFF included (svg.ts:40, assets.ts:52, overlay.ts:198, vertebrae.ts:17,20,27); \w and \d are ASCII-only, no u flag (vertebrae.ts:20; schema.ts:112 ^CHG-\d{3,}$); STABLE_ID_PATTERN is /^[a-z0-9][a-z0-9_-]{0,63}$/; the combining range is written as literal characters U+0300–U+036F (ids.ts:45, regions.ts:23).

Normalisation and case: normalize('NFD'), strip U+0300–036F, toLowerCase() (ids.ts:42-50, regions.ts:22-24), ICU 78.3 tables; slugify ends with .slice(0,64); no toUpperCase.

UTF-16 lengths: compactValue caps text at 120 units and cuts with slice(0,119) + '…' (changelog.ts:34-35), which can split a surrogate pair. Zod .min(1) also counts UTF-16 units.

Splitting and trimming: trim and trimEnd use the JS whitespace set (svg.ts:39, assets.ts:51, seed.ts:79); split(':', 2) discards the remainder (migration-map.ts:82), whereas Rust's splitn keeps it.

Decoding: TextDecoder fatal mode for the SVGs (importer.ts:83, pipeline.ts:114), which strips a leading BOM; Buffer.toString('utf8') is non-fatal (U+FFFD, BOM kept) for pathologies.json and vertebrae.ts (sources.ts:51-52); readFile(…,'utf8') reads the curation files (curation/sources.ts:23).

Deep equality and copies: isDeepStrictEqual ignores key order, NaN equals NaN, +0 differs from −0 (ops.ts:91, overlay.ts:63); structuredClone deep copies (types.ts:46-47, fields.ts:79, ops.ts:109,150, apply.ts:127-128).

Zod semantics: curation schemas are strict objects, discriminated by op; .int() accepts 2.0; defaults apply. Reference url = z.string().url() + /^https?:\/\//i (domain schema.ts:189-192); Rust has domain/sheet/schema.rs:100-107 with js::is_url.

Markdown escaping: cell() escapes | and LF only, not CR (markdown.ts:6-9). No clock, no randomness: no Date, no Math.random, no randomUUID in src.

7. Dependency on packages/domain

22 source files import it, 17 of them type-only.

Runtime symbol Used in Domain source
AnatomicalSheetDocumentSchema legacy/importer.ts:2, curation/apply.ts:2 anatomical-sheet/schema.ts:295
validateSheetDocument importer.ts:4, apply.ts:3 anatomical-sheet/validate.ts:465
SHEET_DOCUMENT_SCHEMA_VERSION (=2) importer.ts:3, legacy/report.ts:1 schema.ts:18
STABLE_ID_PATTERN legacy/ids.ts:2 schema.ts:21
ReferenceSchema curation/schema.ts:1 schema.ts:200

Type-only symbols (schema.ts unless noted): AnatomicalSheetDocumentInput (:315) in 13 files; Geometry (:322); SheetView (:321); SheetIssue (validate.ts:20); Reference (:210); ViewBox (:320); Laterality (:323); FindingCategoryKind (:325), FindingNodeInput (:227), LocalizedOptionalText (:213); AnnotationCategory (:319); ReportMigrationMap (report/migration-map.ts:33) and SheetRef (report/v3.ts:38).

Test runtime symbols: AnatomicalSheetDocumentSchema, validateSheetDocument, ReportMigrationMapSchema (report/migration-map.ts:15); curation.migration-leaves only: ReportV2Schema (report/v2.ts:59), findingPathKey (report/migration-map.ts:35), migrateReportV2ToV3 (report/migrate.ts:106), readReportDocument (report/migrate.ts:156).

Rust counterparts from R2: crates/core/src/domain/sheet/{schema,validate}.rs and domain/report/{migration_map,v2,v3,read}.rs.

8. Tests

Declarations counted by grep; it.each rows expanded by hand. (The orchestrator ran the suites: anatomy 131/131 in 16 files, domain 262/262.)

Suite (lines) Decl Cases What it asserts Files read Render dep
curation.apply (529) 29 41 each op and its records; error messages carry CHG-001 op 0; determinism (:425); purity (:429); B/C rule fixtures/mini-sheet.ts no
curation.assets (79) 5 5 30 annotated elements + titles removed, 270 paths kept, declaration kept, style removed, deterministic + XML re-parse, sha, parseViewBox legacy-sources/Horse.svg no
curation.migration-leaves (271) 8 8 612 leaves: 442 identical, 141 moved (134 + 7), 29 removed; 26 observable annotations; spine regions committed legacy-import/document.json, draft/document.json, draft/report-migration-map.json + domain migrate no
curation.migration-map (183) 5 5 schema-valid map, fates, every target exists; synthetic rename/move/remove/re-home runDraft, mini-sheet no
curation.overlay (83) 4 4 moved/removed markers, legend, detail framing mini-sheet no
curation.pipeline (110) 6 6 0 integrity error, 1 asset, head view_box 60 100 500 380, Cd 15–21, carpus, 811 nodes, CHANGELOG rows, 10 headings, SQL never publishes, CHG-000 refused runDraft + renderDraftArtifacts indirect
curation.schema (85) 5 9 committed curation files parse; rejections; duplicates curation/*.json no
document (23) 2 2 0 issue; determinism real sources no
importer.counts (103) 8 8 27/26, 2 views 1 trigger, 5 spine codes, 9 bilateral, 792/612/41 on both sides sources + regex over the SVGs no
importer.guards (47) 3 3 guard messages; dollar-quote tag inline SVG, real import no
importer.special-cases (128) 10 10 region, laterality, trigger, ssb, anamnesis, lean form, authored labels real import, pathologies.json no
legacy.regions (43) 4 4 inferRegionCode none no
r3.layer-oracles (162) 1 1 8 layer trees equal the frozen JSON crates/core/tests/oracles/sheet.draft.json and r3/layer.json direct
render.compose (230) 10 11 highlight, halo <defs>, framing; app-{main,head}.svg string-equal runDraft, draft/assets/horse.svg, draft/review/app-*.svg direct + xmldom
render.layer (158) 5 5 pair/zone/trigger, styles, states, DOM + serializeLayer runDraft, mini-sheet direct
seed.golden (87) 6 9 see below both generated folders indirect
Total 111 131

Golden test (seed.golden.test.ts): beforeAll re-runs the import and the draft in memory (:29-34); legacy-import: 4 files compared as readFile(…,'utf8') string === fresh render (:37-44); no SQL file in legacy-import (:46-50); the SVG copies compared with Buffer.equals against the sources, plus sha and size (:52-62); draft: one it loops over every file renderDraftArtifacts returns, comparing strings (:66-70); the draft folder must hold exactly the produced files plus assets/<file> (:72-78); horse.svg text === cleanedSvg, plus sha and size (:80-86). No comparison is done on parsed data.

Determinism tests: document.test.ts:16-22 (two imports, toEqual, plus renderArtifacts), curation.apply.test.ts:425, curation.assets.test.ts:46. No test rendered the draft folder twice before R5.1 (the golden pins it against the committed bytes); r5.pipeline-oracles.test.ts now does.

9. Consumers

@faunosteo/anatomy outside the package: package.json:28 (script filter) and packages/README.md:12 only. No import in apps/, packages/*, scripts/, crates/, docker/, the Dockerfile, the vite configs or the eslint configs. Rust cites it in comments only (crates/core/src/anatomy/{layer,compose}.rs, tests/anatomy_layer.rs).

@faunosteo/domain outside its package: imported by packages/anatomy only (package.json, 22 source files, 8 test files). apps/app/eslint.config.js:68-72 bans it in the app. apps/app/tests/unit/r4.census.test.ts :41-57 and :59-78 assert that apps/app and packages/core-wasm neither import nor depend on it; :80-90 asserts the lockfile lists @xmldom/xmldom under exactly ['packages/anatomy']. packages/core-wasm/tests/n-1 is a verbatim copy, not an import.

Path-level dependents: crates/core/tests/report_rules.rs:141-143 reads report-v2.full.json (5 times) and report-v2.minimal.json (4 times); archive_rules.rs:204,603,801,820,911 reads packages/domain/tests/fixtures; archive_support/mod.rs:81 documents horse-slice.ts as its source.

Consumers of the generated artifacts: the app (apps/app/vite.config.ts:13 + vite/sheet-bundle.ts:46-63 bundle document, sheet-ref, migration map, assets.json and the assets; apps/app/tests/helpers/legacyLeaves.ts:17 reads legacy-import/document.json); the core-wasm test suites (runtime, anatomy, measure, serialisation, pdf-import, pdf-import.budget, pdf-export, pdf-export.session); scripts/browser/lib/core-module.mjs:25; the crate tests (anatomy_canvas_op, anatomy_compose, sheet_index, sheet_rules, sheet_contract, editor_rules, fixtures_round_trip, the pdf_* suites, archive_support); the database (supabase/config.toml:44 lists equine_draft.sql in sql_paths; supabase/tests/007_equine_seed.sql plans 19 pgTAP checks; the PGlite harness packages/supabase/tests/db/harness.ts:21, seeds.test.ts); the crate oracles sheet.{draft,legacy-import}.json and migration-map.draft.json carry the seed path as source.

10. Upload tool

packages/supabase/scripts/upload-sheet-assets.ts (99 lines): reads <dir>/assets.json (:48-53); validates each entry (plain file name, sha /^[0-9a-f]{64}$/, id /^[0-9a-f-]{36}$/, :28-40); re-hashes each file and compares sha and size (:56-63); uploads <sha256>.svg to bucket anatomical-sheet-assets as image/svg+xml with upsert false, an "already exists" error tolerated (:77-84); calls RPC confirm_sheet_asset_upload(asset_id) (:86-89). Needs SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY (:42-46, :71-75), resolves the directory from INIT_CWD (:67-70), imports @supabase/supabase-js plus node:crypto, node:fs and node:path. It imports nothing from packages/anatomy; it depends only on the assets.json contract.

11. ANATOMICAL_SHEET_MODEL.md (docs/development)

§6 starts at :304; the folder table at :313-317; changeset fields, ops and target grammar :319-331; asset cleaning and CHG-000 :333-337; review drawings :339-344; Step 4c content (:346) says "44 changes + CHG-000, 48 references" while the file now holds 45 authored changes (CHG-045, colours, documented at :401-404); head view :368-375; status semantics :377-384; migration map (:393-399): 792 = 571 identical + 180 renamed or moved + 7 re-homed + 34 removed, matching CHANGELOG.md:35-43 and the committed map; seed SQL :406-410; import rules :412-429; validation tiers §2.1 at :108.

12. Risks (analyzer)

  • Any byte change in draft/document.json changes documentSha256: formatter, key order, number text or the trailing newline. That rewrites 18 pinned files and makes every older archive rebase once (certain for a Rust emitter under D-R5 as written).
  • Typed serde round-trips emit schema key order, not the working form's insertion order (e.g. review_status last), which produces a byte diff (high).
  • Prettier's JSON layout and its Markdown padding (string-width function) are not reproduced by serde_json or a plain padder (high if bytes must be preserved, none if the files are regenerated by decision).
  • Re-cleaning Horse.svg with the Rust reader (roxmltree plus its own serialiser, BDR-053) instead of xmldom changes the horse.svg bytes. That cascades into a new asset sha and svg_asset_id, a document change, new SQL, a new Storage object to upload, and changes to the anatomy_compose and pdf oracles that read horse.svg (medium to high).
  • Deleting packages/domain breaks the crate tests that read its fixtures (certain unless the fixtures move).
  • r4.census.test.ts:80-90 fails once xmldom leaves the lockfile (certain).
  • Edge-input differences (Unicode \s, Number(''), split limit, Math.round sign, UTF-16 slice) are not triggered by today's inputs (no NBSP, tab, CR, BOM, astral character or exponent found) (low).
  • NFD and lowercase table differences between ICU 78.3 and a Rust crate: slugify never fires on today's data (low).
  • Prettier Markdown escaping could alter more than padding on future content (today: padding only) (low to medium).

13. Open questions (analyzer)

  • Which fingerprint rule binds R5: D-R5 as written, or the BDR-045 amendment?
  • Byte-preserving port or one-time regeneration? Either the 18 files are reproduced byte for byte (Prettier JSON layout, Markdown padding, xmldom serialiser, insertion order), or they are regenerated once and checked by parsed-tree comparison.
  • horse.svg: keep the xmldom-cleaned bytes (asset 7f767f74…) as a frozen input, or re-derive them through the Rust reader (new sha, operator upload)?
  • Where do packages/domain/tests/fixtures/report-v2.*.json live after packages/domain is deleted?
  • Upload tool HTTP crate: the review (:300) names reqwest, the worker uses ureq. Which one?
  • Prettier on the seed: should supabase/seed/** join .prettierignore (today a root pnpm format rewrites the generated JSON and Markdown)?
  • Stale comment: vertebrae.ts:3 points to apps/app/src/domain/species/equine/vertebrae.ts; the source is legacy-sources/vertebrae.ts.