asma-core-helpers 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asma-core-helpers",
3
- "version": "0.40.0",
3
+ "version": "0.41.0",
4
4
  "description": "Core helper utilities for ASMA applications",
5
5
  "files": [
6
6
  "lib/**/*",
@@ -11,6 +11,8 @@ import type {
11
11
  MappingBinding,
12
12
  MappingFilter,
13
13
  MappingNode,
14
+ HighlightRule,
15
+ RuleCondition,
14
16
  QnrAlternative,
15
17
  QnrDataMapping,
16
18
  QnrAction,
@@ -1079,6 +1081,7 @@ const OPTIONAL_COLLECTIONS = [
1079
1081
  'prefillRulesById',
1080
1082
  'prefillRuleOrderByQuestionId',
1081
1083
  'highlightRuleSettingsByQuestionId',
1084
+ 'narrativeRuleSettingsByQuestionId',
1082
1085
  'dataMappingsById',
1083
1086
  'mappingNodesById',
1084
1087
  'mappingBindingsById',
@@ -1432,6 +1435,8 @@ const deleteQuestion = (doc: QnrTemplateDocument, questionId: QuestionId): QnrTe
1432
1435
  // unreachable state that still changes `document_hash`.
1433
1436
  highlightRuleSettingsByQuestionId:
1434
1437
  doc.highlightRuleSettingsByQuestionId && omitKey(doc.highlightRuleSettingsByQuestionId, questionId),
1438
+ narrativeRuleSettingsByQuestionId:
1439
+ doc.narrativeRuleSettingsByQuestionId && omitKey(doc.narrativeRuleSettingsByQuestionId, questionId),
1435
1440
  })
1436
1441
  // A binding pointing at a deleted question is an unresolvable reference the
1437
1442
  // compiler would reject at publication; drop it with its target. A grid column
@@ -1503,6 +1508,108 @@ const scrubColumnPresentationRefs = (doc: QnrTemplateDocument, questionId: Quest
1503
1508
  return changed ? { ...doc, questionsById: nextQuestions } : doc
1504
1509
  }
1505
1510
 
1511
+ /** New operations are checked on direct replay as well as at the wire boundary. */
1512
+ const assertRuleEditShape = (op: TemplateOp, keys: readonly string[]): void => {
1513
+ if (Object.keys(op).some((key) => !keys.includes(key))) {
1514
+ throw new OperationConflictError(`Operation ${op.type} carries an undeclared member`)
1515
+ }
1516
+ }
1517
+
1518
+ const requireRuleQuestion = (doc: QnrTemplateDocument, questionId: unknown): void => {
1519
+ if (typeof questionId !== 'string' || questionId === '' || !Object.hasOwn(doc.questionsById ?? {}, questionId)) {
1520
+ throw new OperationConflictError(`Unknown question "${questionId}"`)
1521
+ }
1522
+ }
1523
+
1524
+ /** Fieldwise true-only settings. Neither a rule nor the other setting is touched. */
1525
+ const setRuleSetting = (
1526
+ doc: QnrTemplateDocument,
1527
+ op: Extract<TemplateOp, { type: 'highlightRuleSettings.set' | 'narrativeRuleSettings.set' }>,
1528
+ root: 'highlightRuleSettingsByQuestionId' | 'narrativeRuleSettingsByQuestionId',
1529
+ ): QnrTemplateDocument => {
1530
+ assertRuleEditShape(op, ['type', 'questionId', 'field', 'value'])
1531
+ requireRuleQuestion(doc, op.questionId)
1532
+ if ((op.field !== 'enabled' && op.field !== 'requiredAll') || typeof op.value !== 'boolean') {
1533
+ throw new OperationConflictError(`Operation ${op.type} requires a known field and boolean value`)
1534
+ }
1535
+ const settings = { ...(doc[root]?.[op.questionId] ?? {}) }
1536
+ if (op.value) settings[op.field] = true
1537
+ else delete settings[op.field]
1538
+ const byQuestion = omitKey(doc[root] ?? {}, op.questionId)
1539
+ return {
1540
+ ...doc,
1541
+ [root]: Object.keys(settings).length === 0 ? byQuestion : { ...byQuestion, [op.questionId]: settings },
1542
+ }
1543
+ }
1544
+
1545
+ /** A new condition edit must resolve its source and every alternative to that source's ownership. */
1546
+ const requireRuleCondition = (doc: QnrTemplateDocument, value: unknown): void => {
1547
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
1548
+ throw new OperationConflictError('A highlight condition must be an object')
1549
+ }
1550
+ const condition = value as RuleCondition
1551
+ requireRuleQuestion(doc, condition.sourceQuestionId)
1552
+ if ((condition.operator !== undefined && typeof condition.operator !== 'string') ||
1553
+ (condition.value !== undefined && (!isDocScalarValue(condition.value) ||
1554
+ (typeof condition.value === 'number' && !Number.isFinite(condition.value)))) ||
1555
+ (condition.alternativeId !== undefined && typeof condition.alternativeId !== 'string') ||
1556
+ (condition.alternativeIds !== undefined && (!Array.isArray(condition.alternativeIds) ||
1557
+ condition.alternativeIds.some((id) => typeof id !== 'string')))) {
1558
+ throw new OperationConflictError('A highlight condition carries a malformed member')
1559
+ }
1560
+ const alternatives = [
1561
+ ...(condition.alternativeId === undefined ? [] : [condition.alternativeId]),
1562
+ ...(condition.alternativeIds ?? []),
1563
+ ]
1564
+ for (const id of alternatives) {
1565
+ if (!Object.hasOwn(doc.alternativesById ?? {}, id) ||
1566
+ !doc.alternativeOrderByQuestionId?.[condition.sourceQuestionId]?.includes(id)) {
1567
+ throw new OperationConflictError(`Alternative "${id}" is not owned by question "${condition.sourceQuestionId}"`)
1568
+ }
1569
+ }
1570
+ }
1571
+
1572
+ /** A field edit requires the existing owner; unlike the released setter it never moves/replaces. */
1573
+ const setHighlightField = (
1574
+ doc: QnrTemplateDocument,
1575
+ op: Extract<TemplateOp, { type: 'highlightRule.setField' }>,
1576
+ ): QnrTemplateDocument => {
1577
+ assertRuleEditShape(op, ['type', 'ruleId', 'questionId', 'field', 'value'])
1578
+ requireRuleQuestion(doc, op.questionId)
1579
+ const owners = Object.entries(doc.highlightRuleOrderByQuestionId ?? {})
1580
+ .filter(([, ids]) => ids.includes(op.ruleId)).map(([id]) => id)
1581
+ const existing = doc.highlightRulesById?.[op.ruleId]
1582
+ if (typeof op.ruleId !== 'string' || op.ruleId === '' || !existing ||
1583
+ !Object.hasOwn(doc.highlightRulesById ?? {}, op.ruleId) || owners.length !== 1 || owners[0] !== op.questionId) {
1584
+ throw new OperationConflictError(`Highlight rule "${op.ruleId}" is not owned by question "${op.questionId}"`)
1585
+ }
1586
+ const rule: HighlightRule = { ...existing }
1587
+ switch (op.field) {
1588
+ case 'condition':
1589
+ requireRuleCondition(doc, op.value)
1590
+ rule.condition = op.value
1591
+ break
1592
+ case 'state':
1593
+ if (op.value !== null && (typeof op.value !== 'number' || !Number.isFinite(op.value))) {
1594
+ throw new OperationConflictError('Highlight state must be a finite number or null')
1595
+ }
1596
+ if (op.value === null) delete rule.state
1597
+ else rule.state = op.value
1598
+ break
1599
+ case 'highlight':
1600
+ case 'showLink':
1601
+ if (op.value !== null && typeof op.value !== 'boolean') {
1602
+ throw new OperationConflictError('Highlight output must be a boolean or null')
1603
+ }
1604
+ if (op.value === null) delete rule[op.field]
1605
+ else rule[op.field] = op.value
1606
+ break
1607
+ default:
1608
+ throw new OperationConflictError('Unknown highlight field')
1609
+ }
1610
+ return { ...doc, highlightRulesById: { ...doc.highlightRulesById, [op.ruleId]: rule } }
1611
+ }
1612
+
1506
1613
  export const applyOperation = (document: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument => {
1507
1614
  const next = reduce(document, op)
1508
1615
  return prune({ ...next, revision: document.revision + 1 })
@@ -2749,6 +2856,15 @@ const reduce = (doc: QnrTemplateDocument, op: TemplateOp): QnrTemplateDocument =
2749
2856
  })
