@htilabs/platform-common-models 0.9.0 → 0.12.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 (174) hide show
  1. package/dist/config/index.cjs +4 -0
  2. package/dist/config/index.cjs.map +1 -1
  3. package/dist/config/index.d.cts +16 -1
  4. package/dist/config/index.d.ts +16 -1
  5. package/dist/config/index.js +2 -0
  6. package/dist/config/index.js.map +1 -1
  7. package/dist/constants/index.cjs +473 -182
  8. package/dist/constants/index.cjs.map +1 -1
  9. package/dist/constants/index.d.cts +1 -1
  10. package/dist/constants/index.d.ts +1 -1
  11. package/dist/constants/index.js +470 -170
  12. package/dist/constants/index.js.map +1 -1
  13. package/dist/cvc-Cp4uWnAa.d.cts +298 -0
  14. package/dist/cvc-Cp4uWnAa.d.ts +298 -0
  15. package/dist/cvcs/index.cjs +21798 -811
  16. package/dist/cvcs/index.cjs.map +1 -1
  17. package/dist/cvcs/index.d.cts +25138 -2212
  18. package/dist/cvcs/index.d.ts +25138 -2212
  19. package/dist/cvcs/index.js +21736 -810
  20. package/dist/cvcs/index.js.map +1 -1
  21. package/dist/enums/index.cjs +4557 -0
  22. package/dist/enums/index.cjs.map +1 -0
  23. package/dist/enums/index.d.cts +5257 -0
  24. package/dist/enums/index.d.ts +5257 -0
  25. package/dist/enums/index.js +4354 -0
  26. package/dist/enums/index.js.map +1 -0
  27. package/dist/index.cjs +24053 -1052
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +5 -3072
  30. package/dist/index.d.ts +5 -3072
  31. package/dist/index.js +23928 -1039
  32. package/dist/index.js.map +1 -1
  33. package/dist/mongo/index.cjs +383 -0
  34. package/dist/mongo/index.cjs.map +1 -0
  35. package/dist/mongo/index.d.cts +221 -0
  36. package/dist/mongo/index.d.ts +221 -0
  37. package/dist/mongo/index.js +351 -0
  38. package/dist/mongo/index.js.map +1 -0
  39. package/dist/{platform-auth-XVB9aHqR.d.cts → platform-auth-Dv5fu0Fh.d.cts} +22 -77
  40. package/dist/{platform-auth-XVB9aHqR.d.ts → platform-auth-Dv5fu0Fh.d.ts} +22 -77
  41. package/dist/schemas/index.cjs +30 -157
  42. package/dist/schemas/index.cjs.map +1 -1
  43. package/dist/schemas/index.js +30 -157
  44. package/dist/schemas/index.js.map +1 -1
  45. package/dist/services/index.cjs +0 -3
  46. package/dist/services/index.cjs.map +1 -1
  47. package/dist/services/index.js +0 -3
  48. package/dist/services/index.js.map +1 -1
  49. package/dist/types/index.d.cts +2 -2
  50. package/dist/types/index.d.ts +2 -2
  51. package/dist/validation/index.cjs +58 -0
  52. package/dist/validation/index.cjs.map +1 -1
  53. package/dist/validation/index.d.cts +82 -283
  54. package/dist/validation/index.d.ts +82 -283
  55. package/dist/validation/index.js +57 -0
  56. package/dist/validation/index.js.map +1 -1
  57. package/package.json +18 -1
  58. package/src/__sot__/README.md +91 -0
  59. package/src/__sot__/coreIndicatorFields.ts +331 -0
  60. package/src/__sot__/coreIndicators.pin.json +2149 -0
  61. package/src/__sot__/cvcIndex.pin.json +272 -0
  62. package/src/__sot__/scoringEmits.pin.json +176 -0
  63. package/src/__tests__/__snapshots__/cvc-sot.snap +260 -40
  64. package/src/__tests__/core-information-scope-invariant.test.ts +134 -0
  65. package/src/__tests__/cvc-136-scoring-invariant.test.ts +328 -0
  66. package/src/__tests__/cvc-181-182-country-parity.test.ts +163 -0
  67. package/src/__tests__/cvc-drift-gate.test.ts +1036 -0
  68. package/src/__tests__/cvc-sot-snapshot.test.ts +191 -18
  69. package/src/__tests__/cvc-status-parser.test.ts +150 -0
  70. package/src/__tests__/cvc-structural.test.ts +70 -1
  71. package/src/__tests__/mongo-verifier.test.ts +502 -0
  72. package/src/config/index.ts +8 -2
  73. package/src/constants/ic.ts +629 -206
  74. package/src/constants/service-catalog.ts +4 -2
  75. package/src/cvcs/activityType.v1.0.0.json +143 -0
  76. package/src/cvcs/adminRoles.v1.0.0.json +153 -0
  77. package/src/cvcs/administeringJurisdiction.v1.0.0.json +40 -40
  78. package/src/cvcs/ageBinReporting.v1.0.0.json +40 -40
  79. package/src/cvcs/assertionDomain.v1.1.0.json +647 -0
  80. package/src/cvcs/assertionStatus.v1.0.0.json +80 -0
  81. package/src/cvcs/carCorrectionReason.v1.0.0.json +89 -0
  82. package/src/cvcs/caseShareState.v1.0.0.json +62 -0
  83. package/src/cvcs/{checkInPhase.v1.0.0.json → checkInPhase.v1.1.0.json} +20 -2
  84. package/src/cvcs/childChangeType.v1.0.0.json +152 -0
  85. package/src/cvcs/citizenship.v1.0.0.json +3062 -0
  86. package/src/cvcs/contactInfoTypes.v1.0.0.json +40 -40
  87. package/src/cvcs/contactLinkType.v1.0.0.json +89 -0
  88. package/src/cvcs/coreDhState.v1.0.0.json +113 -0
  89. package/src/cvcs/coreFunctions.v1.0.0.json +746 -0
  90. package/src/cvcs/coreIndicators.v1.0.0.json +2918 -0
  91. package/src/cvcs/coreInformationScope.v1.0.0.json +1165 -0
  92. package/src/cvcs/coreReferralOutcome.v1.0.0.json +71 -0
  93. package/src/cvcs/countries.v1.0.0.json +3077 -0
  94. package/src/cvcs/createdBySystem.v1.0.0.json +89 -0
  95. package/src/cvcs/criminalOrgCategory.v1.0.0.json +116 -0
  96. package/src/cvcs/determinationHelperCategories.v1.0.0.json +1166 -0
  97. package/src/cvcs/employmentStatus.v1.0.0.json +60 -60
  98. package/src/cvcs/exploitationType.v1.0.0.json +106 -0
  99. package/src/cvcs/facilitatorEntityType.v1.0.0.json +40 -40
  100. package/src/cvcs/highestEducationLevelCompleted.v1.0.0.json +55 -46
  101. package/src/cvcs/hivStatus.v1.0.0.json +71 -0
  102. package/src/cvcs/hmisCurrentLivingSituation.v1.0.0.json +409 -0
  103. package/src/cvcs/hmisRelationshipToHoh.v1.0.0.json +104 -0
  104. package/src/cvcs/homelessStatus.v1.0.0.json +27 -27
  105. package/src/cvcs/housingSubsidyTypes.v1.0.0.json +161 -0
  106. package/src/cvcs/htType.v1.0.0.json +87 -0
  107. package/src/cvcs/identificationStatus.v1.0.0.json +18 -0
  108. package/src/cvcs/immigrationLegalStatusChangeType.v1.0.0.json +143 -0
  109. package/src/cvcs/incarcerationEpisodeType.v1.0.0.json +106 -0
  110. package/src/cvcs/incidentInvolvementRoles.v1.0.0.json +40 -40
  111. package/src/cvcs/incidentParticipationRoles.v1.0.0.json +47 -37
  112. package/src/cvcs/incomeBenefitsSources.v1.0.0.json +31 -2
  113. package/src/cvcs/index.ts +138 -1
  114. package/src/cvcs/juvenileJusticeEpisodeType.v1.0.0.json +28 -18
  115. package/src/cvcs/juvenileJusticeInvolvementStatus.v1.0.0.json +32 -32
  116. package/src/cvcs/livingSituation.v1.0.0.json +213 -0
  117. package/src/cvcs/mentalHealthStatus.v1.0.0.json +71 -0
  118. package/src/cvcs/militaryBranch.v1.0.0.json +20 -20
  119. package/src/cvcs/militaryStatus.v1.0.0.json +20 -20
  120. package/src/cvcs/minorAdultStatus.v1.0.0.json +80 -0
  121. package/src/cvcs/nameType.v1.0.0.json +40 -40
  122. package/src/cvcs/needsAssessmentChangeType.v1.0.0.json +134 -0
  123. package/src/cvcs/offenderStatus.v1.0.0.json +40 -40
  124. package/src/cvcs/offenderStatusFamily.v1.0.0.json +36 -36
  125. package/src/cvcs/personRelationships.v1.0.0.json +67 -2
  126. package/src/cvcs/poPetitionBasis.v1.0.0.json +96 -0
  127. package/src/cvcs/poStatus.v1.0.0.json +144 -0
  128. package/src/cvcs/poViolationStatus.v1.0.0.json +76 -0
  129. package/src/cvcs/programEnrollmentChangeType.v1.0.0.json +134 -0
  130. package/src/cvcs/provenanceSourceId.v1.0.0.json +134 -0
  131. package/src/cvcs/radiusBucket.v1.0.0.json +110 -0
  132. package/src/cvcs/recencyBand.v1.0.0.json +104 -39
  133. package/src/cvcs/referralEntityCategory.v1.0.0.json +40 -40
  134. package/src/cvcs/referralOrigin.v1.0.0.json +26 -0
  135. package/src/cvcs/relationshipConcern.v1.0.0.json +123 -0
  136. package/src/cvcs/riskCategory.v1.0.0.json +134 -0
  137. package/src/cvcs/riskIdentificationMilestone.v1.0.0.json +109 -0
  138. package/src/cvcs/riskSeverityBand.v1.0.0.json +139 -0
  139. package/src/cvcs/roiMethod.v1.0.0.json +107 -0
  140. package/src/cvcs/roiScope.v1.0.0.json +296 -0
  141. package/src/cvcs/roiStatus.v1.0.0.json +106 -0
  142. package/src/cvcs/romanticRelationshipChangeType.v1.0.0.json +162 -0
  143. package/src/cvcs/serviceAudience.v1.0.0.json +96 -0
  144. package/src/cvcs/serviceCategories.v1.0.0.json +44 -44
  145. package/src/cvcs/serviceDeliveryChannel.v1.0.0.json +147 -0
  146. package/src/cvcs/serviceMechanisms.v1.0.0.json +36 -36
  147. package/src/cvcs/serviceStates.v1.0.0.json +55 -33
  148. package/src/cvcs/sessionNoteVisibility.v1.0.0.json +80 -0
  149. package/src/cvcs/sessionTemplate.v1.0.0.json +283 -0
  150. package/src/cvcs/sexProviderSubrole.v1.0.0.json +35 -28
  151. package/src/cvcs/sharePurpose.v1.0.0.json +80 -12
  152. package/src/cvcs/smtType.v1.0.0.json +40 -40
  153. package/src/cvcs/sourceCategory.v1.1.0.json +8 -1
  154. package/src/cvcs/sourceInstrument.v1.0.0.json +458 -0
  155. package/src/cvcs/sourceSubtype.v1.1.0.json +36 -0
  156. package/src/cvcs/sourceSystem.v1.0.0.json +203 -0
  157. package/src/cvcs/specialNeedsDisabilities.v1.0.0.json +143 -0
  158. package/src/cvcs/subjectType.v1.0.0.json +80 -0
  159. package/src/cvcs/suggestionSource.v1.0.0.json +71 -0
  160. package/src/cvcs/traffickingRelevantRole.v1.0.0.json +104 -0
  161. package/src/cvcs/userRoles.v1.0.0.json +203 -0
  162. package/src/cvcs/verificationMethod.v1.0.0.json +18 -0
  163. package/src/cvcs/victimAbuseTypes.v1.0.0.json +276 -0
  164. package/src/cvcs/victimStatusFamily.v1.0.0.json +40 -40
  165. package/src/cvcs/whyNots.v1.0.0.json +385 -0
  166. package/src/generated/cvc-enums.ts +2318 -10
  167. package/src/mongo/catalog.ts +65 -0
  168. package/src/mongo/contract.ts +157 -0
  169. package/src/mongo/index.ts +343 -0
  170. package/src/mongo/similarity.ts +133 -0
  171. package/src/mongo/uri.ts +53 -0
  172. package/src/services/cvcRegistryService.ts +1 -1
  173. package/src/validation/cvcStatus.ts +209 -0
  174. package/src/validation/index.ts +1 -0
