@htilabs/platform-common-models 0.17.0 → 0.18.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 (71) hide show
  1. package/dist/agency-BHv54o79.d.ts +484 -0
  2. package/dist/agency-Ca4pCOOf.d.ts +342 -0
  3. package/dist/agency-DYCv839V.d.cts +342 -0
  4. package/dist/agency-Djp57S71.d.cts +484 -0
  5. package/dist/constants/index.cjs +952 -0
  6. package/dist/constants/index.cjs.map +1 -1
  7. package/dist/constants/index.d.cts +3 -1
  8. package/dist/constants/index.d.ts +3 -1
  9. package/dist/constants/index.js +920 -0
  10. package/dist/constants/index.js.map +1 -1
  11. package/dist/{cvcEntry-ctHTp2df.d.cts → cvcEntry-0BIB9sen.d.cts} +36 -36
  12. package/dist/{cvcEntry-ctHTp2df.d.ts → cvcEntry-0BIB9sen.d.ts} +36 -36
  13. package/dist/cvcs/index.cjs +114 -62
  14. package/dist/cvcs/index.cjs.map +1 -1
  15. package/dist/cvcs/index.d.cts +112 -59
  16. package/dist/cvcs/index.d.ts +112 -59
  17. package/dist/cvcs/index.js +114 -62
  18. package/dist/cvcs/index.js.map +1 -1
  19. package/dist/enums/index.cjs +1 -0
  20. package/dist/enums/index.cjs.map +1 -1
  21. package/dist/enums/index.d.cts +2 -1
  22. package/dist/enums/index.d.ts +2 -1
  23. package/dist/enums/index.js +1 -0
  24. package/dist/enums/index.js.map +1 -1
  25. package/dist/{index-4DiJrn7y.d.ts → index-CDoqrfc1.d.ts} +1 -1
  26. package/dist/{index-qreOzXYS.d.cts → index-Zu_mOJRn.d.cts} +1 -1
  27. package/dist/index.cjs +1654 -1077
  28. package/dist/index.cjs.map +1 -1
  29. package/dist/index.d.cts +6 -4
  30. package/dist/index.d.ts +6 -4
  31. package/dist/index.js +1600 -1076
  32. package/dist/index.js.map +1 -1
  33. package/dist/models/index.d.cts +2 -2
  34. package/dist/models/index.d.ts +2 -2
  35. package/dist/org-type-BYQb9Qzq.d.ts +366 -0
  36. package/dist/org-type-D_FG4KdN.d.cts +366 -0
  37. package/dist/{platform-auth-CrF5U_JH.d.cts → platform-auth-CvAYFVhK.d.cts} +39 -0
  38. package/dist/{platform-auth-CrF5U_JH.d.ts → platform-auth-CvAYFVhK.d.ts} +39 -0
  39. package/dist/schemas/index.cjs +977 -2
  40. package/dist/schemas/index.cjs.map +1 -1
  41. package/dist/schemas/index.d.cts +14 -11
  42. package/dist/schemas/index.d.ts +14 -11
  43. package/dist/schemas/index.js +962 -1
  44. package/dist/schemas/index.js.map +1 -1
  45. package/dist/types/index.d.cts +2 -2
  46. package/dist/types/index.d.ts +2 -2
  47. package/dist/validation/index.cjs +894 -2
  48. package/dist/validation/index.cjs.map +1 -1
  49. package/dist/validation/index.d.cts +5 -1
  50. package/dist/validation/index.d.ts +5 -1
  51. package/dist/validation/index.js +884 -1
  52. package/dist/validation/index.js.map +1 -1
  53. package/package.json +26 -27
  54. package/src/__tests__/__snapshots__/cvc-sot.snap +2 -2
  55. package/src/__tests__/cvc-sot-snapshot.test.ts +5 -5
  56. package/src/__tests__/cvc-structural.test.ts +1 -1
  57. package/src/__tests__/org-type-contract.test.ts +1353 -0
  58. package/src/__tests__/referral-entity-category-canon.test.ts +255 -81
  59. package/src/constants/ic.ts +45 -0
  60. package/src/constants/index.ts +1 -0
  61. package/src/constants/org-type.ts +703 -0
  62. package/src/cvcs/index.ts +1 -1
  63. package/src/cvcs/{referralEntityCategory.v1.1.0.json → referralEntityCategory.v1.2.0.json} +111 -59
  64. package/src/generated/cvc-enums.ts +2 -1
  65. package/src/index.ts +23 -0
  66. package/src/schemas/agency.ts +481 -0
  67. package/src/schemas/index.ts +24 -0
  68. package/src/validation/agency.ts +119 -0
  69. package/src/validation/index.ts +1 -0
  70. package/dist/team-C4LJ5Tex.d.cts +0 -333
  71. package/dist/team-C4LJ5Tex.d.ts +0 -333
