asma-core-helpers 0.30.0 → 0.31.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.
Files changed (31) hide show
  1. package/lib/collaboration/applyOperation.d.ts +33 -1
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +633 -9
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +109 -2
  6. package/lib/collaboration/operations.d.ts.map +1 -1
  7. package/lib/collaboration/operations.js +7 -0
  8. package/lib/collaboration/operations.js.map +1 -1
  9. package/lib/collaboration/schemas.d.ts +163 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +173 -3
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +176 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +9 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.js +78 -1
  18. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  19. package/lib/collaboration/typeContracts.d.ts +53 -0
  20. package/lib/collaboration/typeContracts.d.ts.map +1 -0
  21. package/lib/collaboration/typeContracts.js +2 -0
  22. package/lib/collaboration/typeContracts.js.map +1 -0
  23. package/package.json +1 -1
  24. package/src/collaboration/applyOperation.ts +736 -9
  25. package/src/collaboration/operations.ts +97 -0
  26. package/src/collaboration/schemas.ts +191 -1
  27. package/src/collaboration/templateDocument.ts +167 -1
  28. package/src/collaboration/testHelpers/documentGenerator.ts +77 -1
  29. package/src/collaboration/typeContracts.ts +57 -0
  30. package/src/collaboration/typedAuthoring.test.ts +641 -0
  31. package/src/collaboration/typedAuthoringHardening.test.ts +408 -0
