asma-core-helpers 0.40.0 → 0.41.1

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.
Files changed (50) hide show
  1. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  2. package/lib/collaboration/applyOperation.js +212 -0
  3. package/lib/collaboration/applyOperation.js.map +1 -1
  4. package/lib/collaboration/index.d.ts +1 -0
  5. package/lib/collaboration/index.d.ts.map +1 -1
  6. package/lib/collaboration/index.js +1 -0
  7. package/lib/collaboration/index.js.map +1 -1
  8. package/lib/collaboration/narrativePresence.d.ts +12 -0
  9. package/lib/collaboration/narrativePresence.d.ts.map +1 -0
  10. package/lib/collaboration/narrativePresence.js +34 -0
  11. package/lib/collaboration/narrativePresence.js.map +1 -0
  12. package/lib/collaboration/operations.d.ts +53 -1
  13. package/lib/collaboration/operations.d.ts.map +1 -1
  14. package/lib/collaboration/operations.js +4 -0
  15. package/lib/collaboration/operations.js.map +1 -1
  16. package/lib/collaboration/schemas.d.ts +92 -1
  17. package/lib/collaboration/schemas.d.ts.map +1 -1
  18. package/lib/collaboration/schemas.js +49 -2
  19. package/lib/collaboration/schemas.js.map +1 -1
  20. package/lib/collaboration/templateAuthoringMeta.d.ts +4 -4
  21. package/lib/collaboration/templateAuthoringMeta.d.ts.map +1 -1
  22. package/lib/collaboration/templateAuthoringMeta.js +103 -5
  23. package/lib/collaboration/templateAuthoringMeta.js.map +1 -1
  24. package/lib/collaboration/templateDocument.d.ts +22 -0
  25. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  26. package/lib/collaboration/templateDocument.js.map +1 -1
  27. package/lib/collaboration/typeContracts.d.ts +30 -1
  28. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  29. package/lib/g-definitions.d.ts +5 -0
  30. package/lib/g-definitions.d.ts.map +1 -1
  31. package/lib/g-definitions.js +6 -0
  32. package/lib/g-definitions.js.map +1 -1
  33. package/lib/overlayBack.d.ts +103 -0
  34. package/lib/overlayBack.d.ts.map +1 -0
  35. package/lib/overlayBack.js +540 -0
  36. package/lib/overlayBack.js.map +1 -0
  37. package/package.json +2 -1
  38. package/src/collaboration/applyOperation.ts +230 -0
  39. package/src/collaboration/index.ts +1 -0
  40. package/src/collaboration/narrativePresence.test.ts +328 -0
  41. package/src/collaboration/narrativePresence.ts +42 -0
  42. package/src/collaboration/operations.ts +25 -0
  43. package/src/collaboration/ruleAuthoring.test.ts +285 -0
  44. package/src/collaboration/schemas.ts +65 -2
  45. package/src/collaboration/templateAuthoringMeta.ts +107 -6
  46. package/src/collaboration/templateDocument.ts +23 -0
  47. package/src/collaboration/typeContracts.ts +17 -0
  48. package/src/g-definitions.ts +13 -0
  49. package/src/overlayBack.test.ts +742 -0
  50. package/src/overlayBack.ts +647 -0
