asma-core-helpers 0.32.0 → 0.34.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 (48) hide show
  1. package/lib/collaboration/applyOperation.d.ts +5 -13
  2. package/lib/collaboration/applyOperation.d.ts.map +1 -1
  3. package/lib/collaboration/applyOperation.js +450 -20
  4. package/lib/collaboration/applyOperation.js.map +1 -1
  5. package/lib/collaboration/operations.d.ts +113 -1
  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 +54 -0
  10. package/lib/collaboration/schemas.d.ts.map +1 -1
  11. package/lib/collaboration/schemas.js +74 -1
  12. package/lib/collaboration/schemas.js.map +1 -1
  13. package/lib/collaboration/templateDocument.d.ts +194 -0
  14. package/lib/collaboration/templateDocument.d.ts.map +1 -1
  15. package/lib/collaboration/templateDocument.js +104 -0
  16. package/lib/collaboration/templateDocument.js.map +1 -1
  17. package/lib/collaboration/testHelpers/documentGenerator.d.ts +24 -0
  18. package/lib/collaboration/testHelpers/documentGenerator.d.ts.map +1 -1
  19. package/lib/collaboration/testHelpers/documentGenerator.js +180 -2
  20. package/lib/collaboration/testHelpers/documentGenerator.js.map +1 -1
  21. package/lib/collaboration/typeContracts.d.ts +73 -1
  22. package/lib/collaboration/typeContracts.d.ts.map +1 -1
  23. package/lib/g-definitions.d.ts +17 -0
  24. package/lib/g-definitions.d.ts.map +1 -1
  25. package/lib/g-definitions.js +13 -0
  26. package/lib/g-definitions.js.map +1 -1
  27. package/lib/helpers/sectionPath.helpers.d.ts +64 -0
  28. package/lib/helpers/sectionPath.helpers.d.ts.map +1 -0
  29. package/lib/helpers/sectionPath.helpers.js +68 -0
  30. package/lib/helpers/sectionPath.helpers.js.map +1 -0
  31. package/lib/index.d.ts +1 -0
  32. package/lib/index.d.ts.map +1 -1
  33. package/lib/index.js +1 -0
  34. package/lib/index.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/collaboration/applyOperation.ts +517 -17
  37. package/src/collaboration/operations.ts +95 -0
  38. package/src/collaboration/property.test.ts +49 -0
  39. package/src/collaboration/schemas.ts +82 -0
  40. package/src/collaboration/templateDocument.ts +238 -1
  41. package/src/collaboration/testHelpers/documentGenerator.ts +201 -2
  42. package/src/collaboration/typeContracts.ts +106 -1
  43. package/src/collaboration/typedAuthoring.test.ts +1091 -0
  44. package/src/collaboration/typedAuthoringHardening.test.ts +344 -1
  45. package/src/g-definitions.ts +29 -0
  46. package/src/helpers/sectionPath.helpers.test.ts +159 -0
  47. package/src/helpers/sectionPath.helpers.ts +129 -0
  48. package/src/index.ts +1 -0