@@ -1,5 +1,7 @@
1
1
  import type {
2
2
  ActionId,
3
+ ActionMetadata,
4
+ ActionType,
3
5
  AltId,
4
6
  BindingCardinality,
5
7
  BindingId,
@@ -10,6 +12,7 @@ import type {
10
12
  FilterId,
11
13
  HighlightRuleId,
12
14
  LayoutPlacement,
15
+ MappingFilterPayload,
13
16
  MappingId,
14
17
  NarrativeRuleId,
15
18
  NodeId,
@@ -73,6 +76,32 @@ export type TemplateOp =
73
76
  columnQuestionId: QuestionId
74
77
  placement: LayoutPlacement | null
75
78
  }
79
+ /**
80
+ * Adds, moves or removes one column in the grid's filter selection (M-054).
81
+ *
82
+ * Member-wise rather than a whole-list write, which is the difference that makes concurrent
83
+ * authoring work: two authors adding different filters produce two edits to the *current* list, so
84
+ * both survive. A `filterQuestionIds` array written wholesale would have the second overwrite the
85
+ * first with no conflict raised — the same reason DOC-LAW-1 keys collections by id.
86
+ *
87
+ * `include: true` inserts (at `atIndex`, else appends) and **moves** an id already present when
88
+ * `atIndex` is given; `include: false` removes it. An emptied list is omitted, per DOC-LAW-2.
89
+ */
90
+ | {
91
+ type: 'gridColumn.setFilter'
92
+ questionId: QuestionId
93
+ columnQuestionId: QuestionId
94
+ include: boolean
95
+ atIndex?: number
96
+ }
97
+ /** The same member-wise semantics for the grid's owned action ids (M-055). Ids only, never bodies. */
98
+ | {
99
+ type: 'gridColumn.setAction'
100
+ questionId: QuestionId
101
+ actionId: ActionId
102
+ include: boolean
103
+ atIndex?: number
104
+ }
76
105
  // Authoring-side grid rows are the template's *predefined* rows; instance-added rows
77
106
  // are answer ops (answerOperations.ts). `gridRow.move` is anchor-relative (OQ-V2-24).
78
107
  | { type: 'gridRow.create'; questionId: QuestionId; rowId: RowId; label?: string; atIndex?: number }
@@ -97,10 +126,62 @@ export type TemplateOp =
97
126
  | { type: 'tab.create'; tabId: TabId; label?: string; atIndex?: number }
98
127
  | { type: 'tab.updateField'; tabId: TabId; field: string; value: OpValue }
99
128
  | { type: 'tab.move'; tabId: TabId; toIndex: number }
129
+ /**
130
+ * Writes one question's placement inside a tab's positional grid atomically (M-051).
131
+ *
132
+ * `{row, cell, keepCellSize}` moves as one value, which `tab.updateField` cannot express — an
133
+ * `OpValue` is a scalar or a primitive array — so two dotted updates would be the alternative, and
134
+ * a client that landed one and lost the other would leave a row/cell hybrid the author never
135
+ * authored. `placement: null` clears the entry. Concurrent moves of *different* questions both
136
+ * survive; concurrent moves of the *same* question are last-writer-wins on a whole placement.
137
+ */
138
+ | { type: 'tab.setLayout'; tabId: TabId; questionId: QuestionId; placement: LayoutPlacement | null }
100
139
  | { type: 'tab.delete'; tabId: TabId }
101
140
  // Actions are a set, not an ordered collection (architecture §2.1: `actionsById`, no order array).
102
141
  | { type: 'action.create'; actionId: ActionId; kind?: string }
103
142
  | { type: 'action.updateField'; actionId: ActionId; field: string; value: OpValue }
143
+ /**
144
+ * Creates a **known** action in minimal form, discriminated by kind.
145
+ *
146
+ * Separate from `action.create` (which stays as released, accepting any `kind` string) because the
147
+ * typed path is closed: it cannot mint a UI edit buffer, and it cannot create a kind the reducer
148
+ * has no rules for. Kind is write-once — `action.updateField` refuses to change it.
149
+ */
150
+ /**
151
+ * Two closed arms, not one arm with an optional member: `actionType` is a `gridAction` concept, and a
152
+ * single arm would type-check `{kind: 'topLevelAction', actionType: 'COPY'}` — leaving the reducer as
153
+ * the only thing that noticed, which is a runtime refusal for something the compiler can prevent.
154
+ */
155
+ | { type: 'action.createTyped'; actionId: ActionId; kind: 'topLevelAction'; label?: string; actionType?: never }
156
+ | {
157
+ type: 'action.createTyped'
158
+ actionId: ActionId
159
+ kind: 'gridAction'
160
+ label?: string
161
+ /** A valid draft may omit it; publication is where that is refused. */
162
+ actionType?: ActionType
163
+ }
164
+ /**
165
+ * Adds, moves or removes one grid-action id inside a top-level action's per-grid sequence (M-052).
166
+ *
167
+ * `topLevelAction`-only, member-wise for the same concurrency reason as the grid lists. An emptied
168
+ * sequence drops its grid key, and an emptied map is omitted (DOC-LAW-2).
169
+ */
170
+ | {
171
+ type: 'action.setGridActionRef'
172
+ actionId: ActionId
173
+ gridQuestionId: QuestionId
174
+ gridActionId: ActionId
175
+ include: boolean
176
+ atIndex?: number
177
+ }
178
+ /**
179
+ * Writes or clears one column's metadata on a grid action (M-055).
180
+ *
181
+ * `gridAction`-only. `null` removes the entry; a payload is written canonically, so `{all: true}`
182
+ * stays exclusive with `from`/`to` and an empty object never reaches the document.
183
+ */
184
+ | { type: 'action.setMetadata'; actionId: ActionId; questionId: QuestionId; metadata: ActionMetadata | null }
104
185
  | { type: 'action.delete'; actionId: ActionId }
105
186
  // One entry per mapping root (§2.2a): the root node must exist first (structure pass),
106
187
  // the mapping attaches it to a source (mapping pass). Delete cascades the whole tree.
@@ -162,6 +243,15 @@ export type TemplateOp =
162
243
  operator: string
163
244
  value?: DocScalar
164
245
  }
246
+ /**
247
+ * Sets a filter to one **closed** operator and exactly that operator's payload.
248
+ *
249
+ * Additive beside `mappingFilter.set`, which stays byte-for-byte as released so stored `contains`
250
+ * filters keep replaying. The reducer REPLACES the record rather than patching it, so switching
251
+ * `eq` → `in` cannot leave a stale `value` next to the new `values`; a filter therefore always
252
+ * carries the members of its own operator and no others.
253
+ */
254
+ | ({ type: 'mappingFilter.setTyped'; filterId: FilterId; nodeId: NodeId; fieldId: string } & MappingFilterPayload)
165
255
  | { type: 'mappingFilter.delete'; filterId: FilterId }
166
256
  | { type: 'visibilityRule.set'; ruleId: VisibilityRuleId; questionId: QuestionId; condition: RuleCondition }
167
257
  | { type: 'visibilityRule.delete'; ruleId: VisibilityRuleId }
@@ -198,6 +288,8 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
198
288
  'gridColumn.create': true,
199
289
  'gridColumn.move': true,
200
290
  'gridColumn.setLayout': true,
291
+ 'gridColumn.setFilter': true,
292
+ 'gridColumn.setAction': true,
201
293
  'gridRow.create': true,