@@ -0,0 +1,42 @@
1
+ import type { QnrTemplateDocument } from './templateDocument.js'
2
+
3
+ /** Additive source-state laws; old ARRAY documents have no new validation or reinterpretation. */
4
+ export type NarrativePresenceViolation = {
5
+ law: 'NARRATIVE-PRESENCE'
6
+ path: string
7
+ detail: string
8
+ }
9
+
10
+ /** Count occurrences, not just distinct owners: duplicate structural references are ambiguous. */
11
+ export const hasSingleNarrativeQuestionOwner = (document: QnrTemplateDocument, questionId: string): boolean => {
12
+ if (questionId === '' || !Object.hasOwn(document.questionsById ?? {}, questionId)) return false
13
+ let occurrences = document.questionOrder.filter((id) => id === questionId).length
14
+ for (const question of Object.values(document.questionsById ?? {})) {
15
+ if (question.type === 'QuestionGrid') {
16
+ occurrences += (question.grid?.columnIds ?? []).filter((id) => id === questionId).length
17
+ }
18
+ }
19
+ return occurrences === 1
20
+ }
21
+
22
+ /** Marker position is exact: similarly named open rule/condition extras are ordinary historical data. */
23
+ export const findNarrativePresenceViolations = (document: QnrTemplateDocument): NarrativePresenceViolation[] => {
24
+ const violations: NarrativePresenceViolation[] = []
25
+ for (const [questionId, settings] of Object.entries(document.narrativeRuleSettingsByQuestionId ?? {})) {
26
+ if (settings === null || typeof settings !== 'object' || !Object.hasOwn(settings, 'conditionalPresence')) continue
27
+ const path = `narrativeRuleSettingsByQuestionId[${JSON.stringify(questionId)}].conditionalPresence`
28
+ const marker = settings.conditionalPresence
29
+ const validShape = !Array.isArray(settings) && Object.keys(settings).every((key) =>
30
+ key === 'conditionalPresence' || ((key === 'enabled' || key === 'requiredAll') && settings[key] === true))
31
+ if (!validShape || (marker !== 'absent' && marker !== 'null')) {
32
+ violations.push({ law: 'NARRATIVE-PRESENCE', path, detail: 'Malformed source presence settings' })
33
+ }
34
+ if (!hasSingleNarrativeQuestionOwner(document, questionId)) {
35
+ violations.push({ law: 'NARRATIVE-PRESENCE', path, detail: 'Presence target must have exactly one structural owner' })
36
+ }
37
+ if ((document.narrativeRuleOrderByQuestionId?.[questionId]?.length ?? 0) !== 0) {
38
+ violations.push({ law: 'NARRATIVE-PRESENCE', path, detail: 'Source presence cannot coexist with owned narrative rules' })
39
+ }
40
+ }
41
+ return violations
42
+ }
@@ -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,17 @@ 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
+
76
+ export type NarrativeRuleCollectionAction =
77
+ | { kind: 'set'; ruleId: NarrativeRuleId; condition: RuleCondition }
78
+ | { kind: 'delete'; ruleId: NarrativeRuleId }
79
+ | { kind: 'materialize' }
80
+
69
81
  export type TemplateOp =
70
82
  | { type: 'template.updateMeta'; patch: Record<string, OpValue | Record<string, unknown>> }
71
83
  | {
@@ -441,6 +453,15 @@ export type TemplateOp =
441
453
  | { type: 'visibilityRule.delete'; ruleId: VisibilityRuleId }
442
454
  | { type: 'highlightRule.set'; ruleId: HighlightRuleId; questionId: QuestionId; condition: RuleCondition }
443
455
  | { type: 'highlightRule.delete'; ruleId: HighlightRuleId }
456
+ /** Edits an existing, owned rule without replacing its other authored outputs. */
457
+ | ({ type: 'highlightRule.setField'; ruleId: HighlightRuleId; questionId: QuestionId } & HighlightRuleFieldWrite)
458
+ | { type: 'highlightRuleSettings.set'; questionId: QuestionId; field: RuleSettingField; value: boolean }
459
+ | { type: 'narrativeRuleSettings.set'; questionId: QuestionId; field: RuleSettingField; value: boolean }
460
+ /** Atomic explicit ARRAY selection/edit; ABSENT/NULL may only originate in validated source. */
461
+ | ({ type: 'narrativeRuleCollection.edit'; questionId: QuestionId } & (
462
+ | { expectedPresence: 'array' | 'absent'; intent: 'edit'; action: NarrativeRuleCollectionAction }
463
+ | { expectedPresence: 'null'; intent: 'repair-null'; action: Exclude<NarrativeRuleCollectionAction, { kind: 'delete' }> }
464
+ ))
444
465
  | { type: 'narrativeRule.set'; ruleId: NarrativeRuleId; questionId: QuestionId; condition: RuleCondition }
445
466
  | { type: 'narrativeRule.delete'; ruleId: NarrativeRuleId }
446
467
  | {
@@ -519,6 +540,10 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
519
540
  'visibilityRule.delete': true,
520
541
  'highlightRule.set': true,
521
542
  'highlightRule.delete': true,
543
+ 'highlightRule.setField': true,
544
+ 'highlightRuleSettings.set': true,
545
+ 'narrativeRuleSettings.set': true,
546
+ 'narrativeRuleCollection.edit': true,
522
547
  'narrativeRule.set': true,
523
548
  'narrativeRule.delete': true,
524
549
  '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
+ })
@@ -5,6 +5,7 @@ import { findDocLawViolations, type DocLawViolation } from './docLaws.js'
5
5
  import { IMPLEMENTED_ANSWER_OP_TYPES } from './answerOperations.js'
