@htilabs/platform-common-models 0.8.12 → 0.8.14

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 (130) hide show
  1. package/README.md +44 -0
  2. package/dist/config/index.cjs +4 -0
  3. package/dist/config/index.cjs.map +1 -1
  4. package/dist/config/index.d.cts +16 -1
  5. package/dist/config/index.d.ts +16 -1
  6. package/dist/config/index.js +2 -0
  7. package/dist/config/index.js.map +1 -1
  8. package/dist/constants/index.cjs +143 -287
  9. package/dist/constants/index.cjs.map +1 -1
  10. package/dist/constants/index.d.cts +1 -1
  11. package/dist/constants/index.d.ts +1 -1
  12. package/dist/constants/index.js +143 -275
  13. package/dist/constants/index.js.map +1 -1
  14. package/dist/cvcs/index.cjs +12173 -969
  15. package/dist/cvcs/index.cjs.map +1 -1
  16. package/dist/cvcs/index.d.cts +14927 -2662
  17. package/dist/cvcs/index.d.ts +14927 -2662
  18. package/dist/cvcs/index.js +12141 -968
  19. package/dist/cvcs/index.js.map +1 -1
  20. package/dist/{index-I-DiX9eQ.d.ts → index-CDoqrfc1.d.ts} +1 -1
  21. package/dist/{index-CoVr1jIV.d.cts → index-Zu_mOJRn.d.cts} +1 -1
  22. package/dist/index.cjs +13297 -1361
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +1118 -130
  25. package/dist/index.d.ts +1118 -130
  26. package/dist/index.js +13239 -1346
  27. package/dist/index.js.map +1 -1
  28. package/dist/models/index.d.cts +2 -2
  29. package/dist/models/index.d.ts +2 -2
  30. package/dist/mongo/index.cjs +383 -0
  31. package/dist/mongo/index.cjs.map +1 -0
  32. package/dist/mongo/index.d.cts +221 -0
  33. package/dist/mongo/index.d.ts +221 -0
  34. package/dist/mongo/index.js +351 -0
  35. package/dist/mongo/index.js.map +1 -0
  36. package/dist/{platform-auth-BwfZ0bxU.d.cts → platform-auth-AsfnIXfK.d.cts} +2 -74
  37. package/dist/{platform-auth-BwfZ0bxU.d.ts → platform-auth-AsfnIXfK.d.ts} +2 -74
  38. package/dist/schemas/index.cjs +5 -153
  39. package/dist/schemas/index.cjs.map +1 -1
  40. package/dist/schemas/index.d.cts +29 -25
  41. package/dist/schemas/index.d.ts +29 -25
  42. package/dist/schemas/index.js +5 -153
  43. package/dist/schemas/index.js.map +1 -1
  44. package/dist/services/index.cjs +0 -3
  45. package/dist/services/index.cjs.map +1 -1
  46. package/dist/services/index.js +0 -3
  47. package/dist/services/index.js.map +1 -1
  48. package/dist/types/index.d.cts +2 -2
  49. package/dist/types/index.d.ts +2 -2
  50. package/package.json +13 -1
  51. package/src/__sot__/README.md +56 -0
  52. package/src/__sot__/coreIndicators.pin.json +220 -0
  53. package/src/__sot__/cvcIndex.pin.json +268 -0
  54. package/src/__sot__/scoringEmits.pin.json +176 -0
  55. package/src/__tests__/__snapshots__/cvc-sot.snap +125 -37
  56. package/src/__tests__/cvc-136-scoring-invariant.test.ts +326 -0
  57. package/src/__tests__/cvc-drift-gate.test.ts +607 -0
  58. package/src/__tests__/cvc-sot-snapshot.test.ts +50 -8
  59. package/src/__tests__/cvc-structural.test.ts +43 -1
  60. package/src/__tests__/mongo-verifier.test.ts +502 -0
  61. package/src/config/index.ts +8 -2
  62. package/src/constants/ic.ts +213 -333
  63. package/src/constants/service-catalog.ts +4 -2
  64. package/src/cvcs/adminRoles.v1.0.0.json +153 -0
  65. package/src/cvcs/administeringJurisdiction.v1.0.0.json +40 -40
  66. package/src/cvcs/ageBinReporting.v1.0.0.json +40 -40
  67. package/src/cvcs/assertionDomain.v1.1.0.json +78 -105
  68. package/src/cvcs/assertionStatus.v1.0.0.json +80 -0
  69. package/src/cvcs/citizenship.v1.0.0.json +3062 -0
  70. package/src/cvcs/contactInfoTypes.v1.0.0.json +40 -40
  71. package/src/cvcs/coreDhState.v1.0.0.json +113 -0
  72. package/src/cvcs/coreIndicators.v1.0.0.json +2905 -0
  73. package/src/cvcs/createdBySystem.v1.0.0.json +89 -0
  74. package/src/cvcs/employmentStatus.v1.0.0.json +60 -60
  75. package/src/cvcs/exploitationType.v1.0.0.json +106 -0
  76. package/src/cvcs/facilitatorEntityType.v1.0.0.json +40 -40
  77. package/src/cvcs/highestEducationLevelCompleted.v1.0.0.json +50 -50
  78. package/src/cvcs/hmisCurrentLivingSituation.v1.0.0.json +409 -0
  79. package/src/cvcs/hmisSex.v1.0.0.json +89 -0
  80. package/src/cvcs/homelessStatus.v1.0.0.json +27 -27
  81. package/src/cvcs/housingSubsidyTypes.v1.0.0.json +26 -24
  82. package/src/cvcs/incarcerationEpisodeType.v1.0.0.json +106 -0
  83. package/src/cvcs/incidentInvolvementRoles.v1.0.0.json +40 -40
  84. package/src/cvcs/incidentParticipationRoles.v1.0.0.json +40 -40
  85. package/src/cvcs/index.ts +73 -2
  86. package/src/cvcs/juvenileJusticeEpisodeType.v1.0.0.json +106 -0
  87. package/src/cvcs/juvenileJusticeInvolvementStatus.v1.0.0.json +32 -32
  88. package/src/cvcs/militaryBranch.v1.0.0.json +20 -20
  89. package/src/cvcs/militaryStatus.v1.0.0.json +20 -20
  90. package/src/cvcs/minorAdultStatus.v1.0.0.json +80 -0
  91. package/src/cvcs/nameType.v1.0.0.json +40 -40
  92. package/src/cvcs/offenderStatus.v1.0.0.json +40 -40
  93. package/src/cvcs/offenderStatusFamily.v1.0.0.json +36 -36
  94. package/src/cvcs/poPetitionBasis.v1.0.0.json +96 -0
  95. package/src/cvcs/poStatus.v1.0.0.json +144 -0
  96. package/src/cvcs/poViolationStatus.v1.0.0.json +76 -0
  97. package/src/cvcs/radiusBucket.v1.0.0.json +23 -11
  98. package/src/cvcs/recencyBand.v1.0.0.json +126 -42
  99. package/src/cvcs/referralEntityCategory.v1.0.0.json +40 -40
  100. package/src/cvcs/riskSeverityBand.v1.0.0.json +139 -0
  101. package/src/cvcs/roiScope.v1.0.0.json +111 -3
  102. package/src/cvcs/roiStatus.v1.0.0.json +18 -10
  103. package/src/cvcs/romanticRelationshipChangeType.v1.0.0.json +2 -1
  104. package/src/cvcs/serviceCategories.v1.0.0.json +44 -44
  105. package/src/cvcs/serviceDeliveryChannel.v1.0.0.json +147 -0
  106. package/src/cvcs/serviceMechanisms.v1.0.0.json +36 -36
  107. package/src/cvcs/serviceStates.v1.0.0.json +40 -40
  108. package/src/cvcs/sessionTemplate.v1.0.0.json +261 -0
  109. package/src/cvcs/sexProviderSubrole.v1.0.0.json +35 -28
  110. package/src/cvcs/smtType.v1.0.0.json +40 -40
  111. package/src/cvcs/sourceCategory.v1.1.0.json +8 -1
  112. package/src/cvcs/sourceInstrument.v1.0.0.json +458 -0
  113. package/src/cvcs/sourceSystem.v1.0.0.json +203 -0
  114. package/src/cvcs/subjectType.v1.0.0.json +80 -0
  115. package/src/cvcs/traffickingRelevantRole.v1.0.0.json +104 -0
  116. package/src/cvcs/userRoles.v1.0.0.json +203 -0
  117. package/src/cvcs/victimStatusFamily.v1.0.0.json +40 -40
  118. package/src/cvcs/whyNots.v1.0.0.json +385 -0
  119. package/src/generated/cvc-enums.ts +1121 -127
  120. package/src/index.ts +20 -0
  121. package/src/mongo/catalog.ts +65 -0
  122. package/src/mongo/contract.ts +157 -0
  123. package/src/mongo/index.ts +343 -0
  124. package/src/mongo/similarity.ts +133 -0
  125. package/src/mongo/uri.ts +53 -0
  126. package/src/schemas/common.ts +4 -0
  127. package/src/services/cvcRegistryService.ts +1 -1
  128. package/src/cvcs/riskBand.v1.0.0.json +0 -98
  129. package/dist/{cvcEntry-BCj1OWqL.d.cts → cvcEntry-0BIB9sen.d.cts} +8 -8
  130. package/dist/{cvcEntry-BCj1OWqL.d.ts → cvcEntry-0BIB9sen.d.ts} +8 -8