202
294
  'gridRow.move': true,
203
295
  'gridRow.delete': true,
@@ -209,9 +301,13 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
209
301
  'tab.create': true,
210
302
  'tab.updateField': true,
211
303
  'tab.move': true,
304
+ 'tab.setLayout': true,
212
305
  'tab.delete': true,
213
306
  'action.create': true,
214
307
  'action.updateField': true,
308
+ 'action.createTyped': true,
309
+ 'action.setGridActionRef': true,
310
+ 'action.setMetadata': true,
215
311
  'action.delete': true,
216
312
  'dataMapping.create': true,
217
313
  'dataMapping.delete': true,
@@ -222,6 +318,7 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
222
318
  'mappingBinding.update': true,
223
319
  'mappingBinding.delete': true,
224
320
  'mappingFilter.set': true,
321
+ 'mappingFilter.setTyped': true,
225
322
  'mappingFilter.delete': true,
226
323
  'visibilityRule.set': true,
227
324
  'visibilityRule.delete': true,
@@ -7,10 +7,12 @@ import { IMPLEMENTED_OP_TYPES } from './operations.js'
7
7
  import { QUESTION_TYPES } from './questionTypes.js'
8
8
  import type { BindingTarget, QnrTemplateDocument } from './templateDocument.js'
9
9
  import {
10
+ ACTION_TYPES,
10
11
  BINDING_CARDINALITIES,
11
12
  BINDING_ON_MANY,
12
13
  BINDING_ON_MISSING,
13
14
  BINDING_OPTION_DEFAULTS,
15
+ MAPPING_FILTER_OPERATORS,
14
16
  bindingTargetKey,
15
17
  } from './templateDocument.js'
16
18
 
@@ -136,6 +138,10 @@ const questionGridPresentationSchema = type({
136
138
  headerTabId: 'string?',
137
139
  "rowEditor?": questionGridRowEditorSchema,
138
140
  defaultColumnWidthsByQuestionId: 'Record<string, number>?',
141
+ // Primitive id arrays, which DOC-LAW-1 allows: the per-entry filter configuration legacy kept in
142
+ // `filter_ui.questions[]` belongs on the column question, so the grid owns only the selection.
143
+ filterQuestionIds: 'string[]?',
144
+ actionIds: 'string[]?',
139
145
  ...({ '[string]': 'unknown' } as const),
140
146
  })
141
147
 
@@ -183,13 +189,46 @@ const qnrGridRowSchema = type({
183
189
  ...({ '[string]': 'unknown' } as const),
184
190
  })
185
191
 
192
+ const qnrTabLayoutSchema = type({
193
+ "placementsByQuestionId?": recordOf(layoutPlacementSchema),
194
+ ...({ '[string]': 'unknown' } as const),
195
+ })
196
+
186
197
  const qnrTabSchema = type({
187
198
  label: 'string?',
199
+ "layout?": qnrTabLayoutSchema,
188
200
  ...({ '[string]': 'unknown' } as const),
189
201
  })
190
202
 
203
+ /**
204
+ * One metadata entry. `all: true` is the canonical all-to-all marker and is exclusive with the bounds —
205
+ * a bare `{}` is refused, because DOC-LAW-2 would make "selected but unbounded" and "not selected" the
206
+ * same absence.
207
+ */
208
+ const actionMetadataSchema = type.or(
209
+ // Every arm declares the OTHER arms' members `never`. Omitting them would not be enough: an
210
+ // ArkType object admits undeclared keys, so `{all: true, from: 'a'}` would satisfy the bounded arm
211
+ // and the exclusivity rule would exist only in the reducer.
212
+ type({ from: docScalar, to: docScalar, "all?": 'never' }),
213
+ type({ from: docScalar, "to?": 'never', "all?": 'never' }),
214
+ type({ "from?": 'never', to: docScalar, "all?": 'never' }),
215
+ type({ all: 'true', "from?": 'never', "to?": 'never' }),
216
+ )
217
+
218
+ /**
219
+ * The action record stays BROAD: `kind` is an optional string and the bag is open, because released
220
+ * documents carry unknown kinds and accidental UI buffers that must remain readable (ADR-0008 DEC-006).
221
+ *
222
+ * The typed members are declared so a KNOWN action's shape is validated where it is present — an
223
+ * ordered primitive id array per grid, and canonical metadata per column — without making any of it
224
+ * required. Narrowing `kind` here is exactly what the freeze forbids.
225
+ */
191
226
  const qnrActionSchema = type({
192
227
  kind: 'string?',
228
+ label: 'string?',
229
+ "actionType?": type.enumerated(...ACTION_TYPES),
230
+ actionIdsByGridQuestionId: 'Record<string, string[]>?',
231
+ "metadataByQuestionId?": recordOf(actionMetadataSchema),
193
232
  ...({ '[string]': 'unknown' } as const),
194
233
  })