6
6
  import { IMPLEMENTED_OP_TYPES } from './operations.js'
7
7
  import { QUESTION_TYPES } from './questionTypes.js'
8
+ import { findNarrativePresenceViolations, type NarrativePresenceViolation } from './narrativePresence.js'
8
9
  import {
9
10
  COMPATIBILITY_COLLECTIONS,
10
11
  isTemplateAuthoringDefault,
@@ -95,6 +96,14 @@ const highlightRuleSettingsSchema = type({
95
96
  requiredAll: 'true?',
96
97
  })
97
98
 
99
+ /** M-065 new root: no undeclared member and no second encoding of false. */
100
+ const narrativeRuleSettingsSchema = type({
101
+ enabled: 'true?',
102
+ requiredAll: 'true?',
103
+ conditionalPresence: '("absent" | "null")?',
104
+ '+': 'reject',
105
+ })
106
+
98
107
  const narrativeRuleSchema = type({
99
108
  condition: ruleConditionSchema,
100
109
  ...({ '[string]': 'unknown' } as const),
@@ -441,6 +450,7 @@ export const qnrTemplateDocumentSchema = type({
441
450
  "prefillRulesById?": recordOf(prefillRuleSchema),
442
451
  prefillRuleOrderByQuestionId: 'Record<string, string[]>?',
443
452
  "highlightRuleSettingsByQuestionId?": recordOf(highlightRuleSettingsSchema),
453
+ "narrativeRuleSettingsByQuestionId?": recordOf(narrativeRuleSettingsSchema),
444
454
  "dataMappingsById?": recordOf(dataMappingSchema),
445
455
  "mappingNodesById?": recordOf(mappingNodeSchema),
446
456
  "mappingBindingsById?": recordOf(mappingBindingSchema),
@@ -808,6 +818,43 @@ export const templateOpSchema = type.or(
808
818
  type({ type: '"visibilityRule.delete"', ruleId: 'string' }),
809
819
  type({ type: '"highlightRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
810
820
  type({ type: '"highlightRule.delete"', ruleId: 'string' }),
821
+ type({
822
+ type: '"highlightRule.setField"', ruleId: 'string > 0', questionId: 'string > 0',
823
+ field: '"condition"', value: ruleConditionSchema, '+': 'reject',
824
+ }),
825
+ type({
826
+ type: '"highlightRule.setField"', ruleId: 'string > 0', questionId: 'string > 0',
827
+ field: '"state"', value: 'number | null', '+': 'reject',
828
+ }),
829
+ type({
830
+ type: '"highlightRule.setField"', ruleId: 'string > 0', questionId: 'string > 0',
831
+ field: '"highlight" | "showLink"', value: 'boolean | null', '+': 'reject',
832
+ }),
833
+ type({
834
+ type: '"highlightRuleSettings.set"', questionId: 'string > 0',
835
+ field: '"enabled" | "requiredAll"', value: 'boolean', '+': 'reject',
836
+ }),
837
+ type({
838
+ type: '"narrativeRuleSettings.set"', questionId: 'string > 0',
839
+ field: '"enabled" | "requiredAll"', value: 'boolean', '+': 'reject',
840
+ }),
841
+ type({
842
+ type: '"narrativeRuleCollection.edit"', questionId: 'string > 0',
843
+ expectedPresence: '"array" | "absent"', intent: '"edit"', '+': 'reject',
844
+ action: type.or(
845
+ type({ kind: '"set"', ruleId: 'string > 0', condition: ruleConditionSchema, '+': 'reject' }),
846
+ type({ kind: '"delete"', ruleId: 'string > 0', '+': 'reject' }),
847
+ type({ kind: '"materialize"', '+': 'reject' }),
848
+ ),
849
+ }),
850
+ type({
851
+ type: '"narrativeRuleCollection.edit"', questionId: 'string > 0',
852
+ expectedPresence: '"null"', intent: '"repair-null"', '+': 'reject',
853
+ action: type.or(
854
+ type({ kind: '"set"', ruleId: 'string > 0', condition: ruleConditionSchema, '+': 'reject' }),
855
+ type({ kind: '"materialize"', '+': 'reject' }),
856
+ ),
857
+ }),
811
858
  type({ type: '"narrativeRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
812
859
  type({ type: '"narrativeRule.delete"', ruleId: 'string' }),
813
860
  type({
@@ -1129,6 +1176,16 @@ export const templateDocumentIsDefaultV0281: IsDefault = (path, value) =>
1129
1176
  export const templateAuthoringIsDefault: IsDefault = (path, value) =>
1130
1177
  templateDocumentIsDefault(path, value) || isTemplateAuthoringDefault(path, value)
1131
1178
 
1179
+ /**
1180
+ * ASMA-7684 new-write canonical form: false rule flags are omitted, independently.
1181
+ * Use for new rule authoring/imports only. All released predicates above stay unchanged for
1182
+ * historical snapshot/delta verification, including the 0.39/0.40 authoring canonical form.
1183
+ * The full path is anchored so a coincidentally named flag in a question/rule bag is untouched.
1184
+ */
1185
+ export const templateRuleAuthoringIsDefault: IsDefault = (path, value) =>
1186
+ templateAuthoringIsDefault(path, value) ||
1187
+ (value === false && /^(highlight|narrative)RuleSettingsByQuestionId\.[^.]+\.(enabled|requiredAll)$/.test(path))
1188
+
1132
1189
  /**
1133
1190
  * The instance-side half of the default lint: every present-and-default field on a stored
1134
1191
  * template document, ready for the contract test to reject. Complements
@@ -1270,13 +1327,18 @@ const validate =
1270
1327
  return { ok: true, value: out as T }
1271
1328
  }
1272
1329
 
1273
- export const validateTemplateDocument = validate<QnrTemplateDocument>(qnrTemplateDocumentSchema)
1330
+ export const validateTemplateDocument = (value: unknown): Validation<QnrTemplateDocument> => {
1331
+ const shape = validate<QnrTemplateDocument>(qnrTemplateDocumentSchema)(value)
1332
+ if (!shape.ok) return shape
1333
+ const violations = findNarrativePresenceViolations(shape.value)
1334
+ return violations.length === 0 ? shape : { ok: false, summary: violations.map((v) => `${v.path}: ${v.detail}`).join('; ') }
1335
+ }
1274
1336
 
1275
1337
  /**
1276
1338
  * Full template-document admission check for the contract test: schema + DOC-LAW-1/2 lints +
1277
1339
  * default lint + binding uniqueness. A document passes only in its canonical minimal form.
1278
1340
  */
1279
- export type TemplateDocumentContractViolation = DocLawViolation | QuestionOwnershipViolation
1341
+ export type TemplateDocumentContractViolation = DocLawViolation | QuestionOwnershipViolation | NarrativePresenceViolation
1280
1342
 
1281
1343
  export const findTemplateDocumentContractViolations = (
1282
1344
  document: QnrTemplateDocument,
@@ -1284,6 +1346,7 @@ export const findTemplateDocumentContractViolations = (
1284
1346
  ...findDocLawViolations(document),
1285
1347
  ...findDocLawDefaultViolations(document),
1286
1348
  ...findQuestionOwnershipViolations(document),
1349
+ ...findNarrativePresenceViolations(document),
1287
1350
  ]
1288
1351
 
1289
1352
  export const findDuplicateBindingTargetsSummary = (document: QnrTemplateDocument): string[] =>