@@ -3,6 +3,7 @@ import type {
3
3
  ActionMetadata,
4
4
  ActionType,
5
5
  AltId,
6
+ AlternativeChartLegendSelection,
6
7
  BindingCardinality,
7
8
  BindingId,
8
9
  BindingOnMany,
@@ -12,6 +13,7 @@ import type {
12
13
  FilterId,
13
14
  HighlightRuleId,
14
15
  LayoutPlacement,
16
+ LegacyBindingOverride,
15
17
  MappingFilterPayload,
16
18
  MappingId,
17
19
  NarrativeRuleId,
@@ -123,6 +125,61 @@ export type TemplateOp =
123
125
  | { type: 'alternative.updateField'; questionId: QuestionId; alternativeId: AltId; field: string; value: OpValue }
124
126
  | { type: 'alternative.move'; questionId: QuestionId; alternativeId: AltId; toIndex: number }
125
127
  | { type: 'alternative.delete'; questionId: QuestionId; alternativeId: AltId }
128
+ /**
129
+ * Writes an Expression alternative's formula text and its ordered target list as one value (AC-9).
130
+ *
131
+ * One operation rather than two `alternative.updateField` writes: the formula and the targets it
132
+ * cites are one authored decision, and a client that landed the text but lost the list would leave a
133
+ * formula referencing questions the document does not record as targets.
134
+ *
135
+ * On an `ExpressionQuestion` the formula genuinely lives in the alternative's `value` — the usual
136
+ * "an alternative's value is read-only code" rule does not hold for this type, because that is where
137
+ * legacy's formula editor writes.
138
+ *
139
+ * Deliberately draft-permissive: the text and the list need not agree while editing, so a
140
+ * half-typed formula saves. Publication and preview own the mismatch finding; the reducer must not
141
+ * erase or repair a partial formula the author is still writing.
142
+ */
143
+ | {
144
+ type: 'alternative.setExpressionFormula'
145
+ questionId: QuestionId
146
+ alternativeId: AltId
147
+ value: string
148
+ expressionTargets: QuestionId[]
149
+ }
150
+ /**
151
+ * Creates one radar Chart legend, inserting its keyed record and its order entry atomically (AC-9).
152
+ *
153
+ * Atomic because a legend present in `legendsById` but absent from `legendsOrder` is unreachable
154
+ * state that still moves `document_hash`, and the reverse dangles. `atIndex` exists so a bundle pick
155
+ * can restore authored order losslessly; the app appends, because legacy exposes no reorder control.
156
+ */
157
+ | { type: 'chartLegend.create'; questionId: QuestionId; legendId: string; label: string; atIndex?: number }
158
+ /**
159
+ * Removes one Chart legend, its order entry, and every assignment on that Chart's own alternatives.
160
+ *
161
+ * The cascade matches the legacy effect — a legend that disappears stops appearing on alternatives —
162
+ * and stops at ownership: an identically-named legend id on another question is left alone, which
163
+ * matters because imported ids can collide across questions.
164
+ */
165
+ | { type: 'chartLegend.delete'; questionId: QuestionId; legendId: string }
166
+ /**
167
+ * Binds one Chart alternative to one legend and one expression-enabled target, or clears it (AC-9).
168
+ *
169
+ * The payload carries no `label`: the reducer copies it from the owning legend. Accepting one would
170
+ * let a client give a single legend id two labels, i.e. two hashes for one authored state.
171
+ *
172
+ * A whole object rather than three field writes, for the same reason `tab.setLayout` is atomic —
173
+ * separate id/target/label writes can interleave into a hybrid no author ever selected. `null`
174
+ * clears whatever is stored, including an imported dangling or non-radar assignment, so the
175
+ * operation stays usable for repair.
176
+ */
177
+ | {
178
+ type: 'alternative.setChartLegend'
179
+ questionId: QuestionId
180
+ alternativeId: AltId
181
+ chartLegend: AlternativeChartLegendSelection | null
182
+ }
126
183
  | { type: 'tab.create'; tabId: TabId; label?: string; atIndex?: number }
127
184
  | { type: 'tab.updateField'; tabId: TabId; field: string; value: OpValue }
128
185
  | { type: 'tab.move'; tabId: TabId; toIndex: number }
@@ -136,6 +193,25 @@ export type TemplateOp =
136
193
  * survive; concurrent moves of the *same* question are last-writer-wins on a whole placement.
137
194
  */
138
195
  | { type: 'tab.setLayout'; tabId: TabId; questionId: QuestionId; placement: LayoutPlacement | null }
196
+ /**
197
+ * Adds, moves or removes one question in a tab's authored membership (freeze §3a).
198
+ *
199
+ * Member-wise for the reason `gridColumn.setFilter` is: `tab.updateField` would write the whole
200
+ * `questionIds` array, so two authors adding different questions would produce two whole-array
201
+ * patches and the second would silently discard the first. `include:false` also removes the id from
202
+ * `rowCountQuestionIds` and from `layout.placementsByQuestionId`, because a count or a placement for
203
+ * a non-member is a reference to something the tab no longer shows.
204
+ */
205
+ | { type: 'tab.setQuestion'; tabId: TabId; questionId: QuestionId; include: boolean; atIndex?: number }
206
+ /**
207
+ * Adds, moves or removes one `QuestionGrid` in the subset whose rows contribute to a tab's count.
208
+ *
209
+ * `include:true` requires an existing `QuestionGrid` already in that tab's `questionIds` — a count
210
+ * over a non-member, or over a question with no rows, is not a state an author can mean.
211
+ * `include:false` requires neither, so an imported document whose count names a missing or
212
+ * wrong-typed question stays repairable.
213
+ */
214
+ | { type: 'tab.setRowCountQuestion'; tabId: TabId; questionId: QuestionId; include: boolean; atIndex?: number }
139
215
  | { type: 'tab.delete'; tabId: TabId }
140
216
  // Actions are a set, not an ordered collection (architecture §2.1: `actionsById`, no order array).
141
217
  | { type: 'action.create'; actionId: ActionId; kind?: string }
@@ -235,6 +311,18 @@ export type TemplateOp =
235
311
  }
236
312
  }
