fix(anatomy): B/C changes leave every touched finding and annotation at to_confirm (applier rule, reviewed refused), typed test reads, docs numbers

This commit is contained in:
bchanot committed 2026-10-10 09:03:00 +02:00
1 parent 37550c29a5
commit 6034909674
10 files changed
+776 -327

No files matched your search

+61 -3
View File
@@ -6,8 +6,14 @@ import {
type SheetIssue,
} from '@faunosteo/domain'
import { applyOp, assertDeclared } from './ops'
import { changeSummary, type Change, type Changeset } from './schema'
import type { Item } from './targets'
import {
changeSummary,
needsConfirmation,
type Change,
type ChangeSummary,
type Changeset,
} from './schema'
import { allFindings, topCollection, type Item } from './targets'
import type { ChangeRecord, CurationResult } from './types'
/**
@@ -16,8 +22,56 @@ import type { ChangeRecord, CurationResult } from './types'
* registry first (it is the source of truth). Any op that cannot apply
* exactly as written, and any integrity error left at the end, throws:
* a curated document is never produced from a partially applied changeset.
*
* Review rule: a level B or C change never leaves what it touched
* (findings, finding categories, annotations: every item a set, add, cite,
* rename or move resolved to, whole added subtrees and subtree scopes
* included) as inherited or reviewed. After its ops, the applier sets
* `review_status = 'to_confirm'` on each one and records that edit under the
* same change id. An explicit 'reviewed' in such a change throws. Level A
* is untouched by the rule.
*/
/** Findings and annotations of the document, by item, with their target. */
function reviewable(doc: Item): Map<Item, string> {
const map = new Map<Item, string>()
for (const { item, target } of allFindings(doc)) map.set(item, target)
for (const item of topCollection(doc, 'annotation')) {
map.set(item, `annotation:${String(item.id)}`)
}
return map
}
/** Marks every touched item still in the document 'to_confirm'. */
function markToConfirm(
doc: Item,
change: ChangeSummary,
touched: readonly Item[],
records: ChangeRecord[],
) {
const targets = reviewable(doc)
for (const item of new Set(touched)) {
const target = targets.get(item)
if (target === undefined || item.review_status === 'to_confirm') continue
const before = item.review_status ?? 'inherited'
item.review_status = 'to_confirm'
const op = {
op: 'set',
target,
field: 'review_status',
value: 'to_confirm',
} as const
records.push({
change,
op,
target,
field: 'review_status',
before,
after: 'to_confirm',
})
}
}
function applyChange(doc: Item, change: Change, records: ChangeRecord[]) {
const summarised = changeSummary(change)
try {
@@ -25,13 +79,17 @@ function applyChange(doc: Item, change: Change, records: ChangeRecord[]) {
} catch (error) {
throw new Error(`${change.id}: ${(error as Error).message}`)
}
const touched: Item[] = []
change.ops.forEach((op, index) => {
try {
applyOp({ doc, change: summarised, op, records })
applyOp({ doc, change: summarised, op, records, touched })
} catch (error) {
throw new Error(`${change.id} op ${index}: ${(error as Error).message}`)
}
})
if (needsConfirmation(change.level)) {
markToConfirm(doc, summarised, touched, records)
}
}
function describe(issues: readonly { path: string; message: string }[]) {
+28 -3
View File
@@ -1,7 +1,7 @@
import { isDeepStrictEqual } from 'node:util'
import { fieldKind, isSettable, readField, writeField } from './fields'
import { propagateRename } from './rename'
import type { Op, Position } from './schema'
import { needsConfirmation, type Op, type Position } from './schema'
import {
childList,
childPrefix,
@@ -57,8 +57,20 @@ function unknownField(op: OpOf<'set'>): Error {
return new Error(`unknown field "${op.field}" on "${op.target}"`)
}
/** A B or C change leaves findings to the professional: no 'reviewed'. */
function assertNotReviewed(ctx: OpContext, op: OpOf<'set'>) {
if (op.field !== 'review_status' || op.value !== 'reviewed') return
if (needsConfirmation(ctx.change.level)) {
throw new Error(
`level ${ctx.change.level} cannot set ` +
`"${op.target}" review_status to "reviewed"`,
)
}
}
function setSelf(ctx: OpContext, located: Located, op: OpOf<'set'>) {
if (!isSettable(fieldKind(located.target), op.field)) throw unknownField(op)
ctx.touched.push(located.item)
const before = readField(located.item, op.field)
writeField(located.item, op.field, op.value)
record(ctx, op.target, op.field, { before, after: op.value })
@@ -73,6 +85,7 @@ function setSubtree(ctx: OpContext, located: Located, op: OpOf<'set'>) {
isSettable(fieldKind(located.target, entry.isCategory), op.field),
)
if (entries.length === 0) throw unknownField(op)
ctx.touched.push(...entries.map((entry) => entry.item))
for (const { target, item } of entries) {
const before = readField(item, op.field)
if (isDeepStrictEqual(before, op.value)) continue
@@ -82,6 +95,7 @@ function setSubtree(ctx: OpContext, located: Located, op: OpOf<'set'>) {
}
function applySet(ctx: OpContext, op: OpOf<'set'>): void {
assertNotReviewed(ctx, op)
const located = locate(ctx.doc, op.target)
if ((op.scope ?? 'self') === 'self') setSelf(ctx, located, op)
else setSubtree(ctx, located, op)
@@ -95,6 +109,7 @@ function applyRename(ctx: OpContext, op: OpOf<'rename'>): void {
const before = structuredClone(item)
const from = String(item[key])
item[key] = op.id
ctx.touched.push(item)
record(ctx, op.target, null, { before, after: item })
propagateRename(ctx, { kind: target.kind, from, to: op.id })
}
@@ -118,6 +133,11 @@ function addDestination(ctx: OpContext, op: OpOf<'add'>): Destination {
return { list, key: keyField(kind), prefix: `${kind}:` }
}
function descendants(item: Item): Item[] {
const children = Array.isArray(item.children) ? (item.children as Item[]) : []
return children.flatMap((child) => [child, ...descendants(child)])
}
function applyAdd(ctx: OpContext, op: OpOf<'add'>): void {
if (!isItem(op.value)) throw new Error('add needs an object value')
const dest = addDestination(ctx, op)
@@ -127,7 +147,9 @@ function applyAdd(ctx: OpContext, op: OpOf<'add'>): void {
}
assertFree(dest.list, dest.key, id)
const index = insertionIndex(dest.list, dest.key, op.position)
dest.list.splice(index, 0, structuredClone(op.value))
const added = structuredClone(op.value)
dest.list.splice(index, 0, added)
ctx.touched.push(added, ...descendants(added))
record(ctx, dest.prefix + id, null, { before: null, after: op.value })
}
@@ -153,6 +175,7 @@ function applyMove(ctx: OpContext, op: OpOf<'move'>): void {
assertFree(list, 'id', id, source.item)
source.siblings!.splice(source.siblings!.indexOf(source.item), 1)
list.splice(insertionIndex(list, 'id', op.position), 0, source.item)
ctx.touched.push(source.item)
const after = childPrefix(parent) + id
record(ctx, op.target, null, { before: source.item, after })
}
@@ -170,7 +193,9 @@ export function assertDeclared(doc: Item, ids: readonly string[]): void {
function applyCite(ctx: OpContext, op: OpOf<'cite'>): void {
assertDeclared(ctx.doc, op.reference_ids)
const located = locate(ctx.doc, op.target)
for (const { target, item } of findingScope(located, op.scope ?? 'self')) {
const scope = findingScope(located, op.scope ?? 'self')
ctx.touched.push(...scope.map((entry) => entry.item))
for (const { target, item } of scope) {
const before = Array.isArray(item.reference_ids) ? item.reference_ids : []
const added = [...new Set(op.reference_ids)].filter(
(id) => !before.includes(id),
+2
View File
@@ -27,6 +27,8 @@ export interface OpContext {
change: ChangeSummary
op: Op
records: ChangeRecord[]
/** Items the change edited, in order; the applier marks them at the end. */
touched: Item[]
}
/** Absent values are recorded as null so records stay plain JSON. */
+124 -24
View File
@@ -1,22 +1,34 @@
import { applyChangeset, type CurationResult, type Op } from '../src'
import { changesetOf, MINI_REFERENCES, miniSheet } from './fixtures/mini-sheet'
/* eslint-disable @typescript-eslint/no-explicit-any -- tests read the plain JSON form */
type Plain = Record<string, unknown>
function plain(value: unknown): Plain {
return value as Plain
}
function nodes(item: Plain): Plain[] {
return (item.children ?? []) as Plain[]
}
function run(ops: Op[]): CurationResult {
return applyChangeset(miniSheet(), MINI_REFERENCES, changesetOf(ops))
}
function zone(result: CurationResult, id: string): any {
return result.document.finding_zones.find((z) => z.id === id)
function zone(result: CurationResult, id: string): Plain {
return plain(result.document.finding_zones.find((z) => z.id === id))
}
function hipDysfunctions(result: CurationResult): any {
return zone(result, 'hip').categories[0]
function hipDysfunctions(result: CurationResult): Plain {
return (zone(result, 'hip').categories as Plain[])[0]!
}
function childIds(node: any): string[] {
return (node.children ?? []).map((child: any) => child.id)
function annotation(result: CurationResult, id: string): Plain {
return plain(result.document.annotations.find((a) => a.id === id))
}
function childIds(node: Plain): string[] {
return nodes(node).map((child) => child.id as string)
}
const MOBILITY = 'finding:hip/hip-dysfunctions/mobility'
@@ -53,7 +65,7 @@ describe('applyChangeset: set', () => {
value: 'Mobility',
},
])
expect(hipDysfunctions(result).children[0].description).toEqual({
expect(nodes(hipDysfunctions(result))[0]!.description).toEqual({
en: 'Mobility',
})
})
@@ -75,7 +87,7 @@ describe('applyChangeset: set', () => {
`${MOBILITY}/extension`,
'finding:hip/hip-dysfunctions/pain',
])
expect(hipDysfunctions(result).children[0].children[1].review_status).toBe(
expect(nodes(nodes(hipDysfunctions(result))[0]!)[1]!.review_status).toBe(
'to_confirm',
)
})
@@ -100,34 +112,32 @@ describe('applyChangeset: rename', () => {
it('renames a zone and the annotations follow, one record each', () => {
const result = run([{ op: 'rename', target: 'zone:hip', id: 'hip-joint' }])
expect(zone(result, 'hip-joint')).toBeDefined()
const hip = result.document.annotations.find((a) => a.id === 'hip') as any
const hip = annotation(result, 'hip')
expect(hip.finding_zone_id).toBe('hip-joint')
expect(result.records.map((r) => [r.target, r.field])).toEqual([
['zone:hip', null],
['annotation:hip', 'finding_zone_id'],
])
expect((result.records[0]!.before as any).id).toBe('hip')
expect(plain(result.records[0]!.before).id).toBe('hip')
})
it('renames a region code and the vertebral annotations follow', () => {
const result = run([{ op: 'rename', target: 'region:C', id: 'Cv' }])
expect(result.document.vertebral_config.regions[0]!.code).toBe('Cv')
const neck = result.document.annotations.find((a) => a.id === 'neck') as any
const neck = annotation(result, 'neck')
expect(neck.vertebral_region_code).toBe('Cv')
})
it('renames a view: parent links and trigger targets follow', () => {
const result = run([{ op: 'rename', target: 'view:head', id: 'skull' }])
const trigger = result.document.annotations.find(
(a) => a.id === 'head-trigger',
) as any
const trigger = annotation(result, 'head-trigger')
expect(trigger.opens_view_id).toBe('skull')
expect(result.records.map((r) => r.field)).toEqual([null, 'opens_view_id'])
})
it('renames a main view: parent_view_id and view_id follow', () => {
const result = run([{ op: 'rename', target: 'view:main', id: 'overview' }])
expect((result.document.views[1] as any).parent_view_id).toBe('overview')
expect(plain(result.document.views[1]).parent_view_id).toBe('overview')
expect(
result.document.annotations.every((a) => a.view_id === 'overview'),
).toBe(true)
@@ -146,7 +156,7 @@ describe('applyChangeset: rename', () => {
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] },
{ op: 'rename', target: 'reference:atlas', id: 'atlas-2' },
])
expect(hipDysfunctions(result).children[0].reference_ids).toEqual([
expect(nodes(hipDysfunctions(result))[0]!.reference_ids).toEqual([
'atlas-2',
])
expect(result.records.at(-1)).toMatchObject({
@@ -170,7 +180,7 @@ describe('applyChangeset: add, remove, move', () => {
const op: Op = { op: 'add', target: MOBILITY, value: node('new') }
if (position !== undefined) op.position = position
const result = run([op])
expect(childIds(hipDysfunctions(result).children[0])).toEqual(expected)
expect(childIds(nodes(hipDysfunctions(result))[0]!)).toEqual(expected)
expect(result.records[0]).toMatchObject({
target: `${MOBILITY}/new`,
before: null,
@@ -181,7 +191,7 @@ describe('applyChangeset: add, remove, move', () => {
const result = run([
{ op: 'add', target: `${MOBILITY}/flexion`, value: node('left') },
])
expect(childIds(hipDysfunctions(result).children[0].children[0])).toEqual([
expect(childIds(nodes(nodes(hipDysfunctions(result))[0]!)[0]!)).toEqual([
'left',
])
})
@@ -243,7 +253,7 @@ describe('applyChangeset: add, remove, move', () => {
const result = run([{ op: 'remove', target: MOBILITY }])
expect(childIds(hipDysfunctions(result))).toEqual(['pain'])
expect(result.records[0]).toMatchObject({ target: MOBILITY, after: null })
expect(childIds(result.records[0]!.before)).toEqual([
expect(childIds(plain(result.records[0]!.before))).toEqual([
'flexion',
'extension',
])
@@ -263,12 +273,12 @@ describe('applyChangeset: add, remove, move', () => {
to: 'finding:hip/anamnesis',
},
])
expect(childIds(hipDysfunctions(result).children[0])).toEqual([
expect(childIds(nodes(hipDysfunctions(result))[0]!)).toEqual([
'pain',
'flexion',
'extension',
])
expect(childIds(zone(result, 'hip').categories[1])).toEqual([
expect(childIds((zone(result, 'hip').categories as Plain[])[1]!)).toEqual([
'trauma',
'stiffness',
])
@@ -285,12 +295,12 @@ describe('applyChangeset: cite', () => {
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] },
{ op: 'cite', target: MOBILITY, reference_ids: ['atlas', 'paper'] },
])
expect(hipDysfunctions(result).children[0].reference_ids).toEqual([
expect(nodes(hipDysfunctions(result))[0]!.reference_ids).toEqual([
'atlas',
'paper',
])
expect(
hipDysfunctions(result).children[0].children[0].reference_ids,
nodes(nodes(hipDysfunctions(result))[0]!)[0]!.reference_ids,
).toBeUndefined()
expect(result.records).toHaveLength(2)
})
@@ -427,3 +437,93 @@ describe('applyChangeset: purity', () => {
expect(result.document.references).not.toBe(references)
})
})
describe('applyChangeset: review rule of levels B and C', () => {
const B = { level: 'B' } as const
const withLevel = (ops: Op[], extra = B) =>
applyChangeset(miniSheet(), MINI_REFERENCES, changesetOf(ops, extra))
const status = (item: Plain) => item.review_status
it('marks a node set by a B change to_confirm, with a record', () => {
const result = withLevel([
{
op: 'set',
target: MOBILITY,
field: 'name',
value: { fr: 'a', en: 'a' },
},
])
const node = nodes(hipDysfunctions(result))[0]!
expect(status(node)).toBe('to_confirm')
const last = result.records[result.records.length - 1]!
expect(last).toMatchObject({
target: MOBILITY,
field: 'review_status',
before: 'inherited',
after: 'to_confirm',
})
expect(last.change.id).toBe('CHG-001')
})
it('marks every node of an added subtree', () => {
const value = {
id: 'new',
name: { fr: 'n', en: 'n' },
children: [{ id: 'leaf', name: { fr: 'l', en: 'l' } }],
}
const result = withLevel([
{ op: 'add', target: 'finding:hip/hip-dysfunctions', value },
])
const added = nodes(hipDysfunctions(result)).find((n) => n.id === 'new')!
expect(status(added)).toBe('to_confirm')
expect(status(nodes(added)[0]!)).toBe('to_confirm')
})
it('marks cited targets under a C change', () => {
const result = withLevel(
[{ op: 'cite', target: MOBILITY, reference_ids: ['atlas'] }],
{ level: 'C', question: 'Q?' } as never,
)
expect(status(nodes(hipDysfunctions(result))[0]!)).toBe('to_confirm')
})
it('marks an annotation set by a B change', () => {
const result = withLevel([
{
op: 'set',
target: 'annotation:hip',
field: 'name',
value: { fr: 'h', en: 'h' },
},
])
expect(status(annotation(result, 'hip'))).toBe('to_confirm')
})
it('leaves a level A change untouched', () => {
const result = run([
{
op: 'set',
target: MOBILITY,
field: 'name',
value: { fr: 'a', en: 'a' },
},
])
expect(status(nodes(hipDysfunctions(result))[0]!)).not.toBe('to_confirm')
expect(result.records).toHaveLength(1)
})
it('throws when a B change sets review_status to reviewed', () => {
expect(() =>
withLevel([
{
op: 'set',
target: MOBILITY,
field: 'review_status',
value: 'reviewed',
},
]),
).toThrow(
/CHG-001 op 0: level B cannot set "finding:hip\/hip-dysfunctions\/mobility"/,
)
})
})