@@ -0,0 +1,91 @@
1
+ # `src/__sot__/` — pinned upstream source-of-truth snapshots
2
+
3
+ **Do not hand-edit these files.** Regenerate them with `npm run sot:pins`.
4
+
5
+ ## Why they exist
6
+
7
+ platform-common's CVC surface is **downstream** of three sources of truth that
8
+ live in other repos:
9
+
10
+ | Pin | Upstream | What it is |
11
+ |---|---|---|
12
+ | `cvcIndex.pin.json` | `htilabstech/prototype` · `Final CVCs/CVC_INDEX.md` | The CVC **number space** — which number belongs to which vocabulary. **Authoritative.** A yaml's self-declared number is not. |
13
+ | `coreIndicators.pin.json` | `htilabstech/prototype` · `data/core_indicators.yaml` | The indicator **catalog** — which indicator codes legitimately exist, **and what the catalog says about each one** (label · definition · family · polarity · severity · is_alert · alert_when, verbatim). |
14
+ | `scoringEmits.pin.json` | `htilabstech/hti-scoring` · `weights/risk.weights.json` → `emits_by_code` | What the risk pipeline actually **consumes** — what CVC-136 must be able to express. |
15
+
16
+ (Notion is the fourth SOT: **ratification**. It has no pin because it is a human
17
+ process. Items awaiting it carry `_status.vocabStatus:
18
+ "provisional-pending-notion-ratification"` in their CVC JSON, and are listed in
19
+ `docs/adrs/ADR-CVC-0.8.13-canonical-alignment.md`.)
20
+
21
+ ### The field half of `coreIndicators.pin.json`
22
+
23
+ That pin originally carried only `codes: string[]` — the sorted **set of code
24
+ names**. So both halves of the contract were blind to everything else the catalog
25
+ says: a code could keep its name while its label, definition, family, polarity,
26
+ severity or alert routing was rewritten, and nothing failed. That shipped twice
27
+ in consecutive refreshes — 0.8.14 dropped a definition revision, and the 0.8.17
28
+ branch initially dropped a label rename plus a load-bearing deprecation
29
+ qualifier, caught in human review rather than by CI.
30
+
31
+ The pin now also carries `fields` — the seven projected values per code,
32
+ **verbatim**. `GATE H` in the drift gate asserts CVC-136 restates every one of
33
+ them. The projection and the (enumerated, individually self-tested) YAML
34
+ round-trip normalizations live in `coreIndicatorFields.ts` **next to this file**,
35
+ because both halves must share one definition of them.
36
+
37
+ > `coreIndicatorFields.ts` is hand-maintained source, not a pin. The
38
+ > "do not hand-edit" rule above is about the `*.pin.json` snapshots.
39
+
40
+ ### Regenerating one pin without bumping another
41
+
42
+ The pins are deliberately allowed to sit at **different** upstream SHAs. For a
43
+ release `cvcIndex` was held at `a596eb9` while the prototype moved on, because
44
+ absorbing the newer `CVC_INDEX.md` meant reconciling `INDEX_ABSENT` first —
45
+ `juvenile_justice_involvement_status` (CVC-95) gained an index row and had to be
46
+ promoted out of `INDEX_ABSENT` into `CANONICAL_BINDING`, and CVC-177's binding
47
+ had to be re-pointed at the surviving spelling after the stale duplicate row was
48
+ removed. That reconcile has landed and `cvcIndex` is now at `622410b`;
49
+ `scoringEmits` still sits at its own SHA. Use `--only` so refreshing one pin from
50
+ a checkout does not drag the others along:
51
+
52
+ ```bash
53
+ npm run sot:pins -- --only=coreIndicators
54
+ ```
55
+
56
+ Before these pins existed, platform-common validated itself **against itself**.
57
+ So it drifted, silently, in every direction at once — 66 canonical indicator
58
+ codes missing (including the whole perpetrator lane, which made facilitator
59
+ scoring unexpressible), 56 invented codes consumed by nobody, and a domain
60
+ squatting on CVC-233 which hid the fact that the domain that *owns* 233 had never
61
+ been authored at all.
62
+
63
+ ## The two halves
64
+
65
+ CI cannot clone two private repos on every PR, so the contract is split:
66
+
67
+ - **ENFORCER** — `src/__tests__/cvc-drift-gate.test.ts` asserts the package
68
+ conforms to these pins. Hermetic, no network, runs on every PR
69
+ (`npm run gate:cvc`).
70
+ - **DETECTOR** — `scripts/sot-pins.ts --check` re-derives the pins from live
71
+ upstream checkouts and diffs. Run weekly by
72
+ `.github/workflows/cvc-sot-drift.yml`, which opens a PR when upstream moves.
73
+
74
+ Both halves derive the pins with the **same code**, so a pin can never disagree
75
+ with the checker that validates it.
76
+
77
+ ## Refreshing a pin
78
+
79
+ ```bash
80
+ # Point at local checkouts of the upstream repos (defaults to siblings of the repo root)
81
+ export PROTOTYPE_DIR=../../../../prototype
82
+ export HTI_SCORING_DIR=../../../../hti-scoring
83
+
84
+ npm run sot:pins:check # has upstream moved?
85
+ npm run sot:pins # regenerate
86
+ npm test # the gate now tells you what must change to conform
87
+ ```
88
+
89
+ **Commit the pins and the CVC changes together.** A pin bump on its own is a lie:
90
+ it says "we looked" without saying "we conformed". Each pin records the
91
+ `sourceSha` it was taken at, so a bump is always a reviewable, attributable act.
@@ -0,0 +1,331 @@
1
+ /**
2
+ * THE FIELD HALF OF THE coreIndicators PIN
3
+ * ========================================
4
+ *
5
+ * `coreIndicators.pin.json` used to carry ONLY `codes: string[]` — the sorted
6
+ * SET of `code:` values in `data/core_indicators.yaml`. That made the pin, and
7
+ * therefore BOTH halves of the drift contract, blind to everything else the
8
+ * catalog says about an indicator. A code could keep its name while its label,
9
+ * definition, family, polarity, severity, alert routing, or alert recency
10
+ * window was rewritten upstream, and neither `sot:pins:check` nor `gate:cvc`
11
+ * could see it.
12
+ *
13
+ * That blindness shipped twice, in consecutive refreshes:
14
+ *
15
+ * 0.8.14 — dropped a definition revision that came with the code delta.
16
+ * 0.8.17 — initially dropped a LABEL RENAME and a load-bearing DEPRECATION
17
+ * QUALIFIER in a definition. Caught in human review, not by CI.
18
+ *
19
+ * Both are the same bug: a set-of-codes pin cannot express a field revision, so
20
+ * a refresh that copies the code delta and forgets the field delta passes green.
21
+ *
22
+ * This module is the fix. It defines the PROJECTION — the seven fields of an
23
+ * indicator that platform-common actually restates in
24
+ * `src/cvcs/coreIndicators.v1.0.0.json` — and the NORMALIZATION that makes a
25
+ * YAML scalar and a JSON string comparable. `scripts/sot-pins.ts` uses it to
26
+ * widen the pin; `src/__tests__/cvc-drift-gate.test.ts` (GATE H) uses it to
27
+ * assert the shipped CVC-136 restates every pinned field faithfully.
28
+ *
29
+ * It lives in `src/` rather than `scripts/` for one reason: the root tsconfig
30
+ * sets `rootDir: ./src`, so a `src/` test cannot import from `scripts/`, while
31
+ * `scripts/tsconfig.json` deliberately includes `../src/**`. Putting it here is
32
+ * what lets BOTH halves share ONE definition of the projection — the same
33
+ * property `scripts/sot-pins.ts` already relies on for the pins themselves:
34
+ * a pin can never disagree with the checker that validates it.
35
+ *
36
+ * (This is a `.ts` source file in `src/__sot__/`, not a pin. The README's
37
+ * "do not hand-edit, regenerate with `npm run sot:pins`" rule is about the
38
+ * `*.pin.json` snapshots. This file is hand-maintained.)
39
+ */
40
+
41
+ // ─── The projection ─────────────────────────────────────────────────────────
42
+
43
+ /**
44
+ * The fields CVC-136 restates from the catalog, and therefore the fields the
45
+ * pin must carry. Adding a field here widens the gate: regenerate the pin
46
+ * (`npm run sot:pins`) and GATE H starts enforcing it.
47
+ */
48
+ export const PROJECTED_FIELDS = [
49
+ "label",
50
+ "definition",
51
+ "family",
52
+ "polarity",
53
+ "severity",
54
+ "isAlert",
55
+ "alertWhen",
56
+ ] as const;
57
+
58
+ export type ProjectedField = (typeof PROJECTED_FIELDS)[number];
59
+
60
+ /** One indicator's projected fields. `null` means the source omits the field. */
61
+ export type ProjectedIndicatorFields = Readonly<Record<ProjectedField, string | null>>;
62
+
63
+ /**
64
+ * `data/core_indicators.yaml` field name -> projected name. The catalog is
65
+ * snake_case; the CVC envelope is camelCase.
66
+ */
67
+ const CATALOG_TO_PROJECTED: ReadonlyArray<readonly [string, ProjectedField]> = [
68
+ ["label", "label"],
69
+ ["definition", "definition"],
70
+ ["family", "family"],
71
+ ["polarity", "polarity"],
72
+ ["severity", "severity"],
73
+ ["is_alert", "isAlert"],
74
+ ["alert_when", "alertWhen"],
75
+ ];
76
+
77
+ /**
78
+ * `coreIndicators.v1.0.0.json` entry field name -> projected name. Note the one
79
+ * genuine rename: the CVC envelope calls the catalog's `label` a `title`,
80
+ * because `title` is the envelope-wide field for a human-readable value name.
81
+ * That rename is structural and deliberate — it is NOT drift.
82
+ */
83
+ const SOT_TO_PROJECTED: ReadonlyArray<readonly [string, ProjectedField]> = [
84
+ ["title", "label"],
85
+ ["definition", "definition"],
86
+ ["family", "family"],
87
+ ["polarity", "polarity"],
88
+ ["severity", "severity"],
89
+ ["isAlert", "isAlert"],
90
+ ["alertWhen", "alertWhen"],
91
+ ];
92
+
93
+ /**
94
+ * Free-prose fields, which get the full text normalization below. The other
95
+ * four are machine-consumed enum tokens and are compared as-is apart from
96
+ * trimming — a stray space inside `thread_pave` is real drift, not formatting.
97
+ */
98
+ const PROSE_FIELDS: ReadonlySet<ProjectedField> = new Set<ProjectedField>([
99
+ "label",
100
+ "definition",
101
+ ]);
102
+
103
+ // ─── Normalization ──────────────────────────────────────────────────────────
104
+
105
+ /**
106
+ * WHICH SIDE OF THE COMPARISON A VALUE CAME FROM.
107
+ *
108
+ * This matters, and it is not decoration. A normalization applied to BOTH sides
109
+ * can only ever absorb a difference — it can never CREATE one. That is fine for
110
+ * an artifact the emitter inflicts on the catalog and that CVC-136 was always
111
+ * free to restate either way (a wrap point, a trailing newline). It is NOT fine
112
+ * for an artifact that CVC-136 has an obligation to FIX.
113
+ *
114
+ * E4 is the second kind. See its entry below.
115
+ */
116
+ export type NormalizationSide = "catalog" | "sot";
117
+
118
+ /**
119
+ * THE NORMALIZATION EXEMPTIONS.
120
+ *
121
+ * A YAML scalar and the JSON string that restates it are not byte-identical
122
+ * even when they say exactly the same thing, because the catalog is written and
123
+ * rewritten by a YAML emitter that hard-wraps long scalars. Each exemption
124
+ * below is a real, enumerated round-trip artifact observed in the pinned
125
+ * catalog — NOT a general-purpose fuzzy match.
126
+ *
127
+ * Each carries:
128
+ *
129
+ * `codes` — the exact catalog codes that exercise it.
130
+ * `fields` — the exact projected fields it covers. SCOPED DELIBERATELY: a
131
+ * self-test that spans all seven fields can be satisfied by a
132
+ * DIFFERENT exemption's artifact in a different field, so a dead
133
+ * exemption would look alive. (Observed: every prose artifact in
134
+ * the pinned catalog is in `definition`; E4 and E2 share both a
135
+ * code AND that field.)
136
+ * `sides` — which side of the comparison the normalization runs on. All but
137
+ * E4 are symmetric.
138
+ * `detect` — a predicate over the RAW CATALOG value that is true iff the
139
+ * underlying artifact is still physically present. Field scoping
140
+ * alone is not enough to make a dead exemption fail when two
141
+ * exemptions overlap on one code+field (E2/E4 do exactly that);
142
+ * this is what makes each one independently falsifiable.
143
+ *
144
+ * GATE H's exemption self-tests assert all four: the artifact is still detected,
145
+ * a RAW comparison of the covered fields genuinely fails, and the normalized
146
+ * comparison passes. An exemption that stops being exercised is therefore
147
+ * visible, not silently load-bearing forever.
148
+ *
149
+ * What these CANNOT hide — and this is the point — is any change to what a
150
+ * field SAYS: a label rename, a definition revision, a deprecation qualifier, a
151
+ * family/polarity/severity reclassification, or an alert-routing change. Those
152
+ * are exactly the drift class that shipped twice, and they all survive
153
+ * normalization intact.
154
+ */
155
+ export const NORMALIZATION_EXEMPTIONS = [
156
+ {
157
+ id: "E1-trailing-newline",
158
+ what: "Block and wrapped quoted scalars parse with a trailing newline; the JSON prose does not.",
159
+ sides: "both",
160
+ codes: [
161
+ "intimate_partner_violence_reported_to_law_enforcement",
162
+ "sex_acts_in_own_residence",
163
+ "payment_routed_through_third_party",
164
+ ],
165
+ fields: ["definition"],
166
+ detect: (raw: string) => /\s$/.test(raw),
167
+ },
168
+ {
169
+ id: "E2-wrap-folding",
170
+ what:
171
+ "The emitter hard-wraps long scalars, so wrap points parse as newlines. " +
172
+ "CVC-136 sometimes preserved them and sometimes folded them to spaces. " +
173
+ "Every whitespace run collapses to one space on BOTH sides.",
174
+ sides: "both",
175
+ codes: [
176
+ "depends_on_spouse_or_family_for_immigration_status",
177
+ "clients_unaware_of_third_party_coordination",
178
+ "trauma_perpetrator_is_current_manager",
179
+ ],
180
+ fields: ["definition"],
181
+ detect: (raw: string) => /\S[ \t]*\r?\n[ \t]*\S/.test(raw),
182
+ },
183
+ {
184
+ id: "E3-wrapped-hyphen",
185
+ what:
186
+ "When a wrap point falls immediately after a hyphen inside a compound word " +
187
+ '("emotional-\\nverbal-stalking"), the join is hyphen-direct with NO space. ' +
188
+ "Applied before E2, which would otherwise leave a space behind the hyphen.",
189
+ sides: "both",
190
+ codes: ["trauma_perpetrator_is_current_manager"],
191
+ fields: ["definition"],
192
+ detect: (raw: string) => /-[ \t]*\r?\n/.test(raw),
193
+ },
194
+ {
195
+ id: "E4-leaked-hex-escape",
196
+ what:
197
+ "One upstream scalar was authored SINGLE-QUOTED with Python-style escapes, " +
198
+ "so `fianc\\xE9` parses as six literal characters rather than `fiancé`. " +
199
+ "CVC-136 carries the real character, and MUST: the escape is an upstream " +
200
+ "defect that the restatement is obliged to fix, not a formatting choice it " +
201
+ "is free to mirror. So this decode is CATALOG-ONLY — running it on the SOT " +
202
+ "side too would make a shipped literal `fianc\\xE9(e)` compare EQUAL to the " +
203
+ "catalog and pass, which is the one thing this exemption must never do. " +
204
+ "(That symmetry was the real bug: a snapshot test cannot hold the line, " +
205
+ "because it is refreshed with UPDATE_SNAPSHOT=1.) GATE H additionally " +
206
+ "asserts outright that no shipped CVC-136 value contains `\\xNN`.",
207
+ sides: "catalog",
208
+ codes: ["depends_on_spouse_or_family_for_immigration_status"],
209
+ fields: ["definition"],
210
+ detect: (raw: string) => LEAKED_HEX_ESCAPE.test(raw),
211
+ },
212
+ {
213
+ id: "E5-empty-is-alert",
214
+ what:
215
+ "One catalog entry carries `is_alert: ''`. CVC-136 models 'no alert routing' " +
216
+ "as an absent field. An empty string is read as absent on BOTH sides — but " +
217
+ "ONLY for `isAlert`, which is the only field that is ever empty on either " +
218
+ "side. A blanket empty-reads-as-absent rule would silently excuse an emptied " +
219
+ "label or definition, which is drift, not formatting.",
220
+ sides: "both",
221
+ codes: ["intimate_partner_violence_reported_to_law_enforcement"],
222
+ fields: ["isAlert"],
223
+ detect: (raw: string) => raw === "",
224
+ },
225
+ ] as const;
226
+
227
+ /** The one field E5 covers. An empty value is read as absent here and nowhere else. */
228
+ const EMPTY_READS_AS_ABSENT: ReadonlySet<ProjectedField> = new Set<ProjectedField>(["isAlert"]);
229
+
230
+ /** E4's artifact, as a pattern. Also used by GATE H's belt-and-brace assertion. */
231
+ export const LEAKED_HEX_ESCAPE = /\\x[0-9A-Fa-f]{2}/;
232
+
233
+ /**
234
+ * E4. Decode Python-style `\xNN` escapes that leaked into single-quoted scalars.
235
+ *
236
+ * CATALOG-SIDE ONLY — see the E4 exemption entry. Applying this to the shipped
237
+ * CVC-136 value would let a literal escape ship undetected.
238
+ */
239
+ export function decodeLeakedHexEscapes(value: string): string {
240
+ return value.replace(/\\x([0-9A-Fa-f]{2})/g, (_match, hex: string) =>
241
+ String.fromCharCode(Number.parseInt(hex, 16)),
242
+ );
243
+ }
244
+
245
+ /**
246
+ * E1 + E2 + E3 (symmetric) + E4 (catalog only), in the order they must be
247
+ * applied.
248
+ */
249
+ export function normalizeProse(value: string, side: NormalizationSide): string {
250
+ const decoded = side === "catalog" ? decodeLeakedHexEscapes(value) : value; // E4
251
+ return decoded
252
+ .replace(/-[ \t]*\r?\n[ \t]*/g, "-") // E3 — must precede E2
253
+ .replace(/\s+/g, " ") // E2 (and E1's trailing newline)
254
+ .trim(); // E1
255
+ }
256
+
257
+ /**
258
+ * Normalize one projected value for comparison. Prose gets the full treatment;
259
+ * enum tokens get trimming only. An empty `isAlert` reads as absent (E5); an
260
+ * empty anything-else stays empty and will therefore mismatch, which is what we
261
+ * want — that is content loss, not formatting.
262
+ */
263
+ export function normalizeProjectedValue(
264
+ field: ProjectedField,
265
+ value: string | null,
266
+ side: NormalizationSide,
267
+ ): string | null {
268
+ if (value === null) return null;
269
+ const normalized = PROSE_FIELDS.has(field) ? normalizeProse(value, side) : value.trim();
270
+ if (normalized === "" && EMPTY_READS_AS_ABSENT.has(field)) return null; // E5
271
+ return normalized;
272
+ }
273
+
274
+ /** Normalize one value that came from `data/core_indicators.yaml`. */
275
+ export function normalizeCatalogValue(
276
+ field: ProjectedField,
277
+ value: string | null,
278
+ ): string | null {
279
+ return normalizeProjectedValue(field, value, "catalog");
280
+ }
281
+
282
+ /** Normalize one value that came from `src/cvcs/coreIndicators.v1.0.0.json`. */
283
+ export function normalizeSotValue(field: ProjectedField, value: string | null): string | null {
284
+ return normalizeProjectedValue(field, value, "sot");
285
+ }
286
+
287
+ /** Normalize a whole projected record. */
288
+ export function normalizeProjectedFields(
289
+ fields: ProjectedIndicatorFields,
290
+ side: NormalizationSide,
291
+ ): ProjectedIndicatorFields {
292
+ const out = {} as Record<ProjectedField, string | null>;
293
+ for (const field of PROJECTED_FIELDS) {
294
+ out[field] = normalizeProjectedValue(field, fields[field], side);
295
+ }
296
+ return out;
297
+ }
298
+
299
+ // ─── Projection ─────────────────────────────────────────────────────────────
300
+
301
+ function readRaw(source: Record<string, unknown>, key: string): string | null {
302
+ const value = source[key];
303
+ if (value === undefined || value === null) return null;
304
+ return typeof value === "string" ? value : String(value);
305
+ }
306
+
307
+ function project(
308
+ source: Record<string, unknown>,
309
+ mapping: ReadonlyArray<readonly [string, ProjectedField]>,
310
+ ): ProjectedIndicatorFields {
311
+ const out = {} as Record<ProjectedField, string | null>;
312
+ for (const [sourceKey, field] of mapping) {
313
+ out[field] = readRaw(source, sourceKey);
314
+ }
315
+ return out;
316
+ }
317
+
318
+ /**
319
+ * Project one `data/core_indicators.yaml` entry. Values are VERBATIM — the pin
320
+ * is an honest snapshot of the upstream bytes, exactly like `cvcIndex.pin.json`
321
+ * storing exact index-row strings. Normalization is a comparison-time concern,
322
+ * which is what lets GATE H prove each exemption is really needed.
323
+ */
324
+ export function projectCatalogEntry(entry: Record<string, unknown>): ProjectedIndicatorFields {
325
+ return project(entry, CATALOG_TO_PROJECTED);
326
+ }
327
+
328
+ /** Project one `src/cvcs/coreIndicators.v1.0.0.json` entry. */
329
+ export function projectSotEntry(entry: Record<string, unknown>): ProjectedIndicatorFields {
330
+ return project(entry, SOT_TO_PROJECTED);
331
+ }