@@ -572,11 +572,13 @@ const SOT_SPECS: readonly SotSpec[] = [
572
572
  // codes + 1 missingness root + 3 canonical missingness children = 11.
573
573
  // CVC number is PROVISIONAL pending codebook-session ratification.
574
574
  { file: "relationshipConcern.v1.0.0.json", domain: "relationship_concern", expectedCount: 11 },
575
- // PROVISIONAL CVC-232 recency_band — 6 time-window bands (within_3_months,
576
- // months_3_to_6, months_6_to_12, one_year_or_more, years_3_to_10,
577
- // ten_plus_years) + 1 missingness root + 3 canonical missingness children = 10.
578
- // CVC number is PROVISIONAL pending codebook-session ratification.
579
- { file: "recencyBand.v1.0.0.json", domain: "recency_band", expectedCount: 10 },
575
+ // CVC-137 recency_band — the CANONICAL 8-band key system adopted in 0.8.13
576
+ // (w3m, m3_6, m6_12, y1p, y1_3, y3_10, y10p, ylt3 — the lowercase
577
+ // transliterations of W3M/M3_6/M6_12/Y1P/Y1_3/Y3_10/Y10P/YLT3, carried
578
+ // verbatim in `canonicalCode`) + 1 missingness root + 3 canonical missingness
579
+ // children = 12. Replaces the 6 semantic slugs shipped before 0.8.13; all 6
580
+ // map 1:1 onto a canonical band, and y1_3 / ylt3 are net-new.
581
+ { file: "recencyBand.v1.0.0.json", domain: "recency_band", expectedCount: 12 },
580
582
  // PROVISIONAL CVC-233 housing_subsidy_types — 12 HMIS-aligned subsidy types
581
583
  // (housing_choice_voucher, public_housing, project_based_rental_assistance,
582
584
  // permanent_supportive_housing, rapid_rehousing_assistance,
@@ -586,7 +588,7 @@ const SOT_SPECS: readonly SotSpec[] = [
586
588
  // root + 3 canonical missingness children = 16. CVC number is PROVISIONAL
587
589
  // pending ratification.
588
590
  { file: "housingSubsidyTypes.v1.0.0.json", domain: "housing_subsidy_types", expectedCount: 16 },
589
- { file: "assertionDomain.v1.1.0.json", domain: "assertion_domain", expectedCount: 71 },
591
+ { file: "assertionDomain.v1.1.0.json", domain: "assertion_domain", expectedCount: 68 },
590
592
  { file: "activityType.v1.0.0.json", domain: "activity_type", expectedCount: 14 },
591
593
  { file: "provenanceSourceId.v1.0.0.json", domain: "provenance_source_id", expectedCount: 13 },
592
594
  { file: "radiusBucket.v1.0.0.json", domain: "radius_bucket", expectedCount: 9 },
@@ -608,7 +610,6 @@ const SOT_SPECS: readonly SotSpec[] = [
608
610
  // 5 bands (severe/elevated/review/watch/stable — `stable` is the cutoff-less
609
611
  // fall-through floor, so the count is 5, NOT the 4 numeric BandCutoffs
610
612
  // fields) + 4 missingness = 9
611
- { file: "riskBand.v1.0.0.json", domain: "risk_band", expectedCount: 9 },
612
613
  // ─── 0.8.12 vocabulary batch ───
613
614
  // CANONICAL Notion CVC-133 `core - functions` (verified v1.0): 77 functions
614
615
  // + 4 missingness = 81
@@ -618,12 +619,53 @@ const SOT_SPECS: readonly SotSpec[] = [
618
619
  { file: "needsAssessmentChangeType.v1.0.0.json", domain: "needs_assessment_change_type", expectedCount: 13 },
619
620
  // 15 ROI scope items (@pave/domain ROI_SCOPE_KEYS — the PAVE-seed-attested
620
621
  // subset of the prototype's 27-item UI superset) + 4 = 19
621
- { file: "roiScope.v1.0.0.json", domain: "roi_scope", expectedCount: 19 },
622
+ { file: "roiScope.v1.0.0.json", domain: "roi_scope", expectedCount: 31 },
622
623
  // 5 stored-ROI lifecycle states (@pave/domain ROI_STATUSES) + 4 = 9
623
624
  { file: "roiStatus.v1.0.0.json", domain: "roi_status", expectedCount: 9 },
624
625
  // 2 HMIS FY2026 "P2 Referrals Provided" outcomes (attained / not_attained)
625
626
  // + 4 = 6. The not-attained REASON is a separate axis, not folded in here.
626
627
  { file: "coreReferralOutcome.v1.0.0.json", domain: "core_referral_outcome", expectedCount: 6 },
628
+ // ─── 0.8.13 canonical CVC batch ───
629
+ { file: "coreDhState.v1.0.0.json", domain: "dh_state", expectedCount: 9 },
630
+ // 0.8.14: 214 -> 219 (catalog refresh a596eb9 -> 84a1b67; +5 mints, 0 withdrawn).
631
+ { file: "coreIndicators.v1.0.0.json", domain: "core_indicators", expectedCount: 219 },
632
+ { file: "riskSeverityBand.v1.0.0.json", domain: "risk_severity_band", expectedCount: 9 },
633
+ { file: "adminRoles.v1.0.0.json", domain: "admin_roles", expectedCount: 14 },
634
+ { file: "userRoles.v1.0.0.json", domain: "user_roles", expectedCount: 19 },
635
+ { file: "hmisCurrentLivingSituation.v1.0.0.json", domain: "hmis_current_living_situation", expectedCount: 33 },
636
+ { file: "juvenileJusticeEpisodeType.v1.0.0.json", domain: "juvenile_justice_episode_type", expectedCount: 9 },
637
+ { file: "incarcerationEpisodeType.v1.0.0.json", domain: "incarceration_episode_type", expectedCount: 9 },
638
+ { file: "exploitationType.v1.0.0.json", domain: "exploitation_type", expectedCount: 9 },
639
+ { file: "sourceSystem.v1.0.0.json", domain: "source_system", expectedCount: 19 },
640
+ { file: "sourceInstrument.v1.0.0.json", domain: "source_instrument", expectedCount: 41 },
641
+ { file: "poPetitionBasis.v1.0.0.json", domain: "po_petition_basis", expectedCount: 8 },
642
+ { file: "poStatus.v1.0.0.json", domain: "po_status", expectedCount: 12 },
643
+ { file: "poViolationStatus.v1.0.0.json", domain: "po_violation_status", expectedCount: 6 },
644
+ { file: "sessionTemplate.v1.0.0.json", domain: "session_template", expectedCount: 23 },
645
+ { file: "serviceDeliveryChannel.v1.0.0.json", domain: "service_delivery_channel", expectedCount: 11 },
646
+ { file: "whyNots.v1.0.0.json", domain: "why_nots", expectedCount: 32 },
647
+ // CVC-182 — 249 countries (codes MINTED; upstream Code column is blank) + 1
648
+ // missingness root + 3 canonical missingness children (Unknown / Declined to
649
+ // asnwer / Not collected, carried verbatim from the codebook) = 253.
650
+ { file: "citizenship.v1.0.0.json", domain: "citizenship", expectedCount: 253 },
651
+ // CVC-235 — 4 L1 trafficking-relevant roles + 1 missingness root + 3 canonical
652
+ // missingness children = 8.
653
+ {
654
+ file: "traffickingRelevantRole.v1.0.0.json",
655
+ domain: "trafficking_relevant_role",
656
+ expectedCount: 8,
657
+ },
658
+ // ─── GDR §10.1 CAR-contract vocabularies (provisional 900-block; PAVE
659
+ // @pave/domain verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish). ───
660
+ // 3 lifecycle states (@pave/domain ASSERTION_STATUSES) + 4 missingness = 7
661
+ { file: "assertionStatus.v1.0.0.json", domain: "assertion_status", expectedCount: 7 },
662
+ // 4 actor classes (@pave/domain CREATED_BY_SYSTEMS) + 4 missingness = 8
663
+ { file: "createdBySystem.v1.0.0.json", domain: "created_by_system", expectedCount: 8 },
664
+ // 3 entity kinds (@pave/domain SUBJECT_TYPES) + 4 missingness = 7
665
+ { file: "subjectType.v1.0.0.json", domain: "subject_type", expectedCount: 7 },
666
+ // 3 substantive age bands (@pave/domain AGE_BANDS_AT_EVENT minus `unknown`,
667
+ // which maps to the missingness sentinel) + 4 missingness = 7
668
+ { file: "minorAdultStatus.v1.0.0.json", domain: "minor_adult_status", expectedCount: 7 },
627
669
  ] as const;
628
670
 
629
671
  // ─── Helpers ────────────────────────────────────────────────────────────────
@@ -179,7 +179,6 @@ const SOT_FILES: readonly SotFile[] = [
179
179
  { file: "housingSubsidyTypes.v1.0.0.json", expectedDomain: "housing_subsidy_types" },
180
180
  // ─── Risk taxonomy (names-only projection of the @hti/scoring SOT) ───
181
181
  { file: "riskCategory.v1.0.0.json", expectedDomain: "risk_category" },
182
- { file: "riskBand.v1.0.0.json", expectedDomain: "risk_band" },
183
182
  // ─── 0.8.12 vocabulary batch ───
184
183
  { file: "coreFunctions.v1.0.0.json", expectedDomain: "core_functions" },
185
184
  { file: "needsAssessmentChangeType.v1.0.0.json", expectedDomain: "needs_assessment_change_type" },
@@ -187,6 +186,49 @@ const SOT_FILES: readonly SotFile[] = [
187
186
  { file: "roiStatus.v1.0.0.json", expectedDomain: "roi_status" },
188
187
  { file: "coreReferralOutcome.v1.0.0.json", expectedDomain: "core_referral_outcome" },
189
188
  { file: "assertionDomain.v1.1.0.json", expectedDomain: "assertion_domain" },
189
+ // ─── 0.8.13 canonical CVC batch ───
190
+ { file: "coreDhState.v1.0.0.json", expectedDomain: "dh_state" },
191
+ { file: "coreIndicators.v1.0.0.json", expectedDomain: "core_indicators" },
192
+ { file: "riskSeverityBand.v1.0.0.json", expectedDomain: "risk_severity_band" },
193
+ { file: "adminRoles.v1.0.0.json", expectedDomain: "admin_roles" },
194
+ { file: "userRoles.v1.0.0.json", expectedDomain: "user_roles" },
195
+ { file: "hmisCurrentLivingSituation.v1.0.0.json", expectedDomain: "hmis_current_living_situation" },
196
+ { file: "juvenileJusticeEpisodeType.v1.0.0.json", expectedDomain: "juvenile_justice_episode_type" },
197
+ { file: "incarcerationEpisodeType.v1.0.0.json", expectedDomain: "incarceration_episode_type" },
198
+ { file: "exploitationType.v1.0.0.json", expectedDomain: "exploitation_type" },
199
+ { file: "sourceSystem.v1.0.0.json", expectedDomain: "source_system" },
200
+ { file: "sourceInstrument.v1.0.0.json", expectedDomain: "source_instrument" },
201
+ { file: "poPetitionBasis.v1.0.0.json", expectedDomain: "po_petition_basis" },
202
+ { file: "poStatus.v1.0.0.json", expectedDomain: "po_status" },
203
+ { file: "poViolationStatus.v1.0.0.json", expectedDomain: "po_violation_status" },
204
+ { file: "sessionTemplate.v1.0.0.json", expectedDomain: "session_template" },
205
+ { file: "serviceDeliveryChannel.v1.0.0.json", expectedDomain: "service_delivery_channel" },
206
+ { file: "whyNots.v1.0.0.json", expectedDomain: "why_nots" },
207
+ // ─── 0.8.13 held-item resolutions (Job A) ───
208
+ { file: "citizenship.v1.0.0.json", expectedDomain: "citizenship" },
209
+ { file: "traffickingRelevantRole.v1.0.0.json", expectedDomain: "trafficking_relevant_role" },
210
+ // ─── Domains the hand-maintained list previously OMITTED (found by the
211
+ // CVC drift gate, which scans the directory instead of a list). ───
212
+ { file: "activityType.v1.0.0.json", expectedDomain: "activity_type" },
213
+ { file: "childChangeType.v1.0.0.json", expectedDomain: "child_change_type" },
214
+ { file: "contactLinkType.v1.0.0.json", expectedDomain: "contact_link_type" },
215
+ { file: "hivStatus.v1.0.0.json", expectedDomain: "hiv_status" },
216
+ { file: "immigrationLegalStatusChangeType.v1.0.0.json", expectedDomain: "immigration_legal_status_change_type" },
217
+ { file: "mentalHealthStatus.v1.0.0.json", expectedDomain: "mental_health_status" },
218
+ { file: "programEnrollmentChangeType.v1.0.0.json", expectedDomain: "program_enrollment_change_type" },
219
+ { file: "provenanceSourceId.v1.0.0.json", expectedDomain: "provenance_source_id" },
220
+ { file: "radiusBucket.v1.0.0.json", expectedDomain: "radius_bucket" },
221
+ { file: "roiMethod.v1.0.0.json", expectedDomain: "roi_method" },
222
+ { file: "romanticRelationshipChangeType.v1.0.0.json", expectedDomain: "romantic_relationship_change_type" },
223
+ { file: "sessionNoteVisibility.v1.0.0.json", expectedDomain: "session_note_visibility" },
224
+ { file: "specialNeedsDisabilities.v1.0.0.json", expectedDomain: "special_needs_disabilities" },
225
+ { file: "suggestionSource.v1.0.0.json", expectedDomain: "suggestion_source" },
226
+ // ─── GDR §10.1 CAR-contract vocabularies (provisional 900-block; PAVE
227
+ // @pave/domain verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish). ───
228
+ { file: "assertionStatus.v1.0.0.json", expectedDomain: "assertion_status" },
229
+ { file: "createdBySystem.v1.0.0.json", expectedDomain: "created_by_system" },
230
+ { file: "subjectType.v1.0.0.json", expectedDomain: "subject_type" },
231
+ { file: "minorAdultStatus.v1.0.0.json", expectedDomain: "minor_adult_status" },
190
232
  ] as const;
191
233
 
192
234
  function loadSot(file: string): unknown {
@@ -0,0 +1,502 @@
1
+ /**
2
+ * MongoDB connection/collection verifier — unit tests
3
+ *
4
+ * Covers:
5
+ * - env-affinity shape rule (no connection required)
6
+ * - typo vs unseeded severity split
7
+ * - the ordinal-sibling guard (leads-platform-demo2, cypress-tests-3)
8
+ * - lazy-creation semantics (declared collection with no documents)
9
+ * - undeclared collections reported, never fatal
10
+ * - db name embedded in the connection string (auth's shape)
11
+ * - multi-error aggregation, exit(1) vs throwOnFailure
12
+ * - the READ-ONLY guarantee: only listDatabases/listCollections are called
13
+ *
14
+ * Tests inject a fake catalogue, matching how runCvcBootCheck injects exit and
15
+ * logger. The package's test suite stays free of a real MongoDB.
16
+ *
17
+ * NOTE: because the catalogue is faked, these tests cannot prove that the real
18
+ * driver reports a documents-free collection as absent. That premise was
19
+ * verified once, read-only, against the live cluster: thread registers the
20
+ * Mongoose model `AgencyInfo` (collection `agencyinfos`), which exists in
21
+ * neither platform-test nor platform-dev. See co-9mk.
22
+ */
23
+
24
+ import { writeFileSync, unlinkSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { tmpdir } from "node:os";
27
+
28
+ import { describe, it, expect, vi } from "vitest";
29
+
30
+ import { verifyMongo, type MongoCatalog } from "../mongo/index.js";
31
+ import {
32
+ editDistance,
33
+ isOrdinalSibling,
34
+ nearestNames,
35
+ formatSuggestions,
36
+ } from "../mongo/similarity.js";
37
+ import { parseMongoBlock, checkEnvAffinity } from "../mongo/contract.js";
38
+
39
+ // ─── helpers ─────────────────────────────────────────────────────────────────
40
+
41
+ /** A catalogue backed by a plain object, recording every call it receives. */
42
+ function fakeCatalog(shape: Record<string, string[]>): MongoCatalog & {
43
+ calls: string[];
44
+ } {
45
+ const calls: string[] = [];
46
+ return {
47
+ calls,
48
+ async listDatabases() {
49
+ calls.push("listDatabases");
50
+ return Object.keys(shape);
51
+ },
52
+ async listCollections(database: string) {
53
+ calls.push(`listCollections:${database}`);
54
+ return shape[database] ?? [];
55
+ },
56
+ };
57
+ }
58
+
59
+ function writeContract(body: string, variables = "variables: {}"): string {
60
+ const path = join(tmpdir(), `mongo-contract-${Math.random().toString(36).slice(2)}.yaml`);
61
+ writeFileSync(
62
+ path,
63
+ `service: test-svc\nversion: 1\nenvironments: [local, test, dev, prod]\n${variables}\n${body}`,
64
+ "utf8",
65
+ );
66
+ return path;
67
+ }
68
+
69
+ const BASIC_CONTRACT = `mongo:
70
+ env_affinity:
71
+ test: "-test"
72
+ databases:
73
+ - db_var: THREAD_DB
74
+ uri_var: MONGODB_CLUSTER
75
+ collections: [caserecords, households]
76
+ `;
77
+
78
+ async function run(
79
+ contractBody: string,
80
+ env: NodeJS.ProcessEnv,
81
+ catalog: MongoCatalog,
82
+ envName = "local",
83
+ ) {
84
+ const path = writeContract(contractBody);
85
+ try {
86
+ return await verifyMongo(path, {
87
+ catalog,
88
+ env: envName,
89
+ processEnv: env,
90
+ throwOnFailure: true,
91
+ logger: { error: vi.fn(), warn: vi.fn() },
92
+ });
93
+ } finally {
94
+ unlinkSync(path);
95
+ }
96
+ }
97
+
98
+ // ─── similarity primitives ───────────────────────────────────────────────────
99
+
100
+ describe("editDistance", () => {
101
+ it("returns 0 for identical strings", () => {
102
+ expect(editDistance("thread-test", "thread-test")).toBe(0);
103
+ });
104
+
105
+ it("counts a single substitution", () => {
106
+ expect(editDistance("thread-tst", "thread-test")).toBe(1);
107
+ });
108
+
109
+ it("bails out early beyond the bound", () => {
110
+ // Bounded result only needs to exceed max, not be exact.
111
+ expect(editDistance("thread-pr-4821", "platform-prod", 2)).toBeGreaterThan(2);
112
+ });
113
+
114
+ it("scores an adjacent transposition as ONE edit", () => {
115
+ // platform-dve is a transposition of platform-dev. Plain Levenshtein would
116
+ // score 2 and tie with the production name platform-db.
117
+ expect(editDistance("platform-dve", "platform-dev")).toBe(1);
118
+ expect(editDistance("platform-dve", "platform-db")).toBe(2);
119
+ });
120
+ });
121
+
122
+ describe("formatSuggestions", () => {
123
+ it("renders one, two, and three names", () => {
124
+ expect(formatSuggestions(["a"])).toBe('"a"');
125
+ expect(formatSuggestions(["a", "b"])).toBe('"a" or "b"');
126
+ expect(formatSuggestions(["a", "b", "c"])).toBe('"a", "b" or "c"');
127
+ });
128
+ });
129
+
130
+ describe("isOrdinalSibling", () => {
131
+ it("treats leads-platform-demo and demo2 as siblings", () => {
132
+ expect(isOrdinalSibling("leads-platform-demo3", "leads-platform-demo2")).toBe(true);
133
+ expect(isOrdinalSibling("leads-platform-demo", "leads-platform-demo2")).toBe(true);
134
+ });
135
+
136
+ it("treats cypress-tests-4 and cypress-tests-3 as siblings", () => {
137
+ expect(isOrdinalSibling("cypress-tests-4", "cypress-tests-3")).toBe(true);
138
+ });
139
+
140
+ it("does NOT treat a real typo as a sibling", () => {
141
+ expect(isOrdinalSibling("thread-tst", "thread-test")).toBe(false);
142
+ });
143
+
144
+ it("is false for identical names", () => {
145
+ expect(isOrdinalSibling("thread-test", "thread-test")).toBe(false);
146
+ });
147
+ });
148
+
149
+ describe("nearestNames", () => {
150
+ it("finds a one-edit typo", () => {
151
+ expect(nearestNames("thread-tst", ["thread-test", "thread-dev"])).toEqual([
152
+ "thread-test",
153
+ ]);
154
+ });
155
+
156
+ it("returns empty when nothing is close", () => {
157
+ expect(nearestNames("thread-pr-4821", ["thread-test", "platform-dev"])).toEqual([]);
158
+ });
159
+
160
+ it("EXCLUDES ordinal siblings so a new numbered env is never a typo", () => {
161
+ // The guard that keeps a healthy new environment from being grounded.
162
+ expect(nearestNames("leads-platform-demo3", ["leads-platform-demo2"])).toEqual([]);
163
+ expect(nearestNames("cypress-tests-4", ["cypress-tests-3", "cypress-tests-2"])).toEqual([]);
164
+ });
165
+
166
+ it("returns ALL tied candidates rather than guessing", () => {
167
+ // thread-dv is one edit from both thread-dev and the PRODUCTION thread-db.
168
+ // Picking one by iteration order could steer an operator into production.
169
+ expect(nearestNames("thread-dv", ["thread-db", "thread-dev", "thread-test"])).toEqual([
170
+ "thread-db",
171
+ "thread-dev",
172
+ ]);
173
+ });
174
+
175
+ it("prefers the transposed neighbour over an unrelated production name", () => {
176
+ // platform-dve -> platform-dev (transposition, 1) beats platform-db (2).
177
+ expect(nearestNames("platform-dve", ["platform-db", "platform-dev"])).toEqual([
178
+ "platform-dev",
179
+ ]);
180
+ });
181
+ });
182
+
183
+ // ─── contract parsing + env affinity ─────────────────────────────────────────
184
+
185
+ describe("parseMongoBlock", () => {
186
+ it("returns null when no mongo block is declared", () => {
187
+ expect(parseMongoBlock(undefined, "x.yaml")).toBeNull();
188
+ });
189
+
190
+ it("rejects an empty databases list", () => {
191
+ expect(() => parseMongoBlock({ databases: [] }, "x.yaml")).toThrow(/non-empty list/);
192
+ });
193
+
194
+ it("rejects a database missing db_var", () => {
195
+ expect(() =>
196
+ parseMongoBlock({ databases: [{ uri_var: "U", collections: [] }] }, "x.yaml"),
197
+ ).toThrow(/db_var/);
198
+ });
199
+ });
200
+
201
+ describe("checkEnvAffinity", () => {
202
+ it("passes when the suffix matches", () => {
203
+ expect(checkEnvAffinity("thread-test", "THREAD_DB", "test", { test: "-test" })).toBeNull();
204
+ });
205
+
206
+ it("fails a prod-shaped name in a test environment", () => {
207
+ const msg = checkEnvAffinity("platform-db", "PLATFORM_DB", "test", { test: "-test" });
208
+ expect(msg).toContain('must end with "-test"');
209
+ });
210
+
211
+ it("is inert for environments with no declared affinity", () => {
212
+ expect(checkEnvAffinity("anything", "X", "local", { test: "-test" })).toBeNull();
213
+ });
214
+ });
215
+
216
+ // ─── verifyMongo ─────────────────────────────────────────────────────────────
217
+
218
+ describe("verifyMongo", () => {
219
+ it("passes when every database and collection exists", async () => {
220
+ const catalog = fakeCatalog({ "thread-test": ["caserecords", "households"] });
221
+ const report = await run(BASIC_CONTRACT, { THREAD_DB: "thread-test" }, catalog);
222
+ expect(report.ok).toBe(true);
223
+ expect(report.findings).toEqual([]);
224
+ });
225
+
226
+ it("is a no-op success when the contract declares no mongo block", async () => {
227
+ const catalog = fakeCatalog({});
228
+ const report = await run("", {}, catalog);
229
+ expect(report.ok).toBe(true);
230
+ expect(catalog.calls).toEqual([]);
231
+ });
232
+
233
+ it("FATAL: database absent with a near neighbour is a typo", async () => {
234
+ const catalog = fakeCatalog({ "thread-test": ["caserecords", "households"] });
235
+ await expect(
236
+ run(BASIC_CONTRACT, { THREAD_DB: "thread-tst" }, catalog),
237
+ ).rejects.toThrow(/does not exist\. Did you mean "thread-test"\?/);
238
+ });
239
+
240
+ it("WARN: database absent with no neighbour is an unseeded environment", async () => {
241
+ const catalog = fakeCatalog({ "thread-test": ["caserecords"] });
242
+ const report = await run(BASIC_CONTRACT, { THREAD_DB: "thread-pr-4821" }, catalog);
243
+ expect(report.ok).toBe(true);
244
+ expect(report.findings).toHaveLength(1);
245
+ expect(report.findings[0]).toMatchObject({
246
+ severity: "warn",
247
+ kind: "db_absent_unseeded",
248
+ });
249
+ });
250
+
251
+ it("WARN (not fatal): a legitimately-numbered new environment boots", async () => {
252
+ // The regression guard. demo3 is one edit from demo2 -- must NOT be fatal.
253
+ const contract = `mongo:
254
+ databases:
255
+ - db_var: LEADS_DB
256
+ uri_var: MONGO_LEADS_URI
257
+ collections: [leads]
258
+ `;
259
+ const catalog = fakeCatalog({ "leads-platform-demo2": ["leads"] });
260
+ const report = await run(contract, { LEADS_DB: "leads-platform-demo3" }, catalog);
261
+ expect(report.ok).toBe(true);
262
+ expect(report.findings[0].kind).toBe("db_absent_unseeded");
263
+ });
264
+
265
+ it("FATAL: env-affinity violation, without probing the database", async () => {
266
+ const catalog = fakeCatalog({ "platform-db": ["users"] });
267
+ await expect(
268
+ run(BASIC_CONTRACT, { THREAD_DB: "platform-db" }, catalog, "test"),
269
+ ).rejects.toThrow(/must end with "-test"/);
270
+ // Shape violations short-circuit: the database is never inspected.
271
+ expect(catalog.calls).not.toContain("listCollections:platform-db");
272
+ });
273
+
274
+ it("WARN: declared collection with no documents (lazy creation)", async () => {
275
+ // thread's `agencyinfos`: model registered, collection never created.
276
+ const contract = `mongo:
277
+ databases:
278
+ - db_var: PLATFORM_DB
279
+ uri_var: MONGODB_CLUSTER
280
+ collections: [users, agencyinfos]
281
+ `;
282
+ const catalog = fakeCatalog({ "platform-test": ["users"] });
283
+ const report = await run(contract, { PLATFORM_DB: "platform-test" }, catalog);
284
+ expect(report.ok).toBe(true);
285
+ expect(report.findings).toHaveLength(1);
286
+ expect(report.findings[0]).toMatchObject({
287
+ severity: "warn",
288
+ kind: "collection_absent_unseeded",
289
+ collection: "agencyinfos",
290
+ });
291
+ });
292
+
293
+ it("FATAL: declared collection that is a typo of an existing one", async () => {
294
+ const contract = `mongo:
295
+ databases:
296
+ - db_var: THREAD_DB
297
+ uri_var: MONGODB_CLUSTER
298
+ collections: [caserecord]
299
+ `;
300
+ const catalog = fakeCatalog({ "thread-test": ["caserecords"] });
301
+ await expect(
302
+ run(contract, { THREAD_DB: "thread-test" }, catalog),
303
+ ).rejects.toThrow(/"caserecord" does not exist\. Did you mean "caserecords"\?/);
304
+ });
305
+
306
+ it("WARN: collections present in Mongo but undeclared", async () => {
307
+ const catalog = fakeCatalog({
308
+ "thread-test": ["caserecords", "households", "counters"],
309
+ });
310
+ const report = await run(BASIC_CONTRACT, { THREAD_DB: "thread-test" }, catalog);
311
+ expect(report.ok).toBe(true);
312
+ expect(report.findings).toHaveLength(1);
313
+ expect(report.findings[0]).toMatchObject({
314
+ kind: "collection_undeclared",
315
+ collection: "counters",
316
+ });
317
+ });
318
+
319
+ it("an empty collections list checks the database NAME only", async () => {
320
+ // Incremental adoption: expansion reaches the leads databases but cannot
321
+ // practically enumerate their collections. listCollections must not run.
322
+ const contract = `mongo:
323
+ databases:
324
+ - db_var: LEADS_DB
325
+ uri_var: MONGO_LEADS_URI
326
+ collections: []
327
+ `;
328
+ const catalog = fakeCatalog({ "leads-platform": ["leads", "dataaccessrules"] });
329
+ const report = await run(contract, { LEADS_DB: "leads-platform" }, catalog);
330
+ expect(report.ok).toBe(true);
331
+ expect(report.findings).toEqual([]);
332
+ expect(catalog.calls).toEqual(["listDatabases"]);
333
+ });
334
+
335
+ it("an empty collections list still catches a database typo", async () => {
336
+ const contract = `mongo:
337
+ databases:
338
+ - db_var: LEADS_DB
339
+ uri_var: MONGO_LEADS_URI
340
+ collections: []
341
+ `;
342
+ const catalog = fakeCatalog({ "leads-platform": [] });
343
+ await expect(
344
+ run(contract, { LEADS_DB: "leads-platfrom" }, catalog),
345
+ ).rejects.toThrow(/Did you mean "leads-platform"\?/);
346
+ });
347
+
348
+ it("FATAL: required db_var missing from the environment", async () => {
349
+ const catalog = fakeCatalog({ "thread-test": [] });
350
+ await expect(run(BASIC_CONTRACT, {}, catalog)).rejects.toThrow(
351
+ /THREAD_DB: required by mongo contract but not set/,
352
+ );
353
+ });
354
+
355
+ it("SKIPS an optional database that is not configured", async () => {
356
+ // thread's PAVE_DB is `required: false`; its absence must not fail boot.
357
+ const variables = [
358
+ "variables:",
359
+ " PAVE_DB:",
360
+ " type: string",
361
+ " required: false",
362
+ " secret: false",
363
+ " description: optional pave db",
364
+ ].join("\n");
365
+ const contract = `mongo:
366
+ databases:
367
+ - db_var: PAVE_DB
368
+ uri_var: MONGODB_CLUSTER
369
+ collections: [agencies]
370
+ `;
371
+ const catalog = fakeCatalog({ "pave-test": ["agencies"] });
372
+ const path = writeContract(contract, variables);
373
+ try {
374
+ const report = await verifyMongo(path, {
375
+ catalog,
376
+ env: "local",
377
+ processEnv: {},
378
+ throwOnFailure: true,
379
+ logger: { error: vi.fn(), warn: vi.fn() },
380
+ });
381
+ expect(report.ok).toBe(true);
382
+ expect(report.findings).toEqual([]);
383
+ // Nothing was configured, so nothing was probed.
384
+ expect(catalog.calls).toEqual([]);
385
+ } finally {
386
+ unlinkSync(path);
387
+ }
388
+ });
389
+
390
+ it("applies the contract's per-environment default", async () => {
391
+ // thread declares PLATFORM_DB.default.prod: platform-prod. Reading
392
+ // process.env alone would miss it and report a false fatal.
393
+ const variables = [
394
+ "variables:",
395
+ " PLATFORM_DB:",
396
+ " type: string",
397
+ " required: true",
398
+ " secret: false",
399
+ " description: platform db",
400
+ " default:",
401
+ " prod: platform-prod",
402
+ ].join("\n");
403
+ const contract = `mongo:
404
+ databases:
405
+ - db_var: PLATFORM_DB
406
+ uri_var: MONGODB_CLUSTER
407
+ collections: [users]
408
+ `;
409
+ const catalog = fakeCatalog({ "platform-prod": ["users"] });
410
+ const path = writeContract(contract, variables);
411
+ try {
412
+ const report = await verifyMongo(path, {
413
+ catalog,
414
+ env: "prod",
415
+ processEnv: {}, // deliberately empty: the default must supply the name
416
+ throwOnFailure: true,
417
+ logger: { error: vi.fn(), warn: vi.fn() },
418
+ });
419
+ expect(report.ok).toBe(true);
420
+ expect(catalog.calls).toContain("listCollections:platform-prod");
421
+ } finally {
422
+ unlinkSync(path);
423
+ }
424
+ });
425
+
426
+ it("parses the database name out of the URI when db_var === uri_var", async () => {
427
+ // auth's shape: LEADS_MONGODB_URI embeds the database name.
428
+ const contract = `mongo:
429
+ databases:
430
+ - db_var: LEADS_MONGODB_URI
431
+ uri_var: LEADS_MONGODB_URI
432
+ collections: [leads]
433
+ `;
434
+ const catalog = fakeCatalog({ "leads-platform-test": ["leads"] });
435
+ const report = await run(
436
+ contract,
437
+ { LEADS_MONGODB_URI: "mongodb+srv://u:p@c.mongodb.net/leads-platform-test?w=1" },
438
+ catalog,
439
+ );
440
+ expect(report.ok).toBe(true);
441
+ });
442
+
443
+ it("FATAL: db_var === uri_var but the URI carries no database name", async () => {
444
+ const contract = `mongo:
445
+ databases:
446
+ - db_var: LEADS_MONGODB_URI
447
+ uri_var: LEADS_MONGODB_URI
448
+ collections: [leads]
449
+ `;
450
+ const catalog = fakeCatalog({});
451
+ await expect(
452
+ run(contract, { LEADS_MONGODB_URI: "mongodb://localhost:27017" }, catalog),
453
+ ).rejects.toThrow(/carries no database name/);
454
+ });
455
+
456
+ it("aggregates every fatal finding before failing", async () => {
457
+ const contract = `mongo:
458
+ databases:
459
+ - db_var: A_DB
460
+ uri_var: U
461
+ collections: []
462
+ - db_var: B_DB
463
+ uri_var: U
464
+ collections: []
465
+ `;
466
+ const catalog = fakeCatalog({ "a-test": [] });
467
+ await expect(run(contract, {}, catalog)).rejects.toThrow(
468
+ /2 fatal finding\(s\)[\s\S]*A_DB[\s\S]*B_DB/,
469
+ );
470
+ });
471
+
472
+ it("calls exit(1) rather than throwing when throwOnFailure is unset", async () => {
473
+ const catalog = fakeCatalog({ "thread-test": [] });
474
+ const exit = vi.fn() as unknown as (code: number) => never;
475
+ const logger = { error: vi.fn(), warn: vi.fn() };
476
+ const path = writeContract(BASIC_CONTRACT);
477
+ try {
478
+ await verifyMongo(path, {
479
+ catalog,
480
+ env: "local",
481
+ processEnv: { THREAD_DB: "thread-tst" },
482
+ exit,
483
+ logger,
484
+ });
485
+ } finally {
486
+ unlinkSync(path);
487
+ }
488
+ expect(exit).toHaveBeenCalledWith(1);
489
+ expect(logger.error).toHaveBeenCalledOnce();
490
+ });
491
+
492
+ it("READ-ONLY: issues only listDatabases and listCollections", async () => {
493
+ const catalog = fakeCatalog({ "thread-test": ["caserecords", "households"] });
494
+ await run(BASIC_CONTRACT, { THREAD_DB: "thread-test" }, catalog);
495
+ expect(catalog.calls).toEqual(["listDatabases", "listCollections:thread-test"]);
496
+ // The MongoCatalog interface exposes no write operation at all.
497
+ expect(Object.keys(catalog).filter((k) => k !== "calls").sort()).toEqual([
498
+ "listCollections",
499
+ "listDatabases",
500
+ ]);
501
+ });
502
+ });