2750
2857
  }
2751
2858
 
2859
+ case 'highlightRule.setField':
2860
+ return setHighlightField(doc, op)
2861
+
2862
+ case 'highlightRuleSettings.set':
2863
+ return setRuleSetting(doc, op, 'highlightRuleSettingsByQuestionId')
2864
+
2865
+ case 'narrativeRuleSettings.set':
2866
+ return setRuleSetting(doc, op, 'narrativeRuleSettingsByQuestionId')
2867
+
2752
2868
  case 'narrativeRule.set': {
2753
2869
  if (!doc.questionsById?.[op.questionId]) {
2754
2870
  throw new OperationConflictError(`Unknown question "${op.questionId}"`)
@@ -22,6 +22,7 @@ import type {
22
22
  QnrRuleId,
23
23
  RowId,
24
24
  RuleCondition,
25
+ RuleSettingField,
25
26
  TabId,
26
27
  VisibilityRuleId,
27
28
  } from './templateDocument.js'
@@ -66,6 +67,12 @@ export type OpValue = DocScalar | DocScalar[] | null
66
67
  */
67
68
  type MetaFieldUnset<W> = W extends { field: infer F; value: infer V } ? { field: F; value: V | null } : never
68
69
 
70
+ /** A single highlight member edit; null clears an output, never the condition. */
71
+ export type HighlightRuleFieldWrite =
72
+ | { field: 'condition'; value: RuleCondition }
73
+ | { field: 'state'; value: number | null }
74
+ | { field: 'highlight' | 'showLink'; value: boolean | null }
75
+
69
76
  export type TemplateOp =
70
77
  | { type: 'template.updateMeta'; patch: Record<string, OpValue | Record<string, unknown>> }
71
78
  | {
@@ -441,6 +448,10 @@ export type TemplateOp =
441
448
  | { type: 'visibilityRule.delete'; ruleId: VisibilityRuleId }
442
449
  | { type: 'highlightRule.set'; ruleId: HighlightRuleId; questionId: QuestionId; condition: RuleCondition }
443
450
  | { type: 'highlightRule.delete'; ruleId: HighlightRuleId }
451
+ /** Edits an existing, owned rule without replacing its other authored outputs. */
452
+ | ({ type: 'highlightRule.setField'; ruleId: HighlightRuleId; questionId: QuestionId } & HighlightRuleFieldWrite)
453
+ | { type: 'highlightRuleSettings.set'; questionId: QuestionId; field: RuleSettingField; value: boolean }
454
+ | { type: 'narrativeRuleSettings.set'; questionId: QuestionId; field: RuleSettingField; value: boolean }
444
455
  | { type: 'narrativeRule.set'; ruleId: NarrativeRuleId; questionId: QuestionId; condition: RuleCondition }
445
456
  | { type: 'narrativeRule.delete'; ruleId: NarrativeRuleId }
446
457
  | {
@@ -519,6 +530,9 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
519
530
  'visibilityRule.delete': true,
520
531
  'highlightRule.set': true,
521
532
  'highlightRule.delete': true,
533
+ 'highlightRule.setField': true,
534
+ 'highlightRuleSettings.set': true,
535
+ 'narrativeRuleSettings.set': true,
522
536
  'narrativeRule.set': true,
523
537
  'narrativeRule.delete': true,
524
538
  'qnrRule.set': true,
@@ -0,0 +1,285 @@
1
+ import assert from 'node:assert/strict'
2
+ import { describe, it } from 'node:test'
3
+ import { type } from 'arktype'
4
+ import { applyOperation, OperationConflictError } from './applyOperation.js'
5
+ import { canonicalJson, hashCanonical, reduceToMinimalForm } from './canonicalize.js'
6
+ import type { TemplateOp } from './operations.js'
7
+ import {
8
+ qnrTemplateDocumentSchema, templateOpSchema, templateRuleAuthoringIsDefault,
9
+ templateAuthoringIsDefault, templateDocumentIsDefault, templateDocumentIsDefaultV0281,
10
+ } from './schemas.js'
11
+ import { emptyTemplateDocument, type QnrTemplateDocument, type RuleSettingField } from './templateDocument.js'
12
+
13
+ const scaffold = (): QnrTemplateDocument => {
14
+ const doc = [
15
+ { type: 'question.create', questionId: 'target', questionType: 'TextShort' },
16
+ { type: 'question.create', questionId: 'source', questionType: 'Dropdown' },
17
+ { type: 'question.create', questionId: 'grid', questionType: 'QuestionGrid' },
18
+ { type: 'gridColumn.create', questionId: 'grid', columnQuestionId: 'column', questionType: 'TextShort' },
19
+ { type: 'alternative.create', questionId: 'source', alternativeId: 'a', label: 'A' },
20
+ { type: 'alternative.create', questionId: 'column', alternativeId: 'other-a', label: 'Other' },
21
+ ].reduce((doc, op) => applyOperation(doc, op as TemplateOp), emptyTemplateDocument('7684'))
22
+ return {
23
+ ...doc,
24
+ highlightRulesById: {
25
+ h: { condition: { sourceQuestionId: 'source', alternativeIds: ['a'] }, state: 2, highlight: true, showLink: true, importedText: 'preserved' },
26
+ hc: { condition: { sourceQuestionId: 'source' }, state: 1 },
27
+ },
28
+ highlightRuleOrderByQuestionId: { target: ['h'], column: ['hc'] },
29
+ narrativeRulesById: { n: { condition: { sourceQuestionId: 'source' } } },
30
+ narrativeRuleOrderByQuestionId: { target: ['n'] },
31
+ prefillRulesById: { p: { sourceQuestionId: 'source' } },
32
+ prefillRuleOrderByQuestionId: { target: ['p'] },
33
+ }
34
+ }
35
+
36
+ const settingsTypes = ['highlightRuleSettings.set', 'narrativeRuleSettings.set'] as const
37
+ const rootOf = (opType: typeof settingsTypes[number]) =>
38
+ opType === 'highlightRuleSettings.set' ? 'highlightRuleSettingsByQuestionId' : 'narrativeRuleSettingsByQuestionId'
39
+ const apply = (doc: QnrTemplateDocument, ops: TemplateOp[]) => ops.reduce(applyOperation, doc)
40
+ const unsafe = (doc: QnrTemplateDocument, op: unknown) => applyOperation(doc, op as TemplateOp)
41
+ const refused = (doc: QnrTemplateDocument, op: unknown) => {
42
+ const before = structuredClone(doc)
43
+ assert.throws(() => unsafe(doc, op), OperationConflictError)
44
+ assert.deepEqual(doc, before, 'rejection cannot mutate any input or partially apply an edit')
45
+ }
46
+
47
+ describe('7684-F02/F06 independent rule settings', () => {
48
+ for (const opType of settingsTypes) {
49
+ const root = rootOf(opType)
50
+ for (const enabled of [false, true]) for (const requiredAll of [false, true]) {
51
+ it(`${opType} stores the exact ${enabled}/${requiredAll} combination`, () => {
52
+ const initial = scaffold()
53
+ const result = apply(initial, [
54
+ { type: opType, questionId: 'target', field: 'enabled', value: enabled },
55
+ { type: opType, questionId: 'target', field: 'requiredAll', value: requiredAll },
56
+ ])
57
+ const expected = { ...(enabled ? { enabled: true } : {}), ...(requiredAll ? { requiredAll: true } : {}) }
58
+ if (enabled || requiredAll) assert.deepEqual(result[root], { target: expected })
59
+ else assert.equal(Object.hasOwn(result, root), false)
60
+ assert.deepEqual(result.narrativeRulesById, initial.narrativeRulesById)
61
+ assert.deepEqual(result.highlightRulesById, initial.highlightRulesById)
62
+ assert.deepEqual(result.narrativeRuleOrderByQuestionId, initial.narrativeRuleOrderByQuestionId)
63
+ assert.equal(result[rootOf(opType === settingsTypes[0] ? settingsTypes[1] : settingsTypes[0])], undefined)
64
+ })
65
+ }
66
+ it(`${opType} clears only the selected field; concurrent edits commute`, () => {
67
+ const base = apply(scaffold(), [
68
+ { type: opType, questionId: 'target', field: 'enabled', value: true },
69
+ { type: opType, questionId: 'target', field: 'requiredAll', value: true },
70
+ ])
71
+ const clearEnabled: TemplateOp = { type: opType, questionId: 'target', field: 'enabled', value: false }
72
+ const clearAll: TemplateOp = { type: opType, questionId: 'target', field: 'requiredAll', value: false }
73
+ assert.deepEqual(applyOperation(base, clearEnabled)[root], { target: { requiredAll: true } })
74
+ assert.deepEqual(applyOperation(base, clearAll)[root], { target: { enabled: true } })
75
+ assert.deepEqual(apply(base, [clearEnabled, clearAll]), apply(base, [clearAll, clearEnabled]))
76
+ assert.deepEqual(apply(base, [clearEnabled, { ...clearEnabled, value: true }])[root], base[root])
77
+ })
78
+ for (const field of ['enabled', 'requiredAll'] as RuleSettingField[]) {
79
+ it(`${opType} repeats ${field} idempotently in content`, () => {
80
+ const op: TemplateOp = { type: opType, questionId: 'column', field, value: true }
81
+ const once = applyOperation(scaffold(), op)
82
+ assert.deepEqual(applyOperation(once, op), { ...once, revision: once.revision + 1 })
83
+ })
84
+ }
85
+ }
86
+ it('keeps narrative and highlight flags independent and settings after final rule deletion', () => {
87
+ const doc = apply(scaffold(), [
88
+ { type: 'narrativeRuleSettings.set', questionId: 'target', field: 'requiredAll', value: true },
89
+ { type: 'highlightRuleSettings.set', questionId: 'target', field: 'enabled', value: true },
90
+ { type: 'narrativeRule.delete', ruleId: 'n' },
91
+ { type: 'highlightRule.delete', ruleId: 'h' },
92
+ ])
93
+ assert.deepEqual(doc.narrativeRuleSettingsByQuestionId, { target: { requiredAll: true } })
94
+ assert.deepEqual(doc.highlightRuleSettingsByQuestionId, { target: { enabled: true } })
95
+ assert.equal(doc.narrativeRulesById, undefined)
96
+ assert.equal(doc.narrativeRuleOrderByQuestionId, undefined)
97
+ })
98
+ })
99
+
100
+ describe('7684-F06 lossless highlight member edits', () => {
101
+ it('edits condition then severity without erasing imported outputs or order', () => {
102
+ const initial = scaffold()
103
+ const condition = { sourceQuestionId: 'column', alternativeId: 'other-a', operator: 'Is' }
104
+ const result = apply(initial, [
105
+ { type: 'highlightRule.setField', ruleId: 'h', questionId: 'target', field: 'condition', value: condition },
106
+ { type: 'highlightRule.setField', ruleId: 'h', questionId: 'target', field: 'state', value: 3 },
107
+ ])
108
+ assert.deepEqual(result.highlightRulesById?.h, { ...initial.highlightRulesById!.h, condition, state: 3 })
109
+ assert.deepEqual(result.highlightRuleOrderByQuestionId, initial.highlightRuleOrderByQuestionId)
110
+ assert.deepEqual(initial, scaffold(), 'the reducer must remain pure')
111
+ })
112
+ for (const field of ['state', 'highlight', 'showLink'] as const) {
113
+ it(`clears only ${field}`, () => {
114
+ const initial = scaffold()
115
+ const result = unsafe(initial, { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field, value: null })
116
+ const expected = { ...initial.highlightRulesById!.h }
117
+ delete expected[field]
118
+ assert.deepEqual(result.highlightRulesById?.h, expected)
119
+ assert.deepEqual(result.highlightRulesById?.hc, initial.highlightRulesById?.hc)
120
+ })
121
+ }
122
+ it('preserves false and zero authored outputs and two-editor independent writes', () => {
123
+ const base = scaffold()
124
+ const severity: TemplateOp = { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field: 'state', value: 0 }
125
+ const link: TemplateOp = { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field: 'showLink', value: false }
126
+ const result = apply(base, [severity, link])
127
+ assert.deepEqual(result, apply(base, [link, severity]))
128
+ assert.equal(result.highlightRulesById!.h.state, 0)
129
+ assert.equal(result.highlightRulesById!.h.showLink, false)
130
+ assert.deepEqual(reduceToMinimalForm(result, { isDefault: templateRuleAuthoringIsDefault }), result)
131
+ assert.deepEqual(result.prefillRulesById, base.prefillRulesById)
132
+ assert.equal(result.visibilityRulesById, undefined, '7684-F08 prefill does not become visibility')
133
+ })
134
+ })
135
+
136
+ describe('7684-F07 closed wire shapes and direct replay refusals', () => {
137
+ for (const opType of settingsTypes) {
138
+ for (const malformed of [
139
+ { field: 'unknown', value: true }, { field: 'enabled', value: 'true' },
140
+ { field: 'enabled', value: null }, { field: 'requiredAll', value: 1 },
141
+ { field: 'enabled' }, { field: 'enabled', value: true, patch: {} },
142
+ ]) it(`${opType} rejects ${JSON.stringify(malformed)} on wire and replay`, () => {
143
+ const op = { type: opType, questionId: 'target', ...malformed }
144
+ assert.ok(templateOpSchema(op) instanceof type.errors)
145
+ refused(scaffold(), op)
146
+ })
147
+ it(`${opType} rejects a missing/deleted question after wire admission`, () => {
148
+ const op = { type: opType, questionId: 'gone', field: 'enabled', value: true }
149
+ assert.equal(templateOpSchema(op) instanceof type.errors, false)
150
+ refused(scaffold(), op)
151
+ const deleted = applyOperation(scaffold(), { type: 'question.delete', questionId: 'target' })
152
+ refused(deleted, { ...op, questionId: 'target' })
153
+ refused(scaffold(), { ...op, questionId: '__proto__' })
154
+ })
155
+ }
156
+ for (const malformed of [
157
+ { field: 'missing', value: true }, { field: 'state', value: true },
158
+ { field: 'showLink', value: 'false' }, { field: 'highlight', value: 0 },
159
+ { field: 'condition', value: null }, { field: 'condition', value: [] },
160
+ { field: 'condition', value: { sourceQuestionId: 'source', alternativeIds: [1] } },
161
+ { field: 'condition', value: { sourceQuestionId: 'source', operator: 1 } },
162
+ { field: 'state', value: 3, patch: {} },
163
+ ]) it(`highlight edit rejects ${JSON.stringify(malformed)} on wire and replay`, () => {
164
+ const op = { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', ...malformed }
165
+ assert.ok(templateOpSchema(op) instanceof type.errors)
166
+ refused(scaffold(), op)
167
+ })
168
+ for (const value of [NaN, Infinity, -Infinity]) it(`direct replay refuses non-finite ${value}`, () => {
169
+ refused(scaffold(), { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field: 'state', value })
170
+ })
171
+ for (const patch of [
172
+ { questionId: 'column' }, { questionId: 'gone' }, { ruleId: 'gone' },
173
+ { field: 'condition', value: { sourceQuestionId: 'gone' } },
174
+ { field: 'condition', value: { sourceQuestionId: 'source', alternativeId: 'other-a' } },
175
+ { field: 'condition', value: { sourceQuestionId: 'source', alternativeIds: ['a', 'gone'] } },
176
+ ]) it(`refuses invalid ownership/reference ${JSON.stringify(patch)}`, () => {
177
+ refused(scaffold(), { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field: 'showLink', value: false, ...patch })
178
+ })
179
+ it('refuses ambiguous ownership and deleted sources without partial writes', () => {
180
+ const ambiguous = scaffold()
181
+ ambiguous.highlightRuleOrderByQuestionId!.column.push('h')
182
+ refused(ambiguous, { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field: 'state', value: 3 })
183
+ const deleted = applyOperation(scaffold(), { type: 'question.delete', questionId: 'source' })
184
+ refused(deleted, { type: 'highlightRule.setField', questionId: 'target', ruleId: 'h', field: 'condition', value: { sourceQuestionId: 'source' } })
185
+ })
186
+ })
187
+
188
+ describe('7684-F01/F05 ownership cleanup and canonical history', () => {
189
+ for (const questionId of ['target', 'column', 'grid']) it(`question deletion cleans ${questionId}'s owned settings`, () => {
190
+ const base = apply(scaffold(), ['target', 'column'].flatMap((questionId) => settingsTypes.map((type) =>
191
+ ({ type, questionId, field: 'enabled', value: true } as TemplateOp))))
192
+ const result = applyOperation(base, { type: 'question.delete', questionId })
193
+ const deletedOwner = questionId === 'grid' ? 'column' : questionId
194
+ for (const type of settingsTypes) {
195
+ assert.equal(result[rootOf(type)]?.[deletedOwner], undefined)
196
+ assert.deepEqual(result[rootOf(type)]?.[deletedOwner === 'target' ? 'column' : 'target'], { enabled: true })
197
+ }
198
+ assert.equal(result.highlightRuleOrderByQuestionId?.[deletedOwner], undefined)
199
+ })
200
+ it('prunes false flags and empty containers only under the new canonical predicate', () => {
201
+ const raw = {
202
+ ...scaffold(),
203
+ narrativeRuleSettingsByQuestionId: { target: { enabled: false, requiredAll: true }, column: { enabled: false } },
204
+ highlightRuleSettingsByQuestionId: { target: { enabled: true, requiredAll: false } },
205
+ }
206
+ const next = reduceToMinimalForm(raw, { isDefault: templateRuleAuthoringIsDefault })
207
+ assert.deepEqual(next.narrativeRuleSettingsByQuestionId, { target: { requiredAll: true } })
208
+ assert.deepEqual(next.highlightRuleSettingsByQuestionId, { target: { enabled: true } })
209
+ assert.deepEqual(reduceToMinimalForm(next, { isDefault: templateRuleAuthoringIsDefault }), next)
210
+ assert.equal(qnrTemplateDocumentSchema(next) instanceof type.errors, false)
211
+ assert.deepEqual(reduceToMinimalForm(raw, { isDefault: templateAuthoringIsDefault }), raw)
212
+ for (const predicate of [templateDocumentIsDefaultV0281, templateDocumentIsDefault, templateAuthoringIsDefault]) {
213
+ assert.equal(predicate('narrativeRuleSettingsByQuestionId.target.enabled', false), false)
214
+ }
215
+ assert.equal(templateRuleAuthoringIsDefault('questionsById.target.enabled', false), false)
216
+ assert.equal(templateRuleAuthoringIsDefault('highlightRulesById.h.highlight', false), false)
217
+ })
218
+ for (const settings of [{ enabled: false }, { requiredAll: 'true' }, { enabled: true, extra: true }, null]) {
219
+ it(`narrative document settings reject ${JSON.stringify(settings)}`, () => {
220
+ assert.ok(qnrTemplateDocumentSchema({ ...scaffold(), narrativeRuleSettingsByQuestionId: { target: settings } }) instanceof type.errors)
221
+ })
222
+ }
223
+ it('replays the released replacing/moving setters unchanged', () => {
224
+ const old = applyOperation(scaffold(), { type: 'highlightRule.set', ruleId: 'h', questionId: 'column', condition: { sourceQuestionId: 'historically-dangling' } })
225
+ assert.deepEqual(old.highlightRulesById?.h, { condition: { sourceQuestionId: 'historically-dangling' } })
226
+ assert.deepEqual(old.highlightRuleOrderByQuestionId, { column: ['hc', 'h'] })
227
+ const narrative = applyOperation(scaffold(), { type: 'narrativeRule.set', ruleId: 'n', questionId: 'column', condition: { sourceQuestionId: 'historically-dangling' } })
228
+ assert.deepEqual(narrative.narrativeRuleOrderByQuestionId, { column: ['n'] })
229
+ })
230
+ it('keeps historical hashes and new-write hashes distinct', async () => {
231
+ const historical = { ...scaffold(), highlightRuleSettingsByQuestionId: { target: { enabled: true, requiredAll: false } } }
232
+ const historicalHash = await hashCanonical(reduceToMinimalForm(historical, { isDefault: templateAuthoringIsDefault }))
233
+ assert.equal(historicalHash, 'sha256:048fa69133403b437c749ba97e54ebb582defbe269e363a5f42921cfb3ed2e6c')
234
+ const next = reduceToMinimalForm(historical, { isDefault: templateRuleAuthoringIsDefault })
235
+ assert.notEqual(await hashCanonical(next), historicalHash)
236
+ assert.equal(await hashCanonical(reduceToMinimalForm(historical, { isDefault: templateDocumentIsDefault })), historicalHash)
237
+ assert.equal(canonicalJson(historical).includes('requiredAll":false'), true)
238
+ })
239
+ })
240
+
241
+ /**
242
+ * 7684-F02: shouldShow bypasses disabled rules; any([])=false, all([])=true.
243
+ * Source: asma-app-qnreditor 1cf4a490bffec0db7ab9069729adb4104f0de8c3,
244
+ * src/helpers/NarrativeValidator.ts shouldShow/computeLocalConditionals.
245
+ * The match vectors include a missing source as false. No alternate runtime evaluator is exported.
246
+ */
247
+ describe('7684-F02 legacy narrative truth fixtures and the unresolved presence boundary', () => {
248
+ for (const enabled of [false, true]) for (const all of [false, true]) {
249
+ for (const [matches, anyTruth, allTruth] of [
250
+ [[], false, true], [[false], false, false], [[true], true, true], [[false, true], true, false],
251
+ ] as const) it(`preserves enabled=${enabled} all=${all} matches=${JSON.stringify(matches)}`, () => {
252
+ const doc = apply(scaffold(), [
253
+ { type: 'narrativeRuleSettings.set', questionId: 'target', field: 'enabled', value: enabled },
254
+ { type: 'narrativeRuleSettings.set', questionId: 'target', field: 'requiredAll', value: all },
255
+ ])
256
+ const settings = doc.narrativeRuleSettingsByQuestionId?.target
257
+ const actual = !settings?.enabled || (settings.requiredAll ? matches.every(Boolean) : matches.some(Boolean))
258
+ const legacyExpected = !enabled || (all ? allTruth : anyTruth)
259
+ assert.equal(actual, legacyExpected)
260
+ })
261
+ }
262
+ for (const enabled of [false, true]) for (const all of [false, true]) {
263
+ for (const conditionalPresent of [false, true]) {
264
+ it(`keeps ${conditionalPresent ? 'empty' : 'absent'} legacy conditional separate at ${enabled}/${all}`, () => {
265
+ const doc = apply(scaffold(), [
266
+ { type: 'narrativeRuleSettings.set', questionId: 'target', field: 'enabled', value: enabled },
267
+ { type: 'narrativeRuleSettings.set', questionId: 'target', field: 'requiredAll', value: all },
268
+ ])
269
+ const settings = doc.narrativeRuleSettingsByQuestionId?.target
270
+ const canonicalEmptyTruth = !settings?.enabled || !!settings.requiredAll
271
+ // Pinned shouldShow: absent conditional bypasses computation; [] reaches any/all.
272
+ const legacyTruth = !enabled || !conditionalPresent || all
273
+ const unresolved = enabled && !all && !conditionalPresent
274
+ if (unresolved) assert.notEqual(canonicalEmptyTruth, legacyTruth)
275
+ else assert.equal(canonicalEmptyTruth, legacyTruth)
276
+ const withEmptyOrder = { ...doc, narrativeRuleOrderByQuestionId: { target: [] } }
277
+ const minimal = reduceToMinimalForm(withEmptyOrder)
278
+ assert.equal(Object.hasOwn(minimal, 'narrativeRuleOrderByQuestionId'), false)
279
+ assert.equal(Object.hasOwn(settings ?? {}, 'conditionalPresent'), false)
280
+ // Approved interim: P1 refuses the unresolved family before writes. This release
281
+ // adds no presence marker and cannot license coalescing those two truths at import.
282
+ })
283
+ }
284
+ }
285
+ })
@@ -95,6 +95,13 @@ const highlightRuleSettingsSchema = type({
95
95
  requiredAll: 'true?',
96
96
  })
97
97
 
98
+ /** M-065 new root: no undeclared member and no second encoding of false. */
99
+ const narrativeRuleSettingsSchema = type({
100
+ enabled: 'true?',
101
+ requiredAll: 'true?',
102
+ '+': 'reject',
103
+ })
104
+
98
105
  const narrativeRuleSchema = type({
99
106
  condition: ruleConditionSchema,
100
107
  ...({ '[string]': 'unknown' } as const),
@@ -441,6 +448,7 @@ export const qnrTemplateDocumentSchema = type({
441
448
  "prefillRulesById?": recordOf(prefillRuleSchema),
442
449
  prefillRuleOrderByQuestionId: 'Record<string, string[]>?',
443
450
  "highlightRuleSettingsByQuestionId?": recordOf(highlightRuleSettingsSchema),
451
+ "narrativeRuleSettingsByQuestionId?": recordOf(narrativeRuleSettingsSchema),
444
452
  "dataMappingsById?": recordOf(dataMappingSchema),
445
453
  "mappingNodesById?": recordOf(mappingNodeSchema),
446
454
  "mappingBindingsById?": recordOf(mappingBindingSchema),
@@ -808,6 +816,26 @@ export const templateOpSchema = type.or(
808
816
  type({ type: '"visibilityRule.delete"', ruleId: 'string' }),
809
817
  type({ type: '"highlightRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
810
818
  type({ type: '"highlightRule.delete"', ruleId: 'string' }),
819
+ type({
820
+ type: '"highlightRule.setField"', ruleId: 'string > 0', questionId: 'string > 0',
821
+ field: '"condition"', value: ruleConditionSchema, '+': 'reject',
822
+ }),
823
+ type({
824
+ type: '"highlightRule.setField"', ruleId: 'string > 0', questionId: 'string > 0',
825
+ field: '"state"', value: 'number | null', '+': 'reject',
826
+ }),
827
+ type({
828
+ type: '"highlightRule.setField"', ruleId: 'string > 0', questionId: 'string > 0',
829
+ field: '"highlight" | "showLink"', value: 'boolean | null', '+': 'reject',
830
+ }),
831
+ type({
832
+ type: '"highlightRuleSettings.set"', questionId: 'string > 0',
833
+ field: '"enabled" | "requiredAll"', value: 'boolean', '+': 'reject',
834
+ }),
835
+ type({
836
+ type: '"narrativeRuleSettings.set"', questionId: 'string > 0',
837
+ field: '"enabled" | "requiredAll"', value: 'boolean', '+': 'reject',
838
+ }),
811
839
  type({ type: '"narrativeRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
812
840
  type({ type: '"narrativeRule.delete"', ruleId: 'string' }),
813
841
  type({
@@ -1129,6 +1157,16 @@ export const templateDocumentIsDefaultV0281: IsDefault = (path, value) =>
1129
1157
  export const templateAuthoringIsDefault: IsDefault = (path, value) =>
1130
1158
  templateDocumentIsDefault(path, value) || isTemplateAuthoringDefault(path, value)
1131
1159
 
1160
+ /**
1161
+ * ASMA-7684 new-write canonical form: false rule flags are omitted, independently.
1162
+ * Use for new rule authoring/imports only. All released predicates above stay unchanged for
1163
+ * historical snapshot/delta verification, including the 0.39/0.40 authoring canonical form.
1164
+ * The full path is anchored so a coincidentally named flag in a question/rule bag is untouched.
1165
+ */
1166
+ export const templateRuleAuthoringIsDefault: IsDefault = (path, value) =>
1167
+ templateAuthoringIsDefault(path, value) ||
1168
+ (value === false && /^(highlight|narrative)RuleSettingsByQuestionId\.[^.]+\.(enabled|requiredAll)$/.test(path))
1169
+
1132
1170
  /**
1133
1171
  * The instance-side half of the default lint: every present-and-default field on a stored
1134
1172
  * template document, ready for the contract test to reject. Complements
@@ -545,6 +545,17 @@ export type HighlightRule = {
545
545
  * `false` would be a second encoding of "not set" and would change `document_hash`.
546
546
  */
547
547
  export type HighlightRuleSettings = { enabled?: true; requiredAll?: true }
548
+
549
+ /**
550
+ * M-065 narrative flags, independent of the highlight flags and of stored rules.
551
+ * `enabled` is legacy `have_narrative`; `requiredAll` is legacy `required_all`.
552
+ * False means absence of that member only. Disabling retains the rules and the other flag.
553
+ *
554
+ * This shape does not encode legacy absent versus empty `conditional`. Enabled/any with absent
555
+ * conditional remains an unresolved import case until an explicit representation is ratified.
556
+ */
557
+ export type NarrativeRuleSettings = { enabled?: true; requiredAll?: true }
558
+ export type RuleSettingField = 'enabled' | 'requiredAll'
548
559
  export type NarrativeRule = { condition: RuleCondition; [key: string]: unknown }
549
560
  export type QnrRule = {
550
561
  condition: RuleCondition
@@ -886,6 +897,8 @@ export type QnrTemplateDocument = {
886
897
  prefillRuleOrderByQuestionId?: Record<QuestionId, PrefillRuleId[]>
887
898
  /** Only for a question that actually sets one of them; an all-default entry is omitted. */
888
899
  highlightRuleSettingsByQuestionId?: Record<QuestionId, HighlightRuleSettings>
900
+ /** M-065: true-only flags; stored rules never imply either setting. */
901
+ narrativeRuleSettingsByQuestionId?: Record<QuestionId, NarrativeRuleSettings>
889
902
  dataMappingsById?: Record<MappingId, QnrDataMapping>
890
903
  mappingNodesById?: Record<NodeId, MappingNode>
891
904
  mappingBindingsById?: Record<BindingId, MappingBinding>
@@ -5,6 +5,7 @@ import type {
5
5
  AlternativeChartLegend,
6
6
  LegacyBindingOverride,
7
7
  MappingBinding,
8
+ NarrativeRuleSettings,
8
9
  } from './templateDocument.js'
9
10
 
10
11
  /**
@@ -315,3 +316,19 @@ export type UpdateSettingsStaysOpen = Assert<
315
316
  ? true
316
317
  : false
317
318
  >
319
+
320
+
321
+ // ASMA-7684: member/value correlation and true-only stored narrative settings.
322
+ export type NarrativeSettingsRefuseFalse = Assert<Refuses<{ enabled: false }, NarrativeRuleSettings>>
323
+ export type NarrativeSettingsOpRefusesNull = Assert<Refuses<
324
+ { type: 'narrativeRuleSettings.set'; questionId: string; field: 'enabled'; value: null }, TemplateOp
325
+ >>
326
+ export type NarrativeSettingsOpRefusesUnknownField = Assert<Refuses<
327
+ { type: 'narrativeRuleSettings.set'; questionId: string; field: 'showLink'; value: boolean }, TemplateOp
328
+ >>
329
+ export type HighlightFieldRefusesWrongValue = Assert<Refuses<
330
+ { type: 'highlightRule.setField'; ruleId: string; questionId: string; field: 'state'; value: boolean }, TemplateOp
331
+ >>
332
+ export type HighlightFieldRefusesMissingCondition = Assert<Refuses<
333
+ { type: 'highlightRule.setField'; ruleId: string; questionId: string; field: 'condition'; value: null }, TemplateOp
334
+ >>