195
234
 
@@ -227,10 +266,18 @@ const mappingBindingSchema = type({
227
266
  ...({ '[string]': 'unknown' } as const),
228
267
  })
229
268
 
269
+ /**
270
+ * The stored filter. `operator` stays `string` — released, and documents carry operators outside the
271
+ * closed set (`contains`) that must remain readable. `values`/`from`/`to` are the additive payload
272
+ * members the typed operator arms write.
273
+ */
230
274
  const mappingFilterSchema = type({
231
275
  fieldId: 'string',
232
276
  operator: 'string',
233
277
  "value?": docScalar,
278
+ "values?": '(string | number | boolean)[]',
279
+ "from?": docScalar,
280
+ "to?": docScalar,
234
281
  })
235
282
 
236
283
  const dataMappingSchema = type({
@@ -340,6 +387,20 @@ export const templateOpSchema = type.or(
340
387
  columnQuestionId: 'string',
341
388
  placement: type.or(layoutPlacementSchema, type('null')),
342
389
  }),
390
+ type({
391
+ type: '"gridColumn.setFilter"',
392
+ questionId: 'string',
393
+ columnQuestionId: 'string',
394
+ include: 'boolean',
395
+ atIndex: 'number?',
396
+ }),
397
+ type({
398
+ type: '"gridColumn.setAction"',
399
+ questionId: 'string',
400
+ actionId: 'string',
401
+ include: 'boolean',
402
+ atIndex: 'number?',
403
+ }),
343
404
  type({ type: '"gridRow.create"', questionId: 'string', rowId: 'string', label: 'string?', atIndex: 'number?' }),
344
405
  type({ type: '"gridRow.move"', questionId: 'string', rowId: 'string', afterRowId: 'string | null' }),
345
406
  type({ type: '"gridRow.delete"', questionId: 'string', rowId: 'string' }),
@@ -363,9 +424,60 @@ export const templateOpSchema = type.or(
363
424
  type({ type: '"tab.create"', tabId: 'string', label: 'string?', atIndex: 'number?' }),
364
425
  type({ type: '"tab.updateField"', tabId: 'string', field: 'string', value: opValue }),
365
426
  type({ type: '"tab.move"', tabId: 'string', toIndex: 'number' }),
427
+ type({
428
+ type: '"tab.setLayout"',
429
+ tabId: 'string',
430
+ questionId: 'string',
431
+ placement: type.or(layoutPlacementSchema, type('null')),
432
+ }),
366
433
  type({ type: '"tab.delete"', tabId: 'string' }),
367
434
  type({ type: '"action.create"', actionId: 'string', kind: 'string?' }),
368
435
  type({ type: '"action.updateField"', actionId: 'string', field: 'string', value: opValue }),
436
+ /**
437
+ * Two arms, discriminated on `kind`. A single arm with an optional `actionType` admitted
438
+ * `{kind: 'topLevelAction', actionType: 'COPY'}` and left the reducer as the only thing that
439
+ * noticed — a runtime refusal for something the wire can close.
440
+ *
441
+ * `actionType?: never` on the top-level arm rather than omission: an ArkType object admits
442
+ * undeclared keys, so leaving it out would let it through. Same reason the UI buffers are spelled
443
+ * out as `never` on both arms.
444
+ */
445
+ type({
446
+ type: '"action.createTyped"',
447
+ actionId: 'string',
448
+ kind: '"topLevelAction"',
449
+ label: 'string?',
450
+ "actionType?": 'never',
451
+ "editableLabel?": 'never',
452
+ "editableType?": 'never',
453
+ "editable_label?": 'never',
454
+ "editable_type?": 'never',
455
+ }),
456
+ type({
457
+ type: '"action.createTyped"',
458
+ actionId: 'string',
459
+ kind: '"gridAction"',
460
+ label: 'string?',
461
+ "actionType?": type.enumerated(...ACTION_TYPES),
462
+ "editableLabel?": 'never',
463
+ "editableType?": 'never',
464
+ "editable_label?": 'never',
465
+ "editable_type?": 'never',
466
+ }),
467
+ type({
468
+ type: '"action.setGridActionRef"',
469
+ actionId: 'string',
470
+ gridQuestionId: 'string',
471
+ gridActionId: 'string',
472
+ include: 'boolean',
473
+ atIndex: 'number?',
474
+ }),
475
+ type({
476
+ type: '"action.setMetadata"',
477
+ actionId: 'string',
478
+ questionId: 'string',
479
+ metadata: type.or(actionMetadataSchema, type('null')),
480
+ }),
369
481
  type({ type: '"action.delete"', actionId: 'string' }),
370
482
  type({ type: '"dataMapping.create"', mappingId: 'string', sourceId: 'string', rootNodeId: 'string' }),
371
483
  type({ type: '"dataMapping.delete"', mappingId: 'string' }),
@@ -421,6 +533,67 @@ export const templateOpSchema = type.or(
421
533
  operator: 'string',
422
534
  value: docScalar,
423
535
  }),
536
+ /**
537
+ * Operator-discriminated, so the payload cannot disagree with the operator: `eq` takes a value,
538
+ * `in` a NON-EMPTY list, `range` at least one bound and no value, `isNull` a boolean. Each arm
539
+ * declares the other operators' members `never`, which is what refuses a mixed record carrying a
540
+ * stale `value` beside new `values`.
541
+ */
542
+ type({
543
+ type: '"mappingFilter.setTyped"',
544
+ filterId: 'string',
545
+ nodeId: 'string',
546
+ fieldId: 'string',
547
+ operator: '"eq"',
548
+ value: docScalar,
549
+ "values?": 'never',
550
+ "from?": 'never',
551
+ "to?": 'never',
552
+ }),
553
+ type({
554
+ type: '"mappingFilter.setTyped"',
555
+ filterId: 'string',
556
+ nodeId: 'string',
557
+ fieldId: 'string',
558
+ operator: '"in"',
559
+ values: '(string | number | boolean)[] > 0',
560
+ "value?": 'never',
561
+ "from?": 'never',
562
+ "to?": 'never',
563
+ }),
564
+ type({
565
+ type: '"mappingFilter.setTyped"',
566
+ filterId: 'string',
567
+ nodeId: 'string',
568
+ fieldId: 'string',
569
+ operator: '"range"',
570
+ from: docScalar,
571
+ "to?": docScalar,
572
+ "value?": 'never',
573
+ "values?": 'never',
574
+ }),
575
+ type({
576
+ type: '"mappingFilter.setTyped"',
577
+ filterId: 'string',
578
+ nodeId: 'string',
579
+ fieldId: 'string',
580
+ operator: '"range"',
581
+ "from?": 'never',
582
+ to: docScalar,
583
+ "value?": 'never',
584
+ "values?": 'never',
585
+ }),
586
+ type({
587
+ type: '"mappingFilter.setTyped"',
588
+ filterId: 'string',
589
+ nodeId: 'string',
590
+ fieldId: 'string',
591
+ operator: '"isNull"',
592
+ value: 'boolean',
593
+ "values?": 'never',
594
+ "from?": 'never',
595
+ "to?": 'never',
596
+ }),
424
597
  type({ type: '"mappingFilter.delete"', filterId: 'string' }),
425
598
  type({ type: '"visibilityRule.set"', ruleId: 'string', questionId: 'string', condition: ruleConditionSchema }),
426
599
  type({ type: '"visibilityRule.delete"', ruleId: 'string' }),
@@ -461,12 +634,23 @@ type JsonSchemaLike = {
461
634
  properties?: { type?: { const?: unknown } }
462
635
  }
463
636
 
637
+ /**
638
+ * The distinct op names a schema validates.
639
+ *
640
+ * **Deduplicated**, because one op type may legitimately span several union arms: an
641
+ * operator-discriminated payload (`mappingFilter.setTyped`) is one op with five mutually exclusive
642
+ * shapes, which is exactly how the payload is prevented from disagreeing with its operator. The parity
643
+ * property is "the schema covers exactly these op TYPES", so counting arms instead of types would make
644
+ * a correctly-modelled discriminated op look like a vocabulary mismatch.
645
+ */
464
646
  const opTypeNames = (schema: Type): string[] => {
465
647
  const json = schema.toJsonSchema() as unknown as JsonSchemaLike
466
648
  const members = json.anyOf ?? [json]
467
- return members
649
+ const names = members
468
650
  .map((member) => member.properties?.type?.const)
469
651
  .filter((value): value is string => typeof value === 'string')
652
+
653
+ return [...new Set(names)]
470
654
  }
471
655
 
472
656
  /**
@@ -642,6 +826,12 @@ const TEMPLATE_DOCUMENT_DEFAULT_PATHS: readonly string[] = [
642
826
  */
643
827
  const BINDING_OPTION_DEFAULT_PATH = /^mappingBindingsById\.[^.]+\.(cardinality|onMissing|onMany)$/
644
828
 
829
+ /**
830
+ * The closed operator set, re-exported through the schema module so a consumer validating a filter and a
831
+ * consumer authoring one read the same list. Declared once in `templateDocument.ts`.
832
+ */
833
+ export const SCHEMA_MAPPING_FILTER_OPERATORS: readonly string[] = MAPPING_FILTER_OPERATORS
834
+
645
835
  export const templateDocumentIsDefault: IsDefault = (path, value) => {
646
836
  const option = BINDING_OPTION_DEFAULT_PATH.exec(path)?.[1]
647
837
 
@@ -133,6 +133,22 @@ export type QuestionGridPresentation = {
133
133
  rowEditor?: QuestionGridRowEditor
134
134
  /** OQ-V2-25: authored defaults; per-user widths are preference state outside both documents. */
135
135
  defaultColumnWidthsByQuestionId?: Record<QuestionId, number>
136
+ /**
137
+ * Which of this grid's columns offer a filter control, in authored order (M-054).
138
+ *
139
+ * Legacy stores `filter_ui.questions[]` as an array of objects; DOC-LAW-1 forbids that, and the
140
+ * per-entry flags it carried (`is_multi`, the date-interval bounds) are the *control's* configuration
141
+ * rather than the grid's, so they belong on the column question. What the grid owns is the
142
+ * selection and its order — a primitive id array, maintained one member at a time by
143
+ * `gridColumn.setFilter` so two authors adding different filters concurrently both survive.
144
+ */
145
+ filterQuestionIds?: QuestionId[]
146
+ /**
147
+ * The grid-owned actions, in authored order (M-055) — **ids only, never bodies**. The action
148
+ * records live in `actionsById`; duplicating them here would give one action two homes that could
149
+ * disagree, which is the reason the field map routes grid actions into the root collection.
150
+ */
151
+ actionIds?: ActionId[]
136
152
  [key: string]: unknown
137
153
  }
138
154
 
@@ -165,9 +181,92 @@ export type QnrGridRow = {
165
181
  [key: string]: unknown
166
182
  }
167
183
 
168
- export type QnrTab = { label?: string; [key: string]: unknown }
184
+ /** A tab's positional grid: one placement per question it displays, keyed rather than positional. */
185
+ export type QnrTabLayout = {
186
+ placementsByQuestionId?: Record<QuestionId, LayoutPlacement>
187
+ [key: string]: unknown
188
+ }
189
+
190
+ /**
191
+ * A header tab (M-051).
192
+ *
193
+ * `layout` is the typed successor to legacy `tab_editor.rows[].columns{}`, which is an array of rows
194
+ * each holding an object of columns. DOC-LAW-1 rules that out for the reason it exists: two authors
195
+ * moving different questions produce two whole-array patches, and the second silently discards the
196
+ * first. Keyed placements make those two edits touch two keys instead.
197
+ *
198
+ * The index signature stays: a tab's authored bag is still open (`dependent_question_ids` and friends
199
+ * arrive from the importer), and narrowing it would make an already-stored tab unreadable.
200
+ */
201
+ export type QnrTab = { label?: string; layout?: QnrTabLayout; [key: string]: unknown }
202
+
203
+ /**
204
+ * The **compatibility** action record: `kind` is an arbitrary optional string and the bag is open.
205
+ *
206
+ * Deliberately left broad. It is released, imported documents carry unknown kinds and accidental UI
207
+ * buffers, and narrowing it would make those unreadable — ADR-0008 DEC-006. The typed vocabulary below
208
+ * is additive and closed; a record is "known" only when its `kind` is one of `KNOWN_ACTION_KINDS`, and
209
+ * everything else keeps replaying exactly as before.
210
+ */
169
211
  export type QnrAction = { kind?: string; [key: string]: unknown }
170
212
 
213
+ /** The two action kinds the typed path authors (M-052/M-055). Anything else is legacy-readable only. */
214
+ export const KNOWN_ACTION_KINDS = ['topLevelAction', 'gridAction'] as const
215
+ export type KnownActionKind = (typeof KNOWN_ACTION_KINDS)[number]
216
+
217
+ /** A grid action's effect. Absent is a valid incomplete draft; publication refuses it. */
218
+ export const ACTION_TYPES = ['COPY', 'UPDATE'] as const
219
+ export type ActionType = (typeof ACTION_TYPES)[number]
220
+
221
+ export const isKnownActionKind = (kind: unknown): kind is KnownActionKind =>
222
+ typeof kind === 'string' && (KNOWN_ACTION_KINDS as readonly string[]).includes(kind)
223
+
224
+ /**
225
+ * What a top-level action does: for one composite/grid question, run an authored sequence of that
226
+ * grid's existing actions (M-052).
227
+ *
228
+ * **Not a recursive action tree.** The legacy shape reads like one (`actions:[{id, question_id,
229
+ * actions[]}]`), but the inner ids are grid actions that already exist in `actionsById`, so the v2
230
+ * shape is a map from grid question id to an ordered id array. There is deliberately no
231
+ * `childActionOrder` and no `questionId` member on an action.
232
+ */
233
+ export type KnownTopLevelAction = {
234
+ kind: 'topLevelAction'
235
+ label?: string
236
+ actionIdsByGridQuestionId?: Record<QuestionId, ActionId[]>
237
+ }
238
+
239
+ /**
240
+ * One metadata entry of a grid action: which values it copies or updates between.
241
+ *
242
+ * `{ all: true }` is the canonical all-to-all marker and exists because DOC-LAW-2 would otherwise
243
+ * erase the fact: legacy encodes all-to-all as `from: null, to: null`, and a document may carry
244
+ * neither null nor an empty object, so "selected, unbounded" and "not selected at all" would become
245
+ * the same absence. It is exclusive with `from`/`to`, and a bare `{}` is invalid for the same reason.
246
+ */
247
+ /**
248
+ * Every arm excludes the others' members with `?: never`, so the union is closed at COMPILE time and
249
+ * not only in the reducer. Without the exclusions `{all: true, from: 'a'}` structurally satisfies the
250
+ * from-only arm — TypeScript admits extra properties on a non-fresh object — and the exclusivity rule
251
+ * would exist in three places (reducer, schema) but not in the type consumers actually program against.
252
+ */
253
+ export type ActionMetadata =
254
+ | { from: DocScalar; to: DocScalar; all?: never }
255
+ | { from: DocScalar; to?: never; all?: never }
256
+ | { from?: never; to: DocScalar; all?: never }
257
+ | { all: true; from?: never; to?: never }
258
+
259
+ /** A grid-owned action (M-055): its effect, and the per-column values it applies to. */
260
+ export type KnownGridAction = {
261
+ kind: 'gridAction'
262
+ label?: string
263
+ actionType?: ActionType
264
+ metadataByQuestionId?: Record<QuestionId, ActionMetadata>
265
+ }
266
+
267
+ /** The closed typed vocabulary. A stored `QnrAction` is one of these only when its `kind` says so. */
268
+ export type KnownAction = KnownTopLevelAction | KnownGridAction
269
+
171
270
  /**
172
271
  * A typed conditional (OQ-V2-17/architecture §2.2(4)): question visibility/highlight
173
272
  * depends on another question's answer. Legacy `dependent_question`+`dependent_questions`
@@ -345,10 +444,47 @@ export const bindingIsMultiValued = (binding: MappingBinding): boolean =>
345
444
  resolveBindingOptions(binding).cardinality.endsWith('*')
346
445
 
347
446
  /** Carries no `nodeId` back-pointer: the node already lists it (§2.2a). */
447
+ /** The operators the typed path authors and the compiler branches on (engine contract ENG-MD-005). */
448
+ export const MAPPING_FILTER_OPERATORS = ['eq', 'in', 'range', 'isNull'] as const
449
+ export type MappingFilterOperator = (typeof MAPPING_FILTER_OPERATORS)[number]
450
+
451
+ export const isKnownMappingFilterOperator = (operator: unknown): operator is MappingFilterOperator =>
452
+ typeof operator === 'string' && (MAPPING_FILTER_OPERATORS as readonly string[]).includes(operator)
453
+
454
+ /**
455
+ * The payload each known operator carries — one member set per operator, nothing shared.
456
+ *
457
+ * `range` takes at least one bound because a range with neither is not a filter; `in` takes a
458
+ * non-empty list for the same reason. Both are enforced by the schema rather than left to the reducer,
459
+ * so an unusable filter cannot reach a compiled artifact.
460
+ */
461
+ export type MappingFilterPayload =
462
+ | { operator: 'eq'; value: DocScalar }
463
+ | { operator: 'in'; values: DocScalar[] }
464
+ | { operator: 'range'; from: DocScalar; to?: DocScalar }
465
+ | { operator: 'range'; to: DocScalar }
466
+ | { operator: 'isNull'; value: boolean }
467
+
468
+ /**
469
+ * A node filter. Carries no `nodeId` back-pointer: the node already lists it (§2.2a).
470
+ *
471
+ * **`operator` stays a loose `string`, and that is deliberate.** It is released, and stored documents
472
+ * carry operators outside the closed set (`contains` among them) that must remain readable and
473
+ * replayable — ADR-0008 DEC-006. The closed vocabulary arrives as `MAPPING_FILTER_OPERATORS` plus the
474
+ * additive `mappingFilter.setTyped`, which is the only path that can write a payload; publication is
475
+ * where an unknown operator becomes a refusal.
476
+ *
477
+ * `values`/`from`/`to` are additive members for the `in` and `range` payloads. A filter carries only
478
+ * the members of its own operator: `setTyped` rewrites the record rather than patching it, so
479
+ * switching operator cannot leave a stale `value` behind.
480
+ */
348
481
  export type MappingFilter = {
349
482
  fieldId: string
350
483
  operator: string
351
484
  value?: DocScalar
485
+ values?: DocScalar[]
486
+ from?: DocScalar
487
+ to?: DocScalar
352
488
  }
353
489
 
354
490
  /**
@@ -430,6 +566,36 @@ export type QnrQuestionBundle = {
430
566
  */
431
567
  tabOrder?: TabId[]
432
568
  actionsById?: Record<ActionId, QnrAction>
569
+ /**
570
+ * The mapping-graph fragment its questions are bound through — the same four normalized
571
+ * collections the document root carries, scoped to this root question's subtree.
572
+ *
573
+ * **Why a bundle carries mapping at all.** Mapping is one root-level graph, not per-question state
574
+ * (OQ-V2-28 ✅, §2.2a), so a bundle that copied only questions would lose every binding the moment
575
+ * it was picked: the pick splices this fragment into the family document's root graph precisely so
576
+ * a picked question does not arrive unmapped. The pre-DDL guardrails state it as part of what the
577
+ * column stores — "plus its mapping-graph fragment (the nodes, bindings, and filters its questions
578
+ * are bound through)".
579
+ *
580
+ * The same records and the same laws as the document, deliberately: `dataMappingsById` keyed by
581
+ * mapping id with a primitive `bindingOrder`, nodes keyed by node id with a primitive `filterOrder`,
582
+ * every default omitted. **No new document shape** — a pick replays ordinary authoring ops under
583
+ * fresh ids (`mappingNode.create`, then filters via `mappingFilter.set` or the typed
584
+ * `mappingFilter.setTyped`, then `mappingBinding.create`, and `dataMapping.create` last so the
585
+ * reducer adopts its bindings in the authored order), so anything expressible in a document is
586
+ * expressible in a bundle and nothing else is.
587
+ *
588
+ * All four are optional and independently so: a bundle for an unmapped question carries none of
589
+ * them, and a fragment mid-authoring may carry nodes with no bindings yet. Completeness is a
590
+ * publication question (G-25), never a condition of storing or picking one.
591
+ *
592
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-13-23-25-architecture-qnr-v2-db-design-pre-ddl-guardrails.md:187
593
+ * @see asma-modules/_docs/editor/qnrs/cross/2026-07-13-23-25-architecture-qnr-v2-db-design-pre-ddl-guardrails.md:587 — OQ-V2-28
594
+ */
595
+ dataMappingsById?: Record<MappingId, QnrDataMapping>
596
+ mappingNodesById?: Record<NodeId, MappingNode>
597
+ mappingBindingsById?: Record<BindingId, MappingBinding>
598
+ mappingFiltersById?: Record<FilterId, MappingFilter>
433
599
  }
434
600
 
435
601
  /**