@@ -0,0 +1,703 @@
1
+ /**
2
+ * @htilabs/platform-common-models — Organization type (CVC-48, organization half)
3
+ *
4
+ * THE ONE PLACE an agency's / organization's type is defined and read.
5
+ *
6
+ * ## Ruling of record (Crysta, 2026-10-05 — platform-common #187)
7
+ *
8
+ * Agency type = `core-referral_entity_category` (CVC-48). It is set ONCE on
9
+ * the Org in the Admin Hub ("Organization Type", `direct`); the Agency (an
10
+ * Org's participation on an Account) carries it from the Org; every reader
11
+ * in every app joins on the KEY. No reader guesses the type from free text.
12
+ *
13
+ * Before this module, "agency type" existed four ways across the platform —
14
+ * free text on Thread's `Agency.type`, a positional number on
15
+ * `Organization.type`, the correct CVC-48 key that nothing read, and a
16
+ * free-text recogniser (Thread's `FREE_TEXT_TYPE_MATCHERS`) that the ROI gate,
17
+ * the mandatory-report authority set and the default session role all sat on
18
+ * top of. PAVE kept its own `VSP_TYPE_IDS` in a third spelling. This module
19
+ * replaces all of those with ONE vocabulary (the SOT keys) and ONE set of
20
+ * ruling-backed classifiers over it, so Thread and PAVE answer the same
21
+ * question the same way.
22
+ *
23
+ * ## IC-58 is the concept; CVC-48 is its only codeset
24
+ *
25
+ * IC-58 (Information Concept "Referral Entity Category") says WHAT the thing
26
+ * is; CVC-48 says WHICH VALUES are allowed. The `IC_58_*` constants in
27
+ * `./ic.ts` (`IC_58_REFERRAL_ENTITY`, `IC_58_LABELS`, `IC_58_ORG_TYPE_GROUPS`,
28
+ * `IC_58_EXTERNAL_TIERED`) are NOT a vocabulary of their own: they are CVC-48's
29
+ * own hierarchy written as positional numbers (0–31) for Thread's
30
+ * `Organization.type` and `CaseRecord.referralEntity`. They are deprecated for
31
+ * org-type use in favour of this module and stay exported only so the
32
+ * numbers already stored can be read. {@link LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY}
33
+ * is the one-way bridge (number → CVC-48 key), row for row by label;
34
+ * {@link resolveOrgTypeKeyFromLegacyNumeric} applies it. (Canon's 2025 PAVE
35
+ * pick-list, CVC-86, is a different legacy list — deprecated 2026-09-28 and
36
+ * kept in the records repo as its own crosswalk; it is not in this package.)
37
+ *
38
+ * ## What is and is not derived from the type
39
+ *
40
+ * - DERIVED (this module): sector membership (victim-serving / law
41
+ * enforcement / legal / healthcare / mandated-report authority), the
42
+ * default CVC-69 session role of a person acting FROM an agency of this
43
+ * type, labels, and spelling resolution (key ↔ Sean-spec enum constant ↔
44
+ * canon dotted code ↔ positional code ↔ legacy number).
45
+ * - NOT derived — captured on the org record, never inferred: `vsp` (the
46
+ * "is a DV/SA victim service provider" fact HMIS 2.01 needs — captured in
47
+ * the Admin Hub, UDD Org Data Object ruling 2026-10-05; CVC-48 ruling
48
+ * 2026-08-20 on 02-06-02-00), `vsp_private_nonprofit`, `apps_used`, and
49
+ * the as-built `requires_roi` (informational, GDR § 5.17 clause 2 — not
50
+ * one of the shared organization-type fields). The type only PROPOSES
51
+ * `vsp` ({@link orgTypeDefaultVsp} — the Admin Hub's pre-fill; set when
52
+ * HTI Labs affirms or changes it there, Crysta 2026-10-08); a stored
53
+ * boolean always wins. See `schemas/agency.ts`. (ORG-TYPE-REVIEW-ROUND-2026-10-08)
54
+ *
55
+ * ## Vocabulary
56
+ *
57
+ * CVC-48 is a referral-entity vocabulary whose organization half (canon codes
58
+ * `02-XX-YY-ZZ`) doubles as the org-type typology. {@link ORG_TYPE_KEYS} is
59
+ * that half: Level 1B sector headings (not selectable — a child is required
60
+ * everywhere, including agency onboarding; ruled 2026-08-20) plus Level 2 /
61
+ * Level 3 leaves. The Individual branch (Level 1A) and the missingness leaves
62
+ * are NOT org types; {@link AGENCY_TYPE_KEYS} additionally admits `unknown`
63
+ * as the ONE pre-backfill placeholder a stored agency may carry — the Admin
64
+ * Hub never offers it.
65
+ *
66
+ * The SOT JSON (~28 KB) is imported here so `./constants` stays
67
+ * mongoose-free for edge consumers; the cost is that JSON in the constants
68
+ * bundle. `enumConstant` is a generator column for spelling resolution only —
69
+ * it is not in the seeder's hashable fields and is never written to
70
+ * `cvc_entities`.
71
+ */
72
+
73
+ import referralEntityCategorySot from "../cvcs/referralEntityCategory.v1.2.0.json" with { type: "json" };
74
+ import type {
75
+ IncidentParticipationRoleKey,
76
+ ReferralEntityCategoryKey,
77
+ ReferralEntityCategoryKeys,
78
+ } from "../generated/cvc-enums.js";
79
+
80
+ // ─── SOT entry shape (the v1.1.0 generator's per-entry columns) ─────────────
81
+
82
+ interface OrgTypeSotEntry {
83
+ code: string;
84
+ key: string;
85
+ title: string;
86
+ selectable: boolean;
87
+ parentCode: string | null;
88
+ childCodes: string[];
89
+ definition: string | null;
90
+ /** Canon's 4-segment code (`02-03-01-00`); absent on the house missingness root. */
91
+ canonicalCode?: string;
92
+ /** Canon's Sean-spec JSON constant (`ORGANIZATION_JUSTICE_CHILDWELFARE`). */
93
+ enumConstant?: string;
94
+ }
95
+
96
+ const ENTRIES =
97
+ referralEntityCategorySot.entries as ReadonlyArray<OrgTypeSotEntry>;
98
+ const BY_KEY = new Map(ENTRIES.map((e) => [e.key, e]));
99
+ const BY_CODE = new Map(ENTRIES.map((e) => [e.code, e]));
100
+ const BY_CANON = new Map(
101
+ ENTRIES.filter((e) => e.canonicalCode).map((e) => [
102
+ e.canonicalCode as string,
103
+ e,
104
+ ]),
105
+ );
106
+ const BY_ENUM_CONSTANT = new Map(
107
+ ENTRIES.filter((e) => e.enumConstant).map((e) => [
108
+ e.enumConstant as string,
109
+ e,
110
+ ]),
111
+ );
112
+
113
+ const isOrgHalf = (e: OrgTypeSotEntry): boolean =>
114
+ (e.canonicalCode ?? "").startsWith("02-");
115
+
116
+ // A canon heading is the non-selectable row of the organization half; canon
117
+ // codes them `02-XX-00-00` (codified 2026-08-20: Level 1B is never selectable).
118
+ const isHeading = (e: OrgTypeSotEntry): boolean =>
119
+ isOrgHalf(e) &&
120
+ !e.selectable &&
121
+ /^02-\d\d-00-00$/.test(e.canonicalCode ?? "");
122
+
123
+ // ─── Key sets ───────────────────────────────────────────────────────────────
124
+ //
125
+ // The tuples below are HAND-PINNED literals rather than `ENTRIES.filter(...)`
126
+ // so that the exported TYPES narrow to exactly these keys (a JSON-derived array
127
+ // types as the whole 46-key CVC-48 union, which let `{ type: "anonymous" }`
128
+ // compile — pre-review finding D2). The contract test derives the same sets
129
+ // from the SOT and asserts each tuple equals them, so a re-mirror that adds or
130
+ // retires a leaf fails CI here instead of drifting silently.
131
+
132
+ /** The Level 1B sector headings (never stored as a type; aggregation only). */
133
+ export const ORG_TYPE_HEADING_KEYS = Object.freeze([
134
+ "housing_shelter_continuum",
135
+ "hotlines",
136
+ "justice_protective_systems",
137
+ "health_behavioral_health",
138
+ "education",
139
+ "victim_community_service_providers",
140
+ "coordination_governance",
141
+ "internal",
142
+ "other_entity",
143
+ ] as const satisfies readonly ReferralEntityCategoryKey[]);
144
+ export type OrgTypeHeadingKey = (typeof ORG_TYPE_HEADING_KEYS)[number];
145
+
146
+ /**
147
+ * The org-type keys an Admin Hub picker offers: every CVC-48 organization-half
148
+ * leaf the codebook marks `Selectable` (Level 2 Required + Optional, Level 3
149
+ * Optional), minus the one leaf no admin may pick
150
+ * ({@link ORG_TYPE_NONPICKABLE_LEAF_KEYS}). `school_academic_institution` IS
151
+ * a kind of organization (Level 2 Required under Education) and is offered.
152
+ * `hotline` (02-02-01-00, canon's Level-2 parent of the two hotline children)
153
+ * is carried since 0.18.0 at 048-006-003 — an organization that is a hotline
154
+ * without being national / local has its key.
155
+ */
156
+ export const ORG_TYPE_SELECTABLE_KEYS = Object.freeze([
157
+ "outreach_project",
158
+ "temporary_shelter",
159
+ "residential_project",
160
+ "national_hotline",
161
+ "local_other_hotline",
162
+ "hotline",
163
+ "child_welfare_cps",
164
+ "juvenile_justice",
165
+ "law_enforcement",
166
+ "local_law_enforcement",
167
+ "state_law_enforcement",
168
+ "federal_law_enforcement",
169
+ "tribal_law_enforcement",
170
+ "other_law_enforcement",
171
+ "courts_prosecution",
172
+ "correction_probation",
173
+ "adult_protective_services",
174
+ "inpatient_psychiatric_facility",
175
+ "healthcare_provider",
176
+ "school_academic_institution",
177
+ "child_advocacy_center",
178
+ "victim_service_provider",
179
+ "community_based_service_provider",
180
+ "legal_services_provider",
181
+ "mdt",
182
+ "coalition",
183
+ "employer",
184
+ "benefits_public_assistance_office",
185
+ "other_organization",
186
+ ] as const satisfies readonly ReferralEntityCategoryKey[]);
187
+ export type OrgTypeSelectableKey = (typeof ORG_TYPE_SELECTABLE_KEYS)[number];
188
+
189
+ /**
190
+ * Organization-half leaves the codebook marks Selectable that an Admin Hub
191
+ * picker must NOT offer, yet a stored row may carry: `own_agency_internal`
192
+ * ("Own agency / internal referral", 02-08-01-00). As a REFERRAL value the
193
+ * codebook resolves its meaning THROUGH the receiving agency's type ("HMIS
194
+ * rollup derived from the receiving agency's Agency Type field — IC-58 § III
195
+ * Edge-Case Handling"), so no admin picks it as a kind of organization — the
196
+ * prototype's canonical CVC-48 picker keeps it in its non-pickable annex.
197
+ * But the platform's OWN organization carries it as built (registry row
198
+ * `internal_hti` / HTI Labs, `type: ORGANIZATION_INTERNAL_OWNAGENCY`), and
199
+ * the CVC-69 ruling table's "the platform's own agency → VSP staff" row keys
200
+ * on exactly that stored value. So: storable ({@link AGENCY_TYPE_KEYS}),
201
+ * resolvable, never offered ({@link ORG_TYPE_SELECTABLE_KEYS}).
202
+ */
203
+ export const ORG_TYPE_NONPICKABLE_LEAF_KEYS = Object.freeze([
204
+ "own_agency_internal",
205
+ ] as const satisfies readonly ReferralEntityCategoryKey[]);
206
+
207
+ /** Every CVC-48 key, organization half only (headings + leaves). */
208
+ export const ORG_TYPE_KEYS = Object.freeze([
209
+ ...ORG_TYPE_HEADING_KEYS,
210
+ ...ORG_TYPE_SELECTABLE_KEYS,
211
+ ...ORG_TYPE_NONPICKABLE_LEAF_KEYS,
212
+ ] as const);
213
+ /** A heading OR a leaf. For "what may be stored" see {@link AgencyTypeKey}. */
214
+ export type OrgTypeKey = (typeof ORG_TYPE_KEYS)[number];
215
+
216
+ /**
217
+ * Valid stored values for `Organization.type` (home) / `Agency.type`
218
+ * (mirror): every selectable org-type leaf, the non-pickable leaf the
219
+ * platform's own organization carries ({@link ORG_TYPE_NONPICKABLE_LEAF_KEYS}),
220
+ * plus `unknown` — the pre-backfill placeholder an un-typed row carries until
221
+ * HTI Labs confirms its type (never offered by the Admin Hub; readers treat
222
+ * it as "no sector"). A heading is NOT a valid stored value.
223
+ */
224
+ export const AGENCY_TYPE_KEYS = Object.freeze([
225
+ ...ORG_TYPE_SELECTABLE_KEYS,
226
+ ...ORG_TYPE_NONPICKABLE_LEAF_KEYS,
227
+ "unknown",
228
+ ] as const satisfies readonly ReferralEntityCategoryKey[]);
229
+ export type AgencyTypeKey = (typeof AGENCY_TYPE_KEYS)[number];
230
+
231
+ const ORG_TYPE_KEY_SET: ReadonlySet<string> = new Set(ORG_TYPE_KEYS);
232
+ const AGENCY_TYPE_KEY_SET: ReadonlySet<string> = new Set(AGENCY_TYPE_KEYS);
233
+
234
+ export function isOrgTypeKey(value: unknown): value is OrgTypeKey {
235
+ return typeof value === "string" && ORG_TYPE_KEY_SET.has(value);
236
+ }
237
+
238
+ export function isAgencyTypeKey(value: unknown): value is AgencyTypeKey {
239
+ return typeof value === "string" && AGENCY_TYPE_KEY_SET.has(value);
240
+ }
241
+
242
+ // ─── Spelling resolution ────────────────────────────────────────────────────
243
+
244
+ /**
245
+ * The one lookup both resolvers share: the SOT key (case-insensitive), the
246
+ * Sean-spec enum constant (case-insensitive), the canon dotted code or the
247
+ * positional code (both exact). Never a substring match, never free text.
248
+ */
249
+ function lookup(value: unknown): OrgTypeSotEntry | null {
250
+ if (typeof value !== "string") return null;
251
+ const v = value.trim();
252
+ if (!v) return null;
253
+ return (
254
+ BY_KEY.get(v.toLowerCase()) ??
255
+ BY_ENUM_CONSTANT.get(v.toUpperCase()) ??
256
+ BY_CANON.get(v) ??
257
+ BY_CODE.get(v) ??
258
+ null
259
+ );
260
+ }
261
+
262
+ /**
263
+ * Resolve any of the platform's STRING spellings of an org type to the ONE
264
+ * key. Accepts the SOT key (`child_welfare_cps`), the Sean-spec enum constant
265
+ * the org registry / `agencies.typeId` carry (`ORGANIZATION_JUSTICE_CHILDWELFARE`),
266
+ * the canon dotted code (`02-03-01-00`) or the positional code
267
+ * (`048-007-001-000-000-000-000`). Anything else — including every free-text
268
+ * value the retired recognisers used to guess at, and a legacy NUMBER in any
269
+ * form (`18`, `"18"`) — is `null`. The number has its own, explicit bridge:
270
+ * {@link resolveOrgTypeKeyFromLegacyNumeric}. Case- and whitespace-insensitive;
271
+ * never a substring match.
272
+ */
273
+ export function resolveOrgTypeKey(value: unknown): OrgTypeKey | null {
274
+ const hit = lookup(value);
275
+ return hit && isOrgTypeKey(hit.key) ? hit.key : null;
276
+ }
277
+
278
+ /**
279
+ * Resolve any spelling of a STORABLE agency type: a selectable org-type leaf,
280
+ * or `unknown` (any spelling the missingness leaf has). This is the resolver
281
+ * for reading or backfilling `Agency.type` — a heading
282
+ * (`justice_protective_systems`, `ORGANIZATION_JUSTICE`), a v1.0.0 leaf that
283
+ * became a heading (`education`), an individual referrer or any other
284
+ * missingness row resolves to `null`, exactly as the Mongoose enum and the
285
+ * Zod schemas would refuse it (pre-review finding D1: the previous version
286
+ * returned headings typed as `AgencyTypeKey`). Use {@link resolveOrgTypeKey}
287
+ * when a heading is an acceptable answer (aggregation, labels).
288
+ */
289
+ export function resolveAgencyTypeKey(value: unknown): AgencyTypeKey | null {
290
+ const hit = lookup(value);
291
+ return hit && isAgencyTypeKey(hit.key) ? hit.key : null;
292
+ }
293
+
294
+ // ─── Legacy numeric bridge (Thread `Organization.type` / `CaseRecord.referralEntity`)
295
+
296
+ /**
297
+ * The positional numbers `./ic.ts` `IC_58_REFERRAL_ENTITY` assigned to CVC-48's
298
+ * rows, → the CVC-48 key, row for row by label (`IC_58_LABELS`). One-way:
299
+ * nothing new is ever written as a number. Three numbers name a sector HEADING
300
+ * (17 Education, 19 "Other External", 26 Victim + Community) and
301
+ * therefore resolve to an org type but NOT to a storable agency type — a row
302
+ * Thread defaulted to 19 is an un-typed organization and reads as such
303
+ * until the backfill gives it a leaf. Numbers 2–5 are the Individual branch:
304
+ * referral sources, never org types.
305
+ *
306
+ * **Backfill-only. Not a runtime reader, and never an ROI input.** The ruled
307
+ * shape (Org Data Object, 2026-10-02 / 2026-10-05; platform-common #187) is
308
+ * that the type is set ONCE, as a key, in the Admin Hub, and every reader
309
+ * joins on the key — "no reader guesses from words", and no reader translates
310
+ * numbers either. This table exists so the backfill review can PROPOSE a key
311
+ * for a numeric `Organization.type`; a consumer that still translates numbers
312
+ * at read time (pave's `IC58_TO_REFERRAL_ENTITY_CATEGORY_KEY`, Thread's
313
+ * `Organization.type` itself) retires that path when its rows are backfilled
314
+ * (#187 follow-ups). Whether a share needs a release is decided by the org's
315
+ * attested `vsp` flag, captured in the Admin Hub and never derived from the
316
+ * type (ruling 2026-10-05) — so which key `19` proposes cannot change an ROI
317
+ * answer anywhere. `19` → the `other_entity` HEADING is deliberate: in Thread
318
+ * `19` was the write for "referring organization Unknown / Anonymous"
319
+ * (`UNIDENTIFIED_EXTERNAL_ORG_TYPE`) and the default for every organization
320
+ * created before leaf-only pickers, so it proposes nothing and the review
321
+ * picks the leaf — `other_organization` only when a human says so.
322
+ */
323
+ export const LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY = Object.freeze({
324
+ 0: "unknown",
325
+ 1: "own_agency_internal",
326
+ 2: "self_referred",
327
+ 3: "family_guardian_friend",
328
+ 4: "peer",
329
+ 5: "other_individual",
330
+ 10: "housing_shelter_continuum",
331
+ 11: "hotline",
332
+ 12: "justice_protective_systems",
333
+ 13: "outreach_project",
334
+ 14: "temporary_shelter",
335
+ 15: "residential_project",
336
+ 16: "health_behavioral_health",
337
+ 17: "education",
338
+ 18: "law_enforcement",
339
+ 19: "other_entity",
340
+ 20: "child_welfare_cps",
341
+ 21: "juvenile_justice",
342
+ 22: "courts_prosecution",
343
+ 23: "correction_probation",
344
+ 24: "inpatient_psychiatric_facility",
345
+ 25: "healthcare_provider",
346
+ 26: "victim_community_service_providers",
347
+ 27: "child_advocacy_center",
348
+ 28: "victim_service_provider",
349
+ 29: "community_based_service_provider",
350
+ 30: "employer",
351
+ 31: "benefits_public_assistance_office",
352
+ } as const satisfies Readonly<Record<number, ReferralEntityCategoryKey>>);
353
+ export type LegacyNumericReferralEntity =
354
+ keyof typeof LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY;
355
+
356
+ /**
357
+ * The CVC-48 key a legacy number stands for (any row — individuals included),
358
+ * or `null` for a number the list never had. Accepts a number or its decimal
359
+ * string (`18` / `"18"`), the two forms Thread has stored it in.
360
+ */
361
+ export function resolveReferralEntityKeyFromLegacyNumeric(
362
+ value: unknown,
363
+ ): ReferralEntityCategoryKey | null {
364
+ const n =
365
+ typeof value === "number"
366
+ ? value
367
+ : typeof value === "string" && /^\s*\d{1,2}\s*$/.test(value)
368
+ ? Number(value)
369
+ : NaN;
370
+ if (!Number.isInteger(n)) return null;
371
+ const table: Readonly<Record<number, ReferralEntityCategoryKey>> =
372
+ LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY;
373
+ return table[n] ?? null;
374
+ }
375
+
376
+ /**
377
+ * The ORG TYPE a legacy number stands for — a heading or a leaf — or `null`
378
+ * for the Individual branch, `0` (unknown) and anything unlisted. For "may it
379
+ * be stored as an agency type" pass the result through
380
+ * {@link resolveAgencyTypeKey} (headings → `null`).
381
+ */
382
+ export function resolveOrgTypeKeyFromLegacyNumeric(
383
+ value: unknown,
384
+ ): OrgTypeKey | null {
385
+ const k = resolveReferralEntityKeyFromLegacyNumeric(value);
386
+ return k && isOrgTypeKey(k) ? k : null;
387
+ }
388
+
389
+ // ─── Accessors (any string; `null` on a miss) ───────────────────────────────
390
+
391
+ /** The Sean-spec enum constant for a key (the org registry's spelling). */
392
+ export function orgTypeEnumConstant(key: string): string | null {
393
+ return BY_KEY.get(key)?.enumConstant ?? null;
394
+ }
395
+
396
+ /** The canon dotted code for a key (`02-03-01-00`). */
397
+ export function orgTypeCanonicalCode(key: string): string | null {
398
+ return BY_KEY.get(key)?.canonicalCode ?? null;
399
+ }
400
+
401
+ /** Canon's picker label for a key (`title`); `null` for a key the SOT lacks. */
402
+ export function orgTypeLabel(key: string): string | null {
403
+ return BY_KEY.get(key)?.title ?? null;
404
+ }
405
+
406
+ // ─── Hierarchy ──────────────────────────────────────────────────────────────
407
+
408
+ /**
409
+ * The key and every ancestor, leaf first (`local_law_enforcement` →
410
+ * `law_enforcement` → `justice_protective_systems`). Empty for an unknown key.
411
+ * Guarded against a cyclic or self-referencing `parentCode` in the SOT: the
412
+ * walk stops at the first repeat instead of hanging.
413
+ */
414
+ export function orgTypeAncestry(key: string): ReferralEntityCategoryKey[] {
415
+ const out: ReferralEntityCategoryKey[] = [];
416
+ const seen = new Set<string>();
417
+ let cursor = BY_KEY.get(key);
418
+ while (cursor && !seen.has(cursor.code)) {
419
+ seen.add(cursor.code);
420
+ out.push(cursor.key as ReferralEntityCategoryKey);
421
+ cursor = cursor.parentCode ? BY_CODE.get(cursor.parentCode) : undefined;
422
+ }
423
+ return out;
424
+ }
425
+
426
+ /**
427
+ * Key → parent key, organization half, from the SOT's `parentCode` field —
428
+ * the companion map a consumer uses instead of code-prefix arithmetic
429
+ * (review nit on `fce762f`). The hierarchy is the `parentCode` FIELD, never
430
+ * the positional code's prefix: `national_hotline` / `local_other_hotline`
431
+ * keep their v1.0.0 codes while their parent is now the `hotline` LEAF
432
+ * (048-006-003, carried since 0.18.0), so a child code does not lexically
433
+ * extend its parent's. Headings map to `null`. (`hotline` is the storable
434
+ * leaf — an organization that is a hotline; `hotlines` is the
435
+ * non-storable heading above it. Mind the plural.)
436
+ */
437
+ export const ORG_TYPE_PARENT_KEY: Readonly<
438
+ Record<OrgTypeKey, ReferralEntityCategoryKey | null>
439
+ > = Object.freeze(
440
+ Object.fromEntries(
441
+ ENTRIES.filter(isOrgHalf).map((e) => [
442
+ e.key,
443
+ e.parentCode
444
+ ? ((BY_CODE.get(e.parentCode)?.key as ReferralEntityCategoryKey) ??
445
+ null)
446
+ : null,
447
+ ]),
448
+ ) as Record<OrgTypeKey, ReferralEntityCategoryKey | null>,
449
+ );
450
+
451
+ /**
452
+ * The Level 1B sector heading a key sits under (itself if it is one); `null`
453
+ * for a key whose chain does not end in a heading — `unknown`, the
454
+ * individual referrers, the missingness root (pre-review finding D6: an
455
+ * aggregator keyed on this must skip un-typed agencies, not bucket them under
456
+ * `missingness_root`).
457
+ */
458
+ export function orgTypeSector(key: string): OrgTypeHeadingKey | null {
459
+ const chain = orgTypeAncestry(key);
460
+ if (!chain.length) return null;
461
+ const top = chain[chain.length - 1];
462
+ const entry = BY_KEY.get(top);
463
+ return entry && isHeading(entry) ? (top as OrgTypeHeadingKey) : null;
464
+ }
465
+
466
+ // ─── Sector classifiers (the ruling table) ──────────────────────────────────
467
+ //
468
+ // The rows of the CVC-69 ruling table (OWNER-ROLE-FROM-AGENCY, prototype #703,
469
+ // 2026-10-05) and the canon mandated-report predicate. The sets are
470
+ // hand-pinned (so their TYPES narrow, like the key sets above); the contract
471
+ // test re-derives each subtree-defined set from the SOT hierarchy and fails if
472
+ // a re-mirror adds or moves a leaf, so a new leaf under a heading is caught
473
+ // here rather than silently left out of a classifier.
474
+
475
+ /**
476
+ * Victim-serving organization types: the two Victim + Community leaves whose
477
+ * staff act as victim advocates — `victim_service_provider` and
478
+ * `child_advocacy_center` (CAC ruled under Victim + Community service
479
+ * providers 2026-08-20). `community_based_service_provider` and
480
+ * `legal_services_provider` sit under the same heading but are NOT
481
+ * victim-serving for this question (canon: the residual non-VSP provider; a
482
+ * lawyer's help). `coalition` is a system-level membership body, not a
483
+ * service provider (ruled 2026-08-20). NOTE: this is the TYPE-level default;
484
+ * the org record's own `vsp` attestation decides the HMIS 2.01 / ROI question.
485
+ */
486
+ export const VICTIM_SERVING_ORG_TYPE_KEYS = Object.freeze([
487
+ "victim_service_provider",
488
+ "child_advocacy_center",
489
+ ] as const satisfies readonly OrgTypeSelectableKey[]);
490
+
491
+ /** Law enforcement: the `law_enforcement` leaf and its Level 3 refinements. */
492
+ export const LAW_ENFORCEMENT_ORG_TYPE_KEYS = Object.freeze([
493
+ "law_enforcement",
494
+ "local_law_enforcement",
495
+ "state_law_enforcement",
496
+ "federal_law_enforcement",
497
+ "tribal_law_enforcement",
498
+ "other_law_enforcement",
499
+ ] as const satisfies readonly OrgTypeSelectableKey[]);
500
+
501
+ /** Legal: courts / prosecution, and legal services providers (a lawyer's help). */
502
+ export const LEGAL_ORG_TYPE_KEYS = Object.freeze([
503
+ "courts_prosecution",
504
+ "legal_services_provider",
505
+ ] as const satisfies readonly OrgTypeSelectableKey[]);
506
+
507
+ /**
508
+ * Healthcare incl. behavioral health: the `health_behavioral_health` subtree
509
+ * (the heading is listed so a consumer aggregating by sector can use it; it
510
+ * is never a stored type).
511
+ */
512
+ export const HEALTHCARE_ORG_TYPE_KEYS = Object.freeze([
513
+ "health_behavioral_health",
514
+ "inpatient_psychiatric_facility",
515
+ "healthcare_provider",
516
+ ] as const satisfies readonly OrgTypeKey[]);
517
+
518
+ /**
519
+ * Designated authorities for mandatory / authority reporting: the whole
520
+ * Justice & Protective Systems subtree — child welfare, juvenile justice,
521
+ * every law-enforcement leaf, courts / prosecution, corrections / probation,
522
+ * adult protective services. This is canon's `/^ORGANIZATION_JUSTICE/`
523
+ * predicate over the enum constants, expressed over keys.
524
+ */
525
+ export const REPORT_AUTHORITY_ORG_TYPE_KEYS = Object.freeze([
526
+ "justice_protective_systems",
527
+ "child_welfare_cps",
528
+ "juvenile_justice",
529
+ "law_enforcement",
530
+ "local_law_enforcement",
531
+ "state_law_enforcement",
532
+ "federal_law_enforcement",
533
+ "tribal_law_enforcement",
534
+ "other_law_enforcement",
535
+ "courts_prosecution",
536
+ "correction_probation",
537
+ "adult_protective_services",
538
+ ] as const satisfies readonly OrgTypeKey[]);
539
+
540
+ /**
541
+ * Types that say nothing about a sector: the platform's own organization
542
+ * (`own_agency_internal` as stored on the HTI Labs row; `internal`, its
543
+ * heading) and the pre-backfill `unknown`. This set is the ruling table's
544
+ * "no type / unknown / the platform's own agency → VSP staff" row.
545
+ */
546
+ export const NO_SECTOR_ORG_TYPE_KEYS = Object.freeze([
547
+ "internal",
548
+ "own_agency_internal",
549
+ "unknown",
550
+ ] as const satisfies readonly (OrgTypeKey | "unknown")[]);
551
+
552
+ const asSet = (keys: readonly string[]): ReadonlySet<string> => new Set(keys);
553
+ const VICTIM_SERVING = asSet(VICTIM_SERVING_ORG_TYPE_KEYS);
554
+ const LAW_ENFORCEMENT = asSet(LAW_ENFORCEMENT_ORG_TYPE_KEYS);
555
+ const LEGAL = asSet(LEGAL_ORG_TYPE_KEYS);
556
+ const HEALTHCARE = asSet(HEALTHCARE_ORG_TYPE_KEYS);
557
+ const REPORT_AUTHORITY = asSet(REPORT_AUTHORITY_ORG_TYPE_KEYS);
558
+ const NO_SECTOR = asSet(NO_SECTOR_ORG_TYPE_KEYS);
559
+
560
+ /**
561
+ * Each predicate accepts ANY spelling {@link resolveAgencyTypeKey} accepts and
562
+ * answers `false` for everything it does not recognise — a free-text type is
563
+ * never guessed at.
564
+ */
565
+ export function isVictimServingOrgType(
566
+ type: string | null | undefined,
567
+ ): boolean {
568
+ const k = resolveAgencyTypeKey(type);
569
+ return !!k && VICTIM_SERVING.has(k);
570
+ }
571
+ export function isLawEnforcementOrgType(
572
+ type: string | null | undefined,
573
+ ): boolean {
574
+ const k = resolveAgencyTypeKey(type);
575
+ return !!k && LAW_ENFORCEMENT.has(k);
576
+ }
577
+ export function isLegalOrgType(type: string | null | undefined): boolean {
578
+ const k = resolveAgencyTypeKey(type);
579
+ return !!k && LEGAL.has(k);
580
+ }
581
+ export function isHealthcareOrgType(type: string | null | undefined): boolean {
582
+ const k = resolveAgencyTypeKey(type);
583
+ return !!k && HEALTHCARE.has(k);
584
+ }
585
+ /** Is this type a designated mandatory / authority-report recipient? */
586
+ export function isReportAuthorityOrgType(
587
+ type: string | null | undefined,
588
+ ): boolean {
589
+ const k = resolveAgencyTypeKey(type);
590
+ return !!k && REPORT_AUTHORITY.has(k);
591
+ }
592
+
593
+ /**
594
+ * The type-level DEFAULT for the org record's `vsp` attestation: `true` for
595
+ * `victim_service_provider`, `false` for every other recognised org type,
596
+ * `null` when the type cannot answer — the type is unknown / own-agency
597
+ * (nothing to default from), or it is a `child_advocacy_center` (ruled
598
+ * 2026-10-05: a CAC is victim-serving for the session role and OCAT, but its
599
+ * HMIS VSP standing is whatever the org attests — the registry attests FALSE
600
+ * for the one on file — so a bare CAC type is NOT a default either way; a
601
+ * reader on `null` takes the ROI gate's conservative branch, release
602
+ * required). A stored `vsp` boolean on the org ALWAYS wins; this is only what
603
+ * the Admin Hub pre-fills and what a reader falls back to when the org has
604
+ * not attested.
605
+ */
606
+ export function orgTypeDefaultVsp(
607
+ type: string | null | undefined,
608
+ ): boolean | null {
609
+ const k = resolveAgencyTypeKey(type);
610
+ if (!k || NO_SECTOR.has(k) || k === "child_advocacy_center") return null;
611
+ return k === "victim_service_provider";
612
+ }
613
+
614
+ // ─── Default session role (CVC-69) ──────────────────────────────────────────
615
+
616
+ /**
617
+ * The CVC-69 `incident_participation_roles` key a person acting FROM an
618
+ * agency of this type defaults to — the ruling table on the CVC-69 page
619
+ * (OWNER-ROLE-FROM-AGENCY, prototype #703, 2026-10-05):
620
+ *
621
+ * org attests `vsp: true` → Victim Service provider staff (checked FIRST)
622
+ * victim-serving → Victim Service provider staff
623
+ * law enforcement → Law enforcement personnel
624
+ * courts / prosecution / legal → Legal professional
625
+ * healthcare incl. behavioral health → Healthcare provider staff
626
+ * any other recognised org type → Other Response Personnel
627
+ * no type / unknown / own agency → Victim Service provider staff
628
+ *
629
+ * **This is a non-authoritative UI PRE-FILL, never an authorization input.**
630
+ * It cannot say "no" — the last row is a ruled catch-all, and it also absorbs
631
+ * a value that is PRESENT but unresolvable (legacy free text such as
632
+ * `"Law Enforcement"`). That is the ruling, not an accident: the Personnel
633
+ * roles card records (2026-10-05) "unrecognized or empty types fall back to
634
+ * Victim Service provider staff", the conservative direction for an advocate
635
+ * surface (Swap corrects it by hand). A consumer that needs to KNOW it is
636
+ * looking at the guess calls {@link orgTypeDefaultSessionRoleOrNull} instead.
637
+ * Any VAWA / ROI / VSP gate reads the org's stored `vsp` boolean, never this
638
+ * role (a CAC defaults to `vsp_staff` while its attested `vsp` may be false).
639
+ *
640
+ * Keys are the canonical CVC-69 v1.1.0 spellings (platform-common #186):
641
+ * `vsp_staff`, `law_enforcement_personnel`, `legal_professional`,
642
+ * `healthcare_provider_staff`, `other_response_personnel`. A consumer still
643
+ * on the 0.13.0 spellings (`service_provider_staff`, `responding_officer`,
644
+ * `medical_provider_staff`, `other_incident_responder`) maps through its own
645
+ * successor table until it repins; the test pins this table to
646
+ * `IncidentParticipationRoleKeys` so a future rename lands here too.
647
+ */
648
+ export function orgTypeDefaultSessionRole(
649
+ type: string | null | undefined,
650
+ /**
651
+ * The org's attested HMIS VSP flag (`agencies.vsp`, {@link addAgencyOrgTypeFields}).
652
+ * Canon checks it BEFORE the type (`HTI_SESSION_ROLE_FOR_ORG`, prototype
653
+ * ~L217866; the CVC-69 ruling table's first row): a strict `true` answers
654
+ * `vsp_staff` whatever the type says, because the flag is captured and the
655
+ * type's sector is only a default. `false`, `null`, `undefined` and any
656
+ * non-boolean fall through to the type. Thread's `resolveAgencySessionRole`
657
+ * carries the same precedence (#670) and collapses onto this at the repin.
658
+ */
659
+ vsp?: unknown,
660
+ ): IncidentParticipationRoleKey {
661
+ return orgTypeDefaultSessionRoleOrNull(type, vsp) ?? "vsp_staff";
662
+ }
663
+
664
+ /**
665
+ * The same table, but `null` instead of the catch-all whenever the type does
666
+ * not RESOLVE — absent, empty, free text, a legacy number, a heading. A
667
+ * resolved `unknown` / own-agency type still answers `vsp_staff` (that row is
668
+ * ruled, and the type was read, not guessed), and so does an attested
669
+ * `vsp: true` with any type at all (the flag was read). Use this when the caller must
670
+ * tell "the ruling said VSP staff" from "we had nothing to go on".
671
+ */
672
+ export function orgTypeDefaultSessionRoleOrNull(
673
+ type: string | null | undefined,
674
+ /** See {@link orgTypeDefaultSessionRole}: a strict `true` is a READ answer, never a guess. */
675
+ vsp?: unknown,
676
+ ): IncidentParticipationRoleKey | null {
677
+ if (vsp === true) return "vsp_staff";
678
+ const k = resolveAgencyTypeKey(type);
679
+ if (!k) return null;
680
+ if (NO_SECTOR.has(k)) return "vsp_staff";
681
+ if (VICTIM_SERVING.has(k)) return "vsp_staff";
682
+ if (LAW_ENFORCEMENT.has(k)) return "law_enforcement_personnel";
683
+ if (LEGAL.has(k)) return "legal_professional";
684
+ if (HEALTHCARE.has(k)) return "healthcare_provider_staff";
685
+ return "other_response_personnel";
686
+ }
687
+
688
+ // Compile-time guard: the hand-named keys above exist in the SOT.
689
+ const _orgKeysNamed = [
690
+ "victim_service_provider",
691
+ "child_advocacy_center",
692
+ "community_based_service_provider",
693
+ "legal_services_provider",
694
+ "coalition",
695
+ "courts_prosecution",
696
+ "law_enforcement",
697
+ "health_behavioral_health",
698
+ "justice_protective_systems",
699
+ "internal",
700
+ "own_agency_internal",
701
+ "unknown",
702
+ ] as const satisfies readonly (keyof typeof ReferralEntityCategoryKeys)[];
703
+ void _orgKeysNamed;