237
313
  | { type: 'mappingBinding.delete'; bindingId: BindingId }
314
+ /**
315
+ * Sets or clears one binding's legacy mapping exception (OQ-V2-40, freeze §1a).
316
+ *
317
+ * Accepts only the closed {@link LegacyBindingOverride} or `null`, while the stored member stays
318
+ * `unknown` on read: new producers may write nothing but canonical, and historical arbitrary values
319
+ * keep replaying byte-for-byte through the untouched `create`/`update` arms.
320
+ *
321
+ * Member-only by construction — it cannot reach `nodeId`, `fieldId`, `target`, the behaviour options
322
+ * or any mapping's `bindingOrder`, so repairing an exception can never disturb the graph. `null`
323
+ * removes the member and leaves no empty object behind.
324
+ */
325
+ | { type: 'mappingBinding.setLegacyOverride'; bindingId: BindingId; legacyOverride: LegacyBindingOverride | null }
238
326
  | {
239
327
  type: 'mappingFilter.set'
240
328
  filterId: FilterId
@@ -298,10 +386,16 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
298
386
  'alternative.updateField': true,
299
387
  'alternative.move': true,
300
388
  'alternative.delete': true,
389
+ 'alternative.setExpressionFormula': true,
390
+ 'alternative.setChartLegend': true,
391
+ 'chartLegend.create': true,
392
+ 'chartLegend.delete': true,
301
393
  'tab.create': true,
302
394
  'tab.updateField': true,
303
395
  'tab.move': true,
304
396
  'tab.setLayout': true,
397
+ 'tab.setQuestion': true,
398
+ 'tab.setRowCountQuestion': true,
305
399
  'tab.delete': true,
306
400
  'action.create': true,
307
401
  'action.updateField': true,
@@ -317,6 +411,7 @@ const OP_TYPE_COVERAGE: Record<TemplateOpType, true> = {
317
411
  'mappingBinding.create': true,
318
412
  'mappingBinding.update': true,
319
413
  'mappingBinding.delete': true,
414
+ 'mappingBinding.setLegacyOverride': true,
320
415
  'mappingFilter.set': true,
321
416
  'mappingFilter.setTyped': true,
322
417
  'mappingFilter.delete': true,
@@ -111,6 +111,55 @@ describe('DOC-LAW invariants under random op sequences', () => {
111
111
  }
112
112
  })
113
113
 
114
+ /**
115
+ * The seven operations added by the combined post-v0.31 repair must be *exercised*, not merely
116
+ * listed in the generator.
117
+ *
118
+ * A generated-name check alone is the mutation this guards against: point a generator case at an id
119
+ * pool that is always empty and every application refuses, so the reducer's success path is never run
120
+ * and a broken one still passes a green property suite. Requiring at least one accepted application of
121
+ * each name — and at least one refusal, so the guards are reached too — is what makes the property run
122
+ * evidence rather than decoration.
123
+ */
124
+ describe('the combined repair operations are reached by the property run', () => {
125
+ const NEW_OP_TYPES = [
126
+ 'tab.setQuestion',
127
+ 'tab.setRowCountQuestion',
128
+ 'mappingBinding.setLegacyOverride',
129
+ 'alternative.setExpressionFormula',
130
+ 'alternative.setChartLegend',
131
+ 'chartLegend.create',
132
+ 'chartLegend.delete',
133
+ ] as const
134
+
135
+ it('applies each new operation successfully and refuses each at least once', () => {
136
+ const accepted = new Map<string, number>()
137
+ const refused = new Map<string, number>()
138
+
139
+ // More seeds than the invariant suite uses: each op needs its own preconditions to line up
140
+ // (a radar Chart, a flagged target, an existing legend), which no single short run reaches.
141
+ for (const seed of [4, 7, 13, 99, 101, 202, 303, 404]) {
142
+ const { generated } = runSequence(seed, 400)
143
+ generated.ops.forEach((op, index) => {
144
+ if (!(NEW_OP_TYPES as readonly string[]).includes(op.type)) return
145
+ const bucket = generated.outcomes[index] === true ? accepted : refused
146
+ bucket.set(op.type, (bucket.get(op.type) ?? 0) + 1)
147
+ })
148
+ }
149
+
150
+ assert.deepEqual(
151
+ NEW_OP_TYPES.filter((type) => (accepted.get(type) ?? 0) === 0),
152
+ [],
153
+ `never applied successfully: ${JSON.stringify([...accepted])}`,
154
+ )
155
+ assert.deepEqual(
156
+ NEW_OP_TYPES.filter((type) => (refused.get(type) ?? 0) === 0),
157
+ [],
158
+ `never refused: ${JSON.stringify([...refused])}`,
159
+ )
160
+ })
161
+ })
162
+
114
163
  describe('canonicalization stability', () => {
115
164
  const labelDoc = (label: string) => ({
116
165
  documentId: 'tpl-nfc',
@@ -129,6 +129,44 @@ const layoutPlacementSchema = type({
129
129
  keepCellSize: 'boolean?',
130
130
  })
131
131
 
132
+ /**
133
+ * The closed legacy mapping exception, validated only where a NEW producer writes one.
134
+ *
135
+ * `'+': 'reject'` is load-bearing: ArkType admits undeclared keys by default, so without it
136
+ * `{planId: 'x', actorType: 'y'}` would validate and the forbidden member would reach the reducer.
137
+ *
138
+ * `string > 0` on each member refuses the empty string, which DOC-LAW-2 treats as a second encoding of
139
+ * absent.
140
+ *
141
+ * Three arms mirroring `LegacyBindingOverride`, each making a different member required, rather than one
142
+ * arm plus a `narrow` predicate. A custom predicate cannot be represented in JSON Schema, so
143
+ * `toJsonSchema()` — which the package parity test runs over the whole op union — throws on it. The
144
+ * union expresses the same at-least-one rule declaratively and stays convertible.
145
+ *
146
+ * The stored document member stays `unknown` — see `mappingBindingSchema`, deliberately unchanged.
147
+ */
148
+ const legacyBindingOverrideSchema = type({
149
+ planId: 'string > 0',
150
+ 'kind?': 'string > 0',
151
+ 'mappingRule?': 'string > 0',
152
+ '+': 'reject',
153
+ })
154
+ .or({ 'planId?': 'string > 0', kind: 'string > 0', 'mappingRule?': 'string > 0', '+': 'reject' })
155
+ .or({ 'planId?': 'string > 0', 'kind?': 'string > 0', mappingRule: 'string > 0', '+': 'reject' })
156
+
157
+ /**
158
+ * A Chart legend selection: the legend and its target, and deliberately no `label`.
159
+ *
160
+ * `'+': 'reject'` is what makes "no label" enforceable rather than advisory — the reducer derives the
161
+ * label from the owning legend, and a client-supplied one would let a single legend id carry two
162
+ * labels, i.e. two document hashes for one authored state.
163
+ */
164
+ const alternativeChartLegendSelectionSchema = type({
165
+ id: 'string > 0',
166
+ questionIdMap: 'string > 0',
167
+ '+': 'reject',
168
+ })
169
+
132
170
  const questionGridRowEditorSchema = type({
133
171
  "layoutByQuestionId?": recordOf(layoutPlacementSchema),
134
172
  ...({ '[string]': 'unknown' } as const),
@@ -197,6 +235,10 @@ const qnrTabLayoutSchema = type({
197
235
  const qnrTabSchema = type({
198
236
  label: 'string?',
199
237
  "layout?": qnrTabLayoutSchema,
238
+ // Typed as primitive id arrays rather than left to the open index: an accidental `unknown` would
239
+ // admit an array of objects, which is the DOC-LAW-1 shape these members exist to avoid.
240
+ questionIds: 'string[]?',
241
+ rowCountQuestionIds: 'string[]?',
200
242
  ...({ '[string]': 'unknown' } as const),
201
243
  })
202
244
 
@@ -421,6 +463,27 @@ export const templateOpSchema = type.or(
421
463
  }),
422
464
  type({ type: '"alternative.move"', questionId: 'string', alternativeId: 'string', toIndex: 'number' }),
423
465
  type({ type: '"alternative.delete"', questionId: 'string', alternativeId: 'string' }),
466
+ type({
467
+ type: '"alternative.setExpressionFormula"',
468
+ questionId: 'string',
469
+ alternativeId: 'string',
470
+ value: 'string',
471
+ expressionTargets: 'string[]',
472
+ }),
473
+ type({
474
+ type: '"alternative.setChartLegend"',
475
+ questionId: 'string',
476
+ alternativeId: 'string',
477
+ chartLegend: type.or(alternativeChartLegendSelectionSchema, type('null')),
478
+ }),
479
+ type({
480
+ type: '"chartLegend.create"',
481
+ questionId: 'string',
482
+ legendId: 'string',
483
+ label: 'string',
484
+ atIndex: 'number?',
485
+ }),
486
+ type({ type: '"chartLegend.delete"', questionId: 'string', legendId: 'string' }),
424
487
  type({ type: '"tab.create"', tabId: 'string', label: 'string?', atIndex: 'number?' }),
425
488
  type({ type: '"tab.updateField"', tabId: 'string', field: 'string', value: opValue }),
426
489
  type({ type: '"tab.move"', tabId: 'string', toIndex: 'number' }),
@@ -430,6 +493,20 @@ export const templateOpSchema = type.or(
430
493
  questionId: 'string',
431
494
  placement: type.or(layoutPlacementSchema, type('null')),
432
495
  }),
496
+ type({
497
+ type: '"tab.setQuestion"',
498
+ tabId: 'string',
499
+ questionId: 'string',
500
+ include: 'boolean',
501
+ atIndex: 'number?',
502
+ }),
503
+ type({
504
+ type: '"tab.setRowCountQuestion"',
505
+ tabId: 'string',
506
+ questionId: 'string',
507
+ include: 'boolean',
508
+ atIndex: 'number?',
509
+ }),
433
510
  type({ type: '"tab.delete"', tabId: 'string' }),
434
511
  type({ type: '"action.create"', actionId: 'string', kind: 'string?' }),
435
512
  type({ type: '"action.updateField"', actionId: 'string', field: 'string', value: opValue }),
@@ -524,6 +601,11 @@ export const templateOpSchema = type.or(
524
601
  'onMany?': bindingOnManySchema.or(type.null),
525
602
  }),
526
603
  }),
604
+ type({
605
+ type: '"mappingBinding.setLegacyOverride"',
606
+ bindingId: 'string',
607
+ legacyOverride: type.or(legacyBindingOverrideSchema, type('null')),
608
+ }),
527
609
  type({ type: '"mappingBinding.delete"', bindingId: 'string' }),
528
610
  type({
529
611
  type: '"mappingFilter.set"',
@@ -173,6 +173,79 @@ export type QnrQuestion = {
173
173
 
174
174
  export type QnrAlternative = { label?: string; value?: DocScalar; [key: string]: unknown }
175
175
 
176
+ /**
177
+ * One legend of a radar `Chart` question (AC-9).
178
+ *
179
+ * A keyed record plus an order array on the question rather than an array of objects, for the DOC-LAW-1
180
+ * reason: two authors adding legends concurrently otherwise produce two whole-array writes and the
181
+ * second discards the first.
182
+ */
183
+ export type ChartLegend = { id: string; label: string }
184
+
185
+ /**
186
+ * A Chart alternative's stored binding of one expression-enabled target question to one legend.
187
+ *
188
+ * `label` is carried even though it duplicates `chart.legendsById[id].label`, and the reducer — never
189
+ * the client — derives it. A client-supplied label would let one legend id carry two labels across two
190
+ * alternatives, which is two `document_hash` values for one authored state.
191
+ */
192
+ export type AlternativeChartLegend = { id: string; questionIdMap: QuestionId; label: string }
193
+
194
+ /**
195
+ * What an author actually chooses: the legend and the target. Deliberately label-free.
196
+ *
197
+ * Separate from {@link AlternativeChartLegend} so the operation payload cannot carry a label at all —
198
+ * a type that merely documented "label is ignored here" would still admit one, and the reducer would be
199
+ * trusting a client value it is supposed to derive.
200
+ *
201
+ * `label?: never` is what makes that a COMPILE-time refusal rather than only a runtime one, the same
202
+ * device the `ActionMetadata` arms use: object assignability is structural and excess properties are
203
+ * only rejected on a fresh literal, so `{id, questionIdMap, label}` would otherwise satisfy this type
204
+ * and the exclusion would exist in the schema alone.
205
+ */
206
+ export type AlternativeChartLegendSelection = { id: string; questionIdMap: QuestionId; label?: never }
207
+
208
+ /** UTF-8 bytes of a complete id as lowercase hex. `TextEncoder` is global in browsers and in Node. */
209
+ const idToLowercaseHex = (id: string): string =>
210
+ Array.from(new TextEncoder().encode(id))
211
+ .map((byte) => byte.toString(16).padStart(2, '0'))
212
+ .join('')
213
+
214
+ /**
215
+ * The canonical `<target_...>` token naming a question inside an Expression formula.
216
+ *
217
+ * **Injective, unlike legacy.** Legacy tokenized the *last eight characters* of an id, so two questions
218
+ * whose ids share a suffix produced the same token and a formula silently referenced the wrong one —
219
+ * which is guaranteed rather than unlucky for a bundle pick, where fresh ids are minted from one map.
220
+ * Encoding the complete id as UTF-8 hex makes distinct ids distinct tokens, including ids differing
221
+ * only before their last eight characters, and round-trips non-ASCII ids at the byte level.
222
+ *
223
+ * Hex rather than the raw id because the delimiters must stay unambiguous: an id containing `>` or `_`
224
+ * would otherwise terminate or split its own token.
225
+ */
226
+ export const makeExpressionTargetToken = (questionId: QuestionId): string =>
227
+ `<target_${idToLowercaseHex(questionId)}>`
228
+
229
+ /** The canonical `<exp_...>` token naming an alternative inside `question.expression.base`. */
230
+ export const makeExpressionAlternativeToken = (alternativeId: AltId): string =>
231
+ `<exp_${idToLowercaseHex(alternativeId)}>`
232
+
233
+ /**
234
+ * Anchored recognizers for the canonical grammar.
235
+ *
236
+ * `(?:[0-9a-f]{2})+` requires at least one whole byte and rejects an odd-length body, so an empty
237
+ * token, a truncated byte, an uppercase or non-hex digit, a prefix/suffix claimant, and legacy's
238
+ * last-eight-character spelling are all non-canonical. Recognition only — shared deliberately exposes
239
+ * no decoder: reversing a token would invite callers to *interpret* formulas, which is BunJS import and
240
+ * publication work, not contract work.
241
+ */
242
+ const EXPRESSION_TARGET_TOKEN_PATTERN = /^<target_(?:[0-9a-f]{2})+>$/
243
+ const EXPRESSION_ALTERNATIVE_TOKEN_PATTERN = /^<exp_(?:[0-9a-f]{2})+>$/
244
+
245
+ export const isExpressionTargetToken = (value: string): boolean => EXPRESSION_TARGET_TOKEN_PATTERN.test(value)
246
+ export const isExpressionAlternativeToken = (value: string): boolean =>
247
+ EXPRESSION_ALTERNATIVE_TOKEN_PATTERN.test(value)
248
+
176
249
  /** An authored predefined grid row; cells are keyed by column question id. */
177
250
  export type QnrGridRow = {
178
251
  label?: string
@@ -198,7 +271,40 @@ export type QnrTabLayout = {
198
271
  * The index signature stays: a tab's authored bag is still open (`dependent_question_ids` and friends
199
272
  * arrive from the importer), and narrowing it would make an already-stored tab unreadable.
200
273
  */
201
- export type QnrTab = { label?: string; layout?: QnrTabLayout; [key: string]: unknown }
274
+ export type QnrTab = {
275
+ label?: string
276
+ layout?: QnrTabLayout
277
+ /**
278
+ * Authored tab membership: which questions this tab shows, in the author's order (M-050, freeze §3a).
279
+ *
280
+ * The legacy spelling is `dependent_question_ids`, and post-release importer scrutiny corrected the
281
+ * field inventory's reading of it: the legacy model and viewer use it as **membership**, not as a
282
+ * conditional visibility rule. Importing it as a rule would have made v2 *hide* a question legacy
283
+ * merely *listed*, which is why this is its own member and not a `VisibilityRule`.
284
+ *
285
+ * **Not derivable from `layout`.** A committed fixture carries a counted composite member with no
286
+ * positional placement, so membership is strictly wider than the placement key set. Deriving one
287
+ * from the other would silently drop that member.
288
+ *
289
+ * A primitive id array, so DOC-LAW-1 is satisfied by identity living in the values, and maintained
290
+ * one member at a time by `tab.setQuestion` — two authors adding different questions concurrently
291
+ * both survive, where a whole-array write would discard the first. Absent when the tab has no
292
+ * members; never stored as `[]`.
293
+ */
294
+ questionIds?: QuestionId[]
295
+ /**
296
+ * The `QuestionGrid` members whose visible row counts contribute to this tab's count (freeze §3a).
297
+ *
298
+ * Legacy spells it `count_question_rows`. The v2 name states the direction — "questions whose rows
299
+ * count" — rather than preserving the legacy grammatical ambiguity about what counts what.
300
+ *
301
+ * A strict subset of `questionIds` by rule rather than by type: `tab.setRowCountQuestion` admits
302
+ * only a `QuestionGrid` already in `questionIds`, while exclusion stays available with no live
303
+ * question at all so an imported dangling reference can be repaired.
304
+ */
305
+ rowCountQuestionIds?: QuestionId[]
306
+ [key: string]: unknown
307
+ }
202
308
 
203
309
  /**
204
310
  * The **compatibility** action record: `kind` is an arbitrary optional string and the bag is open.
@@ -425,9 +531,140 @@ export type MappingBinding = {
425
531
  onMissing?: BindingOnMissing
426
532
  /** Absent means `error`. */
427
533
  onMany?: BindingOnMany
534
+ /**
535
+ * The legacy mapping exception, deliberately typed `unknown` and NOT `LegacyBindingOverride`.
536
+ *
537
+ * Declared for discoverability only — the open index already admits it, so this narrows nothing.
538
+ * It stays `unknown` because the member is released and stored documents carry arbitrary values
539
+ * that must remain readable and replayable (ADR-0008 DEC-006). {@link parseLegacyBindingOverride}
540
+ * is the recognizer, and `mappingBinding.setLegacyOverride` is the only writer of a canonical value.
541
+ */
542
+ legacyOverride?: unknown
428
543
  [key: string]: unknown
429
544
  }
430
545
 
546
+ /**
547
+ * The per-binding legacy mapping exception (OQ-V2-40, freeze §1a).
548
+ *
549
+ * Stored only when graph/structure derivation differs from what legacy actually authored, so the
550
+ * observed authoring survives the port instead of being replaced by our derivation of it.
551
+ *
552
+ * **At least one member is mandatory at compile time**, which is what the three arms buy: a bare `{}`
553
+ * would be an exception that records nothing, and under DOC-LAW-2 it is also a second encoding of
554
+ * "absent". Each arm makes a different member required, so the union is exactly "one or more of the
555
+ * three" without admitting the empty record — a single optional-everything type could not say that.
556
+ *
557
+ * `mappingRule` translates to and from the observed `mapping_rule` only at the legacy import/projection
558
+ * boundary; no snake_case duplicate is stored here.
559
+ */
560
+ export type LegacyBindingOverride =
561
+ | { planId: string; kind?: string; mappingRule?: string }
562
+ | { planId?: string; kind: string; mappingRule?: string }
563
+ | { planId?: string; kind?: string; mappingRule: string }
564
+
565
+ /**
566
+ * Reading a stored `legacyOverride` has three outcomes, and collapsing any two of them loses
567
+ * information a caller acts on.
568
+ *
569
+ * `absent` is "no exception recorded", `known` is a canonical value safe to project, and `malformed` is
570
+ * a historical or hand-written value that must stay readable but must never be treated as canonical.
571
+ * A boolean guard would merge the last two, so BunJS publication could not tell "nothing to refuse"
572
+ * from "refuse this", and the bundle picker could not report it unrepresentable rather than dropping it.
573
+ */
574
+ export type LegacyBindingOverrideParseResult =
575
+ | { status: 'absent' }
576
+ | { status: 'known'; value: LegacyBindingOverride }
577
+ | { status: 'malformed' }
578
+
579
+ /** The three members a canonical override may carry. Anything else makes the value malformed. */
580
+ const LEGACY_OVERRIDE_KEYS = ['planId', 'kind', 'mappingRule'] as const
581
+
582
+ /**
583
+ * The one total reader over the released broad member.
584
+ *
585
+ * `MappingBinding.legacyOverride` stays `unknown` on read (ADR-0008 DEC-006): the member is released,
586
+ * stored documents carry arbitrary values, and narrowing the document type would make those unreadable.
587
+ * So recognition lives in a parser rather than in the type, and this is the only place that decides what
588
+ * canonical means — a caller spelling the check itself would be a second declaration free to drift.
589
+ *
590
+ * Refuses, as malformed rather than known: unknown keys, `null`, arrays, nested objects, empty strings,
591
+ * non-string scalars, the empty record, and every member outside the closed three (`actorType`,
592
+ * provider/profile, subject/entity/runtime ids, credentials).
593
+ */
594
+ export const parseLegacyBindingOverride = (value: unknown): LegacyBindingOverrideParseResult => {
595
+ if (value === undefined) return { status: 'absent' }
596
+
597
+ // `typeof null === 'object'`, and an array is an object too — both are malformed, not absent.
598
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return { status: 'malformed' }
599
+
600
+ const entries = Object.entries(value as Record<string, unknown>)
601
+ if (entries.length === 0) return { status: 'malformed' }
602
+
603
+ for (const [key, member] of entries) {
604
+ if (!(LEGACY_OVERRIDE_KEYS as readonly string[]).includes(key)) return { status: 'malformed' }
605
+ if (typeof member !== 'string' || member === '') return { status: 'malformed' }
606
+ }
607
+
608
+ return { status: 'known', value: value as LegacyBindingOverride }
609
+ }
610
+
611
+ /**
612
+ * Which half of a mapping graph an unresolved-evidence placeholder stands in for.
613
+ *
614
+ * Two kinds rather than one opaque sentinel because a node's `entityId` and a binding's `fieldId` are
615
+ * different address spaces: the same evidence must not produce one string that could satisfy both, or a
616
+ * field placeholder could be accepted where an entity was required.
617
+ */
618
+ export type LegacyUnresolvedIdKind = 'entity' | 'field'
619
+
620
+ /**
621
+ * The reserved prefix for an observed connector mapping that resolves to no stable curated id.
622
+ *
623
+ * The graph's shape is retained with a deterministic placeholder rather than dropping the binding,
624
+ * because `MappingNode.entityId` and `MappingBinding.fieldId` are required members: without a
625
+ * placeholder the only options were inventing a catalog identity or losing the observed evidence.
626
+ *
627
+ * The `:` separator is deliberate. The engine's `MachineIdSchema` is `^[A-Za-z0-9_.-]+$`, which forbids
628
+ * a colon, so a valid curated id can never collide with one of these and no activation rule changes.
629
+ */
630
+ export const LEGACY_UNRESOLVED_ID_PREFIX = 'legacy-unresolved:'
631
+
632
+ /** Exactly `legacy-unresolved:<entity|field>:<64 lowercase hex>`. Anchored: no prefix/suffix claimant. */
633
+ const LEGACY_UNRESOLVED_ID_PATTERN = /^legacy-unresolved:(entity|field):[0-9a-f]{64}$/
634
+
635
+ /**
636
+ * Builds the placeholder from a caller-supplied SHA-256 digest.
637
+ *
638
+ * The caller supplies the digest, not the raw evidence: shared does not hash legacy data or decide what
639
+ * the evidence is, so BunJS owns the material and shared owns only the canonical spelling. The factory
640
+ * still refuses a digest that is not 64 lowercase hex characters, because a placeholder that fails
641
+ * `isLegacyUnresolvedId` would be quarantined as a malformed claimant by the very consumers meant to
642
+ * recognize it.
643
+ *
644
+ * Deterministic and kind-disjoint: the same digest yields the same value on every call, and the entity
645
+ * and field forms of one digest are different strings.
646
+ */
647
+ export const makeLegacyUnresolvedId = (kind: LegacyUnresolvedIdKind, sha256Hex: string): string => {
648
+ if (!/^[0-9a-f]{64}$/.test(sha256Hex)) {
649
+ throw new Error(
650
+ `makeLegacyUnresolvedId: "${sha256Hex}" is not a 64-character lowercase SHA-256 hex digest`,
651
+ )
652
+ }
653
+ return `${LEGACY_UNRESOLVED_ID_PREFIX}${kind}:${sha256Hex}`
654
+ }
655
+
656
+ /**
657
+ * Exact recognition of a canonical placeholder.
658
+ *
659
+ * Distinguishes a canonical sentinel from a **prefix claimant** — a string that starts with the reserved
660
+ * prefix but is not canonical (wrong discriminator, short/uppercase/non-hex digest, prefix only). That
661
+ * distinction is the whole point: consumers quarantine everything starting with the prefix, and this
662
+ * predicate is what splits the quarantined set into `unresolved-legacy-mapping` and
663
+ * `malformed-legacy-unresolved-id`. Neither class may reach an engine.
664
+ */
665
+ export const isLegacyUnresolvedId = (value: unknown): boolean =>
666
+ typeof value === 'string' && LEGACY_UNRESOLVED_ID_PATTERN.test(value)
667
+
431
668
  /**
432
669
  * Hydrates a stored binding's behaviours to the total set (§2.2a: "the hydrated in-memory binding is
433
670
  * a total object"). One place rather than `?? 'omit'` at each use site — a reader that spelled the