@htilabs/platform-common-models 0.15.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.
- package/dist/agency-BHv54o79.d.ts +484 -0
- package/dist/agency-Ca4pCOOf.d.ts +342 -0
- package/dist/agency-DYCv839V.d.cts +342 -0
- package/dist/agency-Djp57S71.d.cts +484 -0
- package/dist/constants/index.cjs +952 -0
- package/dist/constants/index.cjs.map +1 -1
- package/dist/constants/index.d.cts +3 -1
- package/dist/constants/index.d.ts +3 -1
- package/dist/constants/index.js +920 -0
- package/dist/constants/index.js.map +1 -1
- package/dist/{cvcEntry-DaDrEuTa.d.cts → cvcEntry-0BIB9sen.d.cts} +44 -44
- package/dist/{cvcEntry-DaDrEuTa.d.ts → cvcEntry-0BIB9sen.d.ts} +44 -44
- package/dist/cvcs/index.cjs +182 -77
- package/dist/cvcs/index.cjs.map +1 -1
- package/dist/cvcs/index.d.cts +187 -78
- package/dist/cvcs/index.d.ts +187 -78
- package/dist/cvcs/index.js +182 -77
- package/dist/cvcs/index.js.map +1 -1
- package/dist/enums/index.cjs +3 -1
- package/dist/enums/index.cjs.map +1 -1
- package/dist/enums/index.d.cts +7 -5
- package/dist/enums/index.d.ts +7 -5
- package/dist/enums/index.js +3 -1
- package/dist/enums/index.js.map +1 -1
- package/dist/{index-C0J3f169.d.ts → index-CDoqrfc1.d.ts} +1 -1
- package/dist/{index-EPjPjR0z.d.cts → index-Zu_mOJRn.d.cts} +1 -1
- package/dist/index.cjs +1704 -1073
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.js +1650 -1072
- package/dist/index.js.map +1 -1
- package/dist/models/index.d.cts +2 -2
- package/dist/models/index.d.ts +2 -2
- package/dist/org-type-BYQb9Qzq.d.ts +366 -0
- package/dist/org-type-D_FG4KdN.d.cts +366 -0
- package/dist/{platform-auth-CrF5U_JH.d.cts → platform-auth-CvAYFVhK.d.cts} +39 -0
- package/dist/{platform-auth-CrF5U_JH.d.ts → platform-auth-CvAYFVhK.d.ts} +39 -0
- package/dist/schemas/index.cjs +977 -2
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +38 -35
- package/dist/schemas/index.d.ts +38 -35
- package/dist/schemas/index.js +962 -1
- package/dist/schemas/index.js.map +1 -1
- package/dist/types/index.d.cts +2 -2
- package/dist/types/index.d.ts +2 -2
- package/dist/validation/index.cjs +894 -2
- package/dist/validation/index.cjs.map +1 -1
- package/dist/validation/index.d.cts +5 -1
- package/dist/validation/index.d.ts +5 -1
- package/dist/validation/index.js +884 -1
- package/dist/validation/index.js.map +1 -1
- package/package.json +26 -27
- package/src/__tests__/__snapshots__/cvc-sot.snap +5 -5
- package/src/__tests__/core-functions-canon.test.ts +53 -0
- package/src/__tests__/core-information-scope-invariant.test.ts +94 -4
- package/src/__tests__/cvc-sot-snapshot.test.ts +13 -10
- package/src/__tests__/cvc-status-parser.test.ts +1 -1
- package/src/__tests__/cvc-structural.test.ts +3 -3
- package/src/__tests__/org-type-contract.test.ts +1353 -0
- package/src/__tests__/referral-entity-category-canon.test.ts +255 -81
- package/src/constants/ic.ts +45 -0
- package/src/constants/index.ts +1 -0
- package/src/constants/org-type.ts +703 -0
- package/src/cvcs/{coreFunctions.v1.0.0.json → coreFunctions.v1.1.0.json} +11 -2
- package/src/cvcs/index.ts +3 -3
- package/src/cvcs/{referralEntityCategory.v1.1.0.json → referralEntityCategory.v1.2.0.json} +111 -59
- package/src/cvcs/{roiScope.v1.0.0.json → roiScope.v1.2.0.json} +51 -7
- package/src/generated/cvc-enums.ts +7 -5
- package/src/index.ts +23 -0
- package/src/schemas/agency.ts +481 -0
- package/src/schemas/index.ts +24 -0
- package/src/validation/agency.ts +119 -0
- package/src/validation/index.ts +1 -0
- package/dist/team-C4LJ5Tex.d.cts +0 -333
- package/dist/team-C4LJ5Tex.d.ts +0 -333
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/validation/cvc.ts","../../src/validation/cvcStatus.ts","../../src/validation/team.ts","../../src/constants/platform-auth.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Controlled Vocabulary (CVC) Validation\n *\n * Zod schemas for validating CVC Source-of-Truth (SOT) JSON files and\n * individual CVC entries. Implements the locked spec §9.2 shapes.\n *\n * Used by:\n * - CI structural tests that parse every committed SOT file.\n * - The generalized seed CLI (`seedCvc`) prior to persistence.\n * - Downstream consumers that need to validate CVC payloads.\n *\n * Canonical spec:\n * /gt/docs/data/cvcs/CVC Implementation Spec 2780449faf8045258c67daab0f1c5569.md\n *\n * Format v2 (2026-04-15):\n * - Positional 7-segment codes `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (3 digits per\n * segment). Segment 1 is the Notion-aligned domain prefix:\n * `022` service_categories (CVC-22)\n * `025` service_mechanisms (CVC-25)\n * `049` service_states (CVC-49)\n * - Missingness entries are embedded per-domain (synthetic `missingness_root`\n * at `<prefix>-000-000-000-000-000-000` plus three values at segment 7 =\n * `001`/`002`/`003`). The shared `missingness.v1.0.0.json` file was\n * retired in favor of per-domain missingness.\n * - Envelope `missingness` field and the C7 invariant have been removed; the\n * shared-merge pathway no longer exists.\n */\n\nimport { z } from \"zod\";\n\n// ─── Primitive schemas ───────────────────────────────────────────────────────\n\n/**\n * 7-segment positional CVC code: `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (three digits\n * per segment). Segment 1 is the Notion-aligned domain prefix. Remaining\n * hierarchy segments are filled left-to-right as levels deepen; unused\n * segments remain `000`. See locked spec §3 (format v2).\n */\nexport const CvcCodeSchema = z.string().regex(/^\\d{3}(-\\d{3}){6}$/);\n\n/**\n * Stable machine key for a CVC entry. Must start with a lowercase letter and\n * contain only lowercase alphanumerics or underscores. Used as a cross-CVC\n * reference target (e.g. `relevantMechanisms` pointing at mechanism keys).\n * See locked spec §3.2.\n */\nexport const CvcKeySchema = z.string().regex(/^[a-z][a-z0-9_]*$/);\n\n// ─── Entry schemas ───────────────────────────────────────────────────────────\n\n/**\n * Base entry shape shared by every CVC domain. Domain-specific extensions\n * (e.g. `ServiceCategoryEntrySchema`) should use `.extend()` to add fields.\n * See locked spec §9.2.\n *\n * Uses `.passthrough()` so that domain-specific fields (like\n * `relevantMechanisms` on service-category entries) survive base parsing\n * unmodified. This keeps cross-CVC reference validation honest: the §4.5\n * structural validator needs to see the raw referenced keys, and a strip-by-\n * default schema would silently hide them.\n */\nexport const CvcEntrySchema = z\n .object({\n code: CvcCodeSchema,\n key: CvcKeySchema,\n title: z.string().min(1),\n selectable: z.boolean(),\n parentCode: CvcCodeSchema.nullable(),\n childCodes: z.array(CvcCodeSchema),\n definition: z.string().nullable(),\n })\n .passthrough();\n\n/**\n * Service-category-specific entry. Adds `relevantMechanisms` — a cross-CVC\n * reference into the `service_mechanisms` domain via entry keys. `null` means\n * \"not applicable\" (e.g. structural L1 topic rows). See locked spec §9.2.\n */\nexport const ServiceCategoryEntrySchema = CvcEntrySchema.extend({\n relevantMechanisms: z.array(CvcKeySchema).nullable(),\n});\n\n/**\n * Primary-language-specific entry. Adds:\n * - `iso6391Code` — the ISO 639-1 alpha-2 code for the language, or `null`\n * for entries without an ISO 639-1 code (missingness entries, Chinese\n * varieties Mandarin/Cantonese, `other_language`). ASL is stored as\n * `\"ase\"` (ISO 639-3) per Notion's convention; the CVC header documents\n * this caveat.\n * - `priority` — `true` for front-end short-list entries (14 total in\n * CVC-122: 13 L1 languages plus the canonical `unknown` missingness\n * entry). See locked spec §9.2.\n */\nexport const PrimaryLanguageEntrySchema = CvcEntrySchema.extend({\n iso6391Code: z.string().nullable(),\n priority: z.boolean(),\n});\n\n// ─── Envelope schema ─────────────────────────────────────────────────────────\n\n/**\n * Top-level SOT JSON envelope. One envelope per (domain, version) pair.\n *\n * `levels` is a positional map from level number (`\"0\"`, `\"1\"`, …) to a human\n * label describing the level. Missingness entries are embedded in `entries`\n * (per-domain) rather than merged in from a shared SOT file; see module\n * header for the v2 format summary.\n */\nexport const CvcEnvelopeSchema = z.object({\n domain: z.string().min(1),\n name: z.string().min(1),\n version: z.string().min(1),\n levels: z.record(z.string(), z.string()),\n entries: z.array(CvcEntrySchema),\n});\n\n// ─── Inferred types ──────────────────────────────────────────────────────────\n\nexport type CvcCode = z.infer<typeof CvcCodeSchema>;\nexport type CvcKey = z.infer<typeof CvcKeySchema>;\nexport type CvcEntry = z.infer<typeof CvcEntrySchema>;\nexport type ServiceCategoryEntry = z.infer<typeof ServiceCategoryEntrySchema>;\nexport type PrimaryLanguageEntry = z.infer<typeof PrimaryLanguageEntrySchema>;\nexport type CvcEnvelope = z.infer<typeof CvcEnvelopeSchema>;\n\n/**\n * SOT family identifier (e.g. `\"service_categories\"`, `\"service_states\"`,\n * `\"service_mechanisms\"`, `\"missingness\"`). The canonical list of domains is\n * enumerated by the SOT JSON files in `src/cvcs/`. Typed as `string` rather\n * than a closed union so adding a new SOT file does not require touching this\n * type. See locked spec §2.\n */\nexport type CvcDomain = string;\n\n// ─── Structural validator (locked spec §4 / §9.3) ───────────────────────────\n\n/**\n * Derive an entry's level from its 7-segment code per locked spec §3.3.\n *\n * - Segment 7 non-zero → level 0 (missingness value entry, e.g. `unknown`).\n * - Otherwise return the index (1..5) of the last non-zero hierarchy segment.\n * - Hierarchy segments 2..7 all zero → level 0 (per-domain missingness root,\n * e.g. `022-000-000-000-000-000-000`). Segment 1 carries the domain prefix\n * and is intentionally not consulted by the level derivation.\n */\nexport function getCvcLevel(code: string): number {\n const segments = code.split(\"-\");\n // segments[6] is the missingness slot (positional segment 7).\n if (segments[6] !== \"000\") return 0;\n // Walk hierarchy segments 6..2 (indices 5..1) looking for the deepest\n // populated level.\n for (let i = 5; i >= 1; i -= 1) {\n if (segments[i] !== \"000\") return i;\n }\n return 0;\n}\n\n/**\n * Error collected by {@link validateCvc}. Each error names the invariant it\n * violates (`C1`..`C8`, skipping the retired `C7`) so CI output points\n * straight at the locked spec rule that failed. `code` or `key` narrow the\n * error to a specific entry when the violation is entry-scoped.\n */\nexport interface CvcValidationError {\n invariant: \"C1\" | \"C2\" | \"C3\" | \"C4\" | \"C5\" | \"C6\" | \"C8\";\n message: string;\n code?: string;\n key?: string;\n}\n\n/**\n * Structural invariants to enforce on every committed SOT file per locked spec\n * §4. Zod's schema `parse()` guarantees the *shape* of the envelope; this\n * function enforces the cross-entry *semantics* that Zod cannot express.\n *\n * Invariants (locked spec §4):\n * - **C1** Code format + uniqueness (§4.1). Format v2 uses 3-digit segments.\n * - **C2** Key format + uniqueness (§4.2).\n * - **C3** Tree: every `parentCode` resolves to an existing entry or null; no\n * cycles (§4.3).\n * - **C4** `childCodes` are the exact bidirectional inverse of `parentCode`\n * (§4.3).\n * - **C5** Selectability is a boolean (§4.4).\n * - **C6** Cross-CVC `relevantMechanisms` references resolve against a\n * provided `service_mechanisms` key set (§4.5, §7). Only checked when the\n * caller supplies `options.mechanismKeys`.\n * - **C7** _Retired in format v2_ (envelope no longer carries the shared\n * `missingness` field; missingness is per-domain and embedded in\n * `entries`). The invariant slot is intentionally left empty to preserve\n * the numbering of C1/C2/C3/C4/C5/C6/C8 in historical references.\n * - **C8** No entry anywhere contains a key `'provided'` (legacy Thread UI\n * label guard; not a canonical state).\n *\n * @param envelope Parsed envelope (typically from `CvcEnvelopeSchema.parse()`).\n * @param options.mechanismKeys Optional set of valid `service_mechanisms`\n * entry keys. If provided and the envelope entries have `relevantMechanisms`\n * fields, each referenced key must be in this set (C6).\n * @returns An array of {@link CvcValidationError}. An empty array means valid.\n */\nexport function validateCvc(\n envelope: CvcEnvelope,\n options: { mechanismKeys?: ReadonlySet<string> } = {},\n): CvcValidationError[] {\n const errors: CvcValidationError[] = [];\n const { entries } = envelope;\n\n // ── C1: code format + uniqueness ──────────────────────────────────────────\n const codeRe = /^\\d{3}(-\\d{3}){6}$/;\n const seenCodes = new Set<string>();\n for (const entry of entries) {\n if (!codeRe.test(entry.code)) {\n errors.push({\n invariant: \"C1\",\n message: `code does not match /^\\\\d{3}(-\\\\d{3}){6}$/`,\n code: entry.code,\n key: entry.key,\n });\n }\n if (seenCodes.has(entry.code)) {\n errors.push({\n invariant: \"C1\",\n message: `duplicate code`,\n code: entry.code,\n key: entry.key,\n });\n }\n seenCodes.add(entry.code);\n }\n\n // ── C2: key format + uniqueness ───────────────────────────────────────────\n const keyRe = /^[a-z][a-z0-9_]*$/;\n const seenKeys = new Set<string>();\n for (const entry of entries) {\n if (!keyRe.test(entry.key)) {\n errors.push({\n invariant: \"C2\",\n message: `key does not match /^[a-z][a-z0-9_]*$/`,\n code: entry.code,\n key: entry.key,\n });\n }\n if (seenKeys.has(entry.key)) {\n errors.push({\n invariant: \"C2\",\n message: `duplicate key`,\n code: entry.code,\n key: entry.key,\n });\n }\n seenKeys.add(entry.key);\n }\n\n // Build a lookup by code for the remaining tree checks. Skip entries whose\n // code we already know is malformed — their index would be meaningless.\n const byCode = new Map<string, CvcEntry>();\n for (const entry of entries) {\n if (codeRe.test(entry.code)) byCode.set(entry.code, entry);\n }\n\n // ── C3: tree — parents resolve, no cycles ─────────────────────────────────\n for (const entry of entries) {\n if (entry.parentCode === null) continue;\n if (!byCode.has(entry.parentCode)) {\n errors.push({\n invariant: \"C3\",\n message: `parentCode ${entry.parentCode} does not resolve to any entry in this CVC`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n // Cycle detection: walk parent chain from each entry, bail if we revisit.\n for (const entry of entries) {\n const visited = new Set<string>();\n let cursor: CvcEntry | undefined = entry;\n while (cursor && cursor.parentCode !== null) {\n if (visited.has(cursor.code)) {\n errors.push({\n invariant: \"C3\",\n message: `cycle detected in parentCode chain starting from ${entry.code}`,\n code: entry.code,\n key: entry.key,\n });\n break;\n }\n visited.add(cursor.code);\n cursor = byCode.get(cursor.parentCode);\n }\n }\n\n // ── C4: childCodes are exact inverse of parentCode ────────────────────────\n // Build the set of (parent, child) edges from parentCode, then from\n // childCodes, and require they match exactly.\n const parentToChildrenFromParent = new Map<string, Set<string>>();\n for (const entry of entries) {\n if (entry.parentCode !== null) {\n let set = parentToChildrenFromParent.get(entry.parentCode);\n if (!set) {\n set = new Set();\n parentToChildrenFromParent.set(entry.parentCode, set);\n }\n set.add(entry.code);\n }\n }\n\n for (const entry of entries) {\n const declared = new Set(entry.childCodes);\n const derived = parentToChildrenFromParent.get(entry.code) ?? new Set();\n\n for (const child of declared) {\n if (!derived.has(child)) {\n errors.push({\n invariant: \"C4\",\n message: `entry lists ${child} in childCodes but that entry's parentCode is not ${entry.code}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n for (const child of derived) {\n if (!declared.has(child)) {\n errors.push({\n invariant: \"C4\",\n message: `entry ${child} has parentCode ${entry.code} but is missing from its childCodes`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n }\n\n // ── C5: selectability per §4.4 ────────────────────────────────────────────\n // Zod already enforces `selectable: boolean`; we make the invariant explicit\n // at validator level so a future schema loosening cannot silently bypass it.\n for (const entry of entries) {\n if (typeof entry.selectable !== \"boolean\") {\n errors.push({\n invariant: \"C5\",\n message: `selectable must be a boolean, got ${typeof entry.selectable}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n // ── C6: cross-CVC refs — `relevantMechanisms` resolves against provided set\n if (options.mechanismKeys) {\n for (const entry of entries) {\n const raw = (entry as unknown as Record<string, unknown>)[\n \"relevantMechanisms\"\n ];\n if (raw === undefined || raw === null) continue;\n if (!Array.isArray(raw)) {\n errors.push({\n invariant: \"C6\",\n message: `relevantMechanisms must be an array or null`,\n code: entry.code,\n key: entry.key,\n });\n continue;\n }\n for (const mechKey of raw) {\n if (\n typeof mechKey !== \"string\" ||\n !options.mechanismKeys.has(mechKey)\n ) {\n errors.push({\n invariant: \"C6\",\n message: `relevantMechanisms references unknown service_mechanisms key: ${String(mechKey)}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n }\n }\n\n // ── C8: legacy `'provided'` key guard ─────────────────────────────────────\n // Walk every property of every entry (including nested arrays) looking for\n // a key named `'provided'`. It is a Thread UI label, not a canonical state.\n const walkForProvided = (value: unknown, entry: CvcEntry): void => {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n for (const item of value) walkForProvided(item, entry);\n return;\n }\n if (typeof value === \"object\") {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === \"provided\") {\n errors.push({\n invariant: \"C8\",\n message: `entry contains forbidden legacy key 'provided' (see locked spec §4)`,\n code: entry.code,\n key: entry.key,\n });\n }\n walkForProvided(v, entry);\n }\n }\n };\n for (const entry of entries) {\n walkForProvided(entry, entry);\n // Also guard against a literal string value of 'provided' appearing as an\n // entry's `key`, which would be an obvious smuggling attempt.\n if (entry.key === \"provided\") {\n errors.push({\n invariant: \"C8\",\n message: `entry key must not be the legacy label 'provided'`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n return errors;\n}\n","/**\n * @htilabs/platform-common-models — CVC `_status`/`_source` provenance parser\n *\n * Problem this solves: `_status` on a SOT envelope (`src/cvcs/*.json`) is\n * unvalidated free text (115 of 179 domains carry it; the rest predate the\n * convention). A consumer that wants to know \"is this actually a draft?\" has\n * had to eyeball a string like\n *\n * \"DRAFT — TEMPORARY: net-new value-CVC not yet in Notion; provisional\n * 900+ numbering; codes from prototype/data/cvcs/core_accommodation_type\n * .yaml; PENDING canonical Notion authoring (PAVE Auditability backlog).\"\n *\n * and get it right past two real traps observed across the current\n * population:\n * - A leading `\"CANONICAL — …\"` marker is a PROVENANCE note on an\n * ALREADY-ratified file, not a maturity warning — it must not be lumped\n * in with `\"DRAFT\"`/`\"PROVISIONAL\"`.\n * - `core_functions` is self-contradictory: it leads\n * `\"DRAFTED — NEEDS REVIEW\"` but the same string continues\n * `\"…Canonical numbering (133), NOT provisional.\"` A naive\n * leading-word reader silently picks one side; this parser flags it.\n *\n * This module is a pure, additive, standalone export. It does NOT touch\n * `CvcEnvelopeSchema` (`./cvc.ts`) — `_status`/`_source` are intentionally\n * outside that Zod schema (see its module header), and adding them there\n * would risk changing parse behavior for every existing consumer. Callers\n * pass the RAW parsed JSON object (before or instead of\n * `CvcEnvelopeSchema.parse()`), not the Zod-inferred `CvcEnvelope`.\n *\n * Classification rule (leading token of `_status`, case-insensitive):\n * - contains \"draft\" → `maturity: \"draft\"`\n * - contains \"provisional\" → `maturity: \"provisional\"`\n * - contains \"canonical\" → `maturity: \"canonical\"` (a provenance note on\n * an already-ratified file, NOT a maturity flag — kept distinct from\n * `\"final\"` below so a caller can tell \"explicitly marked ratified\"\n * apart from \"predates the convention entirely\")\n * - `_status` absent entirely → `maturity: \"final\"` (legacy/unmarked)\n *\n * One real domain (`share_purpose` — \"Synced verbatim from canonical\n * CVC-84…\") has a present `_status` whose LEADING token (\"Synced\") is none\n * of the three convention words. Rather than mis-file it as `\"final\"` (which\n * per the rule above is reserved for an ABSENT field) this parser falls back\n * to scanning the full string for a single unambiguous keyword family before\n * giving up — see `detectMaturity` below.\n */\n\n// ─── Public shape ───────────────────────────────────────────────────────────\n\n/**\n * The subset of a raw (pre-validation) SOT envelope this parser reads.\n * Deliberately NOT the Zod-inferred `CvcEnvelope` from `./cvc.ts` — that type\n * is the *parsed* shape, which does not declare `_status`/`_source` at all\n * (they live outside the locked envelope schema on purpose). Pass the raw\n * `JSON.parse()` result of a `src/cvcs/*.json` file here.\n */\nexport interface RawCvcEnvelopeProvenance {\n _status?: unknown;\n _source?: unknown;\n}\n\n/** The four observed maturity states. See module header for the rule. */\nexport type CvcMaturity = \"draft\" | \"provisional\" | \"canonical\" | \"final\";\n\nexport interface CvcStatusInfo {\n /** One of the four states; see module header for the classification rule. */\n maturity: CvcMaturity;\n /**\n * The text this parser classified. For a string `_status` this is that\n * string verbatim. For the 11 domains authored with a structured\n * `_status` object (`{ vocabStatus, authoredBy, evidence, … }` — e.g.\n * `citizenship`, `core_functions`'s sibling `countries`), this is\n * `_status.vocabStatus` — the field those envelopes use for exactly this\n * purpose — not the whole object. `null` iff `_status` is absent.\n */\n rawStatus: string | null;\n /** True iff `_source` cites a `prototype/data/cvcs/*.yaml` path. */\n sourceIsPrototype: boolean;\n /** The cited `prototype/data/cvcs/*.yaml` path, or `null` if none. */\n sourcePath: string | null;\n /**\n * True when the classification is a judgment call rather than a clean\n * read: either the leading token disagrees with a later\n * \"NOT draft\"/\"NOT provisional\"/\"NOT canonical\" qualifier in the same\n * string (the `core_functions` shape — generic, not special-cased, so any\n * future domain authored in the same self-contradictory shape is also\n * caught), or the string carries more than one maturity keyword family\n * with no leading token to arbitrate between them.\n */\n ambiguous: boolean;\n}\n\n// ─── Implementation ─────────────────────────────────────────────────────────\n\nconst MATURITY_KEYWORDS: ReadonlyArray<{\n keyword: string;\n maturity: Exclude<CvcMaturity, \"final\">;\n}> = [\n { keyword: \"draft\", maturity: \"draft\" },\n { keyword: \"provisional\", maturity: \"provisional\" },\n { keyword: \"canonical\", maturity: \"canonical\" },\n];\n\n/** Matches a `prototype/data/cvcs/<file>.yaml` citation anywhere in `_source`. */\nconst PROTOTYPE_SOURCE_RE = /(prototype\\/data\\/cvcs\\/[A-Za-z0-9_.-]+\\.yaml)/;\n\n/**\n * A maturity keyword explicitly negated (\"NOT provisional.\") anywhere in the\n * string — the self-contradiction signal. Deliberately scans the WHOLE\n * string (not just past the leading token): the qualifier that disagrees\n * with the leading word is, by construction, never the leading word itself.\n */\nconst NEGATED_MATURITY_RE = /\\bnot\\s+(draft|provisional|canonical)\\b/i;\n\n/**\n * Extract the text this parser classifies against, from either `_status`\n * shape observed in the current SOT population:\n * - `string` (104 of 115 status-bearing domains) → the string itself.\n * - `{ vocabStatus: string, … }` (11 domains — a richer, hand-authored\n * provenance record) → `vocabStatus`, the field those envelopes use for\n * exactly this classification (values seen: `\"canonical\"` and\n * `\"provisional-pending-notion-ratification\"`).\n * - Anything else present but shapeless (unseen in the current 179-domain\n * population) → `JSON.stringify` as a last resort, so a future oddity\n * still gets a best-effort classification instead of silently vanishing.\n * - Absent → `null`.\n */\nfunction extractClassificationText(status: unknown): string | null {\n if (typeof status === \"string\") return status;\n if (status !== null && typeof status === \"object\") {\n const vocabStatus = (status as Record<string, unknown>).vocabStatus;\n if (typeof vocabStatus === \"string\") return vocabStatus;\n return JSON.stringify(status);\n }\n return null;\n}\n\n/** The first \"word\" of a status string, lowercased, for the leading-token rule. */\nfunction leadingToken(text: string): string {\n return (text.trim().split(/[\\s—–:-]+/, 1)[0] ?? \"\").toLowerCase();\n}\n\n/**\n * Classify a present, non-null `_status` text into a maturity + ambiguity\n * flag. Isolated from {@link parseCvcStatus} so the fallback path (the\n * `share_purpose` shape) and the negation check are each unit-testable in\n * isolation.\n */\nfunction detectMaturity(text: string): { maturity: Exclude<CvcMaturity, \"final\">; ambiguous: boolean } {\n const lead = leadingToken(text);\n const leadMatch = MATURITY_KEYWORDS.find(({ keyword }) => lead.includes(keyword));\n\n let maturity: Exclude<CvcMaturity, \"final\">;\n if (leadMatch) {\n maturity = leadMatch.maturity;\n } else {\n // The leading token is none of the three convention words. Observed once\n // in the current population: `share_purpose`'s\n // \"Synced verbatim from canonical CVC-84…\" — \"Synced\" leads, but the\n // string is unambiguously describing an already-ratified vocabulary.\n // Fall back to scanning the WHOLE string for maturity keyword families\n // rather than defaulting to \"final\": the field IS present, and \"final\"\n // per the module-header rule is reserved for an ABSENT `_status`.\n const foundFamilies = MATURITY_KEYWORDS.filter(({ keyword }) =>\n new RegExp(`\\\\b${keyword}\\\\w*\\\\b`, \"i\").test(text),\n );\n const distinctFamilies = new Set(foundFamilies.map((f) => f.maturity));\n if (distinctFamilies.size === 1) {\n // Single unambiguous family found in the body — safe to accept.\n maturity = foundFamilies[0].maturity;\n return { maturity, ambiguous: false };\n }\n if (distinctFamilies.size > 1) {\n // Multiple families present with no leading token to arbitrate.\n // Report the first-occurring family as a best-effort primary and let\n // the caller see `ambiguous: true` — never silently pick a winner.\n maturity = foundFamilies[0].maturity;\n return { maturity, ambiguous: true };\n }\n // No maturity keyword anywhere in a present `_status` string. Unseen in\n // the current 179-domain population; treat conservatively as\n // \"provisional\" (the least-committal non-final bucket) rather than\n // silently promoting an unrecognized status to a settled one, and flag\n // it for human attention.\n return { maturity: \"provisional\", ambiguous: true };\n }\n\n return { maturity, ambiguous: NEGATED_MATURITY_RE.test(text) };\n}\n\n/**\n * Parse a SOT envelope's `_status`/`_source` provenance fields into a\n * structured, typed result. Pure function — no filesystem access, no\n * dependency on `CvcEnvelopeSchema`. See module header for the full rule and\n * the two known traps it exists to catch.\n */\nexport function parseCvcStatus(envelope: RawCvcEnvelopeProvenance): CvcStatusInfo {\n const source = typeof envelope._source === \"string\" ? envelope._source : null;\n const protoMatch = source?.match(PROTOTYPE_SOURCE_RE) ?? null;\n const sourceIsPrototype = protoMatch !== null;\n const sourcePath = protoMatch?.[1] ?? null;\n\n const text = extractClassificationText(envelope._status);\n if (text === null) {\n return { maturity: \"final\", rawStatus: null, sourceIsPrototype, sourcePath, ambiguous: false };\n }\n\n const { maturity, ambiguous } = detectMaturity(text);\n return { maturity, rawStatus: text, sourceIsPrototype, sourcePath, ambiguous };\n}\n","/**\n * @htilabs/platform-common-models — Team directory field validation\n *\n * Zod schemas for the team directory fields declared in\n * `../schemas/team.ts`, the fields the Thread→PAVE \"Refer to intake\" preset\n * reads. See that module for canon citations and the two deliberate\n * divergences (`apps` uses the {@link PLATFORM_TOOL} codes, and `canReferTo`\n * sits on the team because there is no Program model).\n *\n * This is the wire / API shape: ids are 24-hex strings, not ObjectIds. Merge\n * {@link TeamDirectoryFieldsSchema} into a consumer's team schema with\n * `.merge()` or `.extend(TeamDirectoryFieldsSchema.shape)`.\n */\n\nimport { z } from \"zod\";\nimport { PLATFORM_TOOL_VALUES } from \"../constants/platform-auth.js\";\n\n/** A Mongo ObjectId serialized as a 24-character hex string. */\nconst ObjectIdHexSchema = z\n .string()\n .regex(/^[0-9a-fA-F]{24}$/, \"must be a 24-character hex ObjectId\");\n\nconst hasNoDuplicates = (values: readonly string[]): boolean =>\n new Set(values.map((v) => v.toLowerCase())).size === values.length;\n\n/** One platform app a team works in: a {@link PLATFORM_TOOL} code. */\nexport const TeamAppSchema = z.enum(PLATFORM_TOOL_VALUES);\n\n/**\n * The team directory fields. Both are optional, so a team payload without\n * them validates unchanged. When present, neither list may repeat a value.\n */\nexport const TeamDirectoryFieldsSchema = z.object({\n apps: z\n .array(TeamAppSchema)\n .refine(hasNoDuplicates, \"apps must not repeat an app\")\n .optional(),\n canReferTo: z\n .array(ObjectIdHexSchema)\n .refine(hasNoDuplicates, \"canReferTo must not repeat a team\")\n .optional(),\n});\n\n/** A platform app code accepted on a team. */\nexport type TeamApp = z.infer<typeof TeamAppSchema>;\n\n/** Wire shape of the team directory fields (ids as hex strings). */\nexport type TeamDirectoryFieldsInput = z.infer<typeof TeamDirectoryFieldsSchema>;\n","/**\n * @htilabs/platform-common-models — Platform Authorization Constants\n *\n * Enums and labels for the platform role/function permission model.\n * Includes permission states, share view levels, tool codes, role levels,\n * and function implementation statuses.\n *\n * Source: PLATFORM_AUTH_SPEC.md Sections 5 + 6\n */\n\n// ─── Permission State (4-state role→function mapping) ──────────────\n\nexport const PERMISSION_STATE = {\n /** Role can always perform this function (mandatory, cannot disable). */\n ALWAYS: \"ALWAYS\",\n /** Default On — user can opt off. */\n PREF_YES: \"PREF_YES\",\n /** Default Off — user can opt in. */\n PREF_NO: \"PREF_NO\",\n /** Role is explicitly barred from this function. */\n NEVER: \"NEVER\",\n} as const;\n\nexport type PermissionStateValue =\n (typeof PERMISSION_STATE)[keyof typeof PERMISSION_STATE];\n\nexport const PERMISSION_STATE_VALUES = [\n PERMISSION_STATE.ALWAYS,\n PERMISSION_STATE.PREF_YES,\n PERMISSION_STATE.PREF_NO,\n PERMISSION_STATE.NEVER,\n] as const;\n\nexport const PERMISSION_STATE_LABELS: Record<PermissionStateValue, string> = {\n [PERMISSION_STATE.ALWAYS]: \"Always\",\n [PERMISSION_STATE.PREF_YES]: \"Default On\",\n [PERMISSION_STATE.PREF_NO]: \"Default Off\",\n [PERMISSION_STATE.NEVER]: \"Never\",\n};\n\n/** UI display metadata for permission states (colors, icons). */\nexport const PERMISSION_STATE_DISPLAY: Record<\n PermissionStateValue,\n { label: string; color: string; bgColor: string; icon: string }\n> = {\n [PERMISSION_STATE.ALWAYS]: {\n label: \"Always\",\n color: \"#2e7d32\",\n bgColor: \"#e8f5e9\",\n icon: \"\\u{1F512}\",\n },\n [PERMISSION_STATE.PREF_YES]: {\n label: \"Default On\",\n color: \"#1565c0\",\n bgColor: \"#e3f2fd\",\n icon: \"\\u{1F513}\",\n },\n [PERMISSION_STATE.PREF_NO]: {\n label: \"Default Off\",\n color: \"#e65100\",\n bgColor: \"#fff3e0\",\n icon: \"\\u{1F513}\",\n },\n [PERMISSION_STATE.NEVER]: {\n label: \"Never\",\n color: \"#c62828\",\n bgColor: \"#ffebee\",\n icon: \"\\u{1F512}\",\n },\n};\n\n// ─── Share View (data visibility for shared records) ───────────────\n\nexport const SHARE_VIEW = {\n /** System metadata only (partial access). */\n SYS_INFO: \"sys_info\",\n /** Full case/record content. */\n ALL: \"all\",\n /** No data access. */\n NONE: \"none\",\n} as const;\n\nexport type ShareViewValue = (typeof SHARE_VIEW)[keyof typeof SHARE_VIEW];\n\nexport const SHARE_VIEW_VALUES = [\n SHARE_VIEW.SYS_INFO,\n SHARE_VIEW.ALL,\n SHARE_VIEW.NONE,\n] as const;\n\nexport const SHARE_VIEW_LABELS: Record<ShareViewValue, string> = {\n [SHARE_VIEW.SYS_INFO]: \"System Info Only\",\n [SHARE_VIEW.ALL]: \"Full Content\",\n [SHARE_VIEW.NONE]: \"No Data Access\",\n};\n\n// ─── Platform Tool Codes ───────────────────────────────────────────\n\nexport const PLATFORM_TOOL = {\n PAVE: \"PAVE\",\n ECHO: \"ECHO\",\n LEADS: \"LEADS\",\n THREAD: \"THREAD\",\n TRAIL: \"TRAIL\",\n PLATFORM: \"PLATFORM\",\n} as const;\n\nexport type PlatformToolValue =\n (typeof PLATFORM_TOOL)[keyof typeof PLATFORM_TOOL];\n\nexport const PLATFORM_TOOL_VALUES = [\n PLATFORM_TOOL.PAVE,\n PLATFORM_TOOL.ECHO,\n PLATFORM_TOOL.LEADS,\n PLATFORM_TOOL.THREAD,\n PLATFORM_TOOL.TRAIL,\n PLATFORM_TOOL.PLATFORM,\n] as const;\n\nexport const PLATFORM_TOOL_LABELS: Record<PlatformToolValue, string> = {\n [PLATFORM_TOOL.PAVE]: \"PAVE\",\n [PLATFORM_TOOL.ECHO]: \"Echo\",\n [PLATFORM_TOOL.LEADS]: \"LEADS\",\n [PLATFORM_TOOL.THREAD]: \"Thread\",\n [PLATFORM_TOOL.TRAIL]: \"Trail\",\n [PLATFORM_TOOL.PLATFORM]: \"Platform\",\n};\n\n// ─── Role Level (hierarchy tiers) ──────────────────────────────────\n\nexport const ROLE_LEVEL = {\n /** User-facing roles (staff, volunteers, practitioners). */\n OPERATIONAL: \"operational\",\n /** Agency-level admin roles. */\n AGENCY: \"agency\",\n /** Team-level admin roles. */\n TEAM: \"team\",\n /** HTI-wide platform admin. */\n PLATFORM: \"platform\",\n /** External governance/oversight roles. */\n OVERSIGHT: \"oversight\",\n} as const;\n\nexport type RoleLevelValue = (typeof ROLE_LEVEL)[keyof typeof ROLE_LEVEL];\n\nexport const ROLE_LEVEL_VALUES = [\n ROLE_LEVEL.OPERATIONAL,\n ROLE_LEVEL.AGENCY,\n ROLE_LEVEL.TEAM,\n ROLE_LEVEL.PLATFORM,\n ROLE_LEVEL.OVERSIGHT,\n] as const;\n\nexport const ROLE_LEVEL_LABELS: Record<RoleLevelValue, string> = {\n [ROLE_LEVEL.OPERATIONAL]: \"Operational\",\n [ROLE_LEVEL.AGENCY]: \"Agency\",\n [ROLE_LEVEL.TEAM]: \"Team\",\n [ROLE_LEVEL.PLATFORM]: \"Platform\",\n [ROLE_LEVEL.OVERSIGHT]: \"Oversight\",\n};\n\n// ─── Function Implementation Status ────────────────────────────────\n\nexport const FUNCTION_STATUS = {\n NOT_STARTED: \"Not started\",\n DEFINED_NEW: \"Defined; new function\",\n DEFINED_EXISTING: \"Defined; existing PAVE function\",\n FUNCTIONAL: \"Functional on all apps\",\n FUTURE: \"Future function (not v1)\",\n} as const;\n\nexport type FunctionStatusValue =\n (typeof FUNCTION_STATUS)[keyof typeof FUNCTION_STATUS];\n\nexport const FUNCTION_STATUS_VALUES = [\n FUNCTION_STATUS.NOT_STARTED,\n FUNCTION_STATUS.DEFINED_NEW,\n FUNCTION_STATUS.DEFINED_EXISTING,\n FUNCTION_STATUS.FUNCTIONAL,\n FUNCTION_STATUS.FUTURE,\n] as const;\n\nexport const FUNCTION_STATUS_LABELS: Record<FunctionStatusValue, string> = {\n [FUNCTION_STATUS.NOT_STARTED]: \"Not Started\",\n [FUNCTION_STATUS.DEFINED_NEW]: \"Defined (New)\",\n [FUNCTION_STATUS.DEFINED_EXISTING]: \"Defined (Existing PAVE)\",\n [FUNCTION_STATUS.FUNCTIONAL]: \"Functional\",\n [FUNCTION_STATUS.FUTURE]: \"Future (Not v1)\",\n};\n"],"mappings":";AA4BA,SAAS,SAAS;AAUX,IAAM,gBAAgB,EAAE,OAAO,EAAE,MAAM,oBAAoB;AAQ3D,IAAM,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB;AAezD,IAAM,iBAAiB,EAC3B,OAAO;AAAA,EACN,MAAM;AAAA,EACN,KAAK;AAAA,EACL,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACvB,YAAY,EAAE,QAAQ;AAAA,EACtB,YAAY,cAAc,SAAS;AAAA,EACnC,YAAY,EAAE,MAAM,aAAa;AAAA,EACjC,YAAY,EAAE,OAAO,EAAE,SAAS;AAClC,CAAC,EACA,YAAY;AAOR,IAAM,6BAA6B,eAAe,OAAO;AAAA,EAC9D,oBAAoB,EAAE,MAAM,YAAY,EAAE,SAAS;AACrD,CAAC;AAaM,IAAM,6BAA6B,eAAe,OAAO;AAAA,EAC9D,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,UAAU,EAAE,QAAQ;AACtB,CAAC;AAYM,IAAM,oBAAoB,EA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AI,GAAG;AAAA,EACnB,CAAC,WAAW,QAAQ,GAAG;AAAA,EACvB,CAAC,WAAW,SAAS,GAAG;AAC1B;AAIO,IAAM,kBAAkB;AAAA,EAC7B,aAAa;AAAA,EACb,aAAa;AAAA,EACb,kBAAkB;AAAA,EAClB,YAAY;AAAA,EACZ,QAAQ;AACV;AAKO,IAAM,yBAAyB;AAAA,EACpC,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAAA,EAChB,gBAAgB;AAClB;AAEO,IAAM,yBAA8D;AAAA,EACzE,CAAC,gBAAgB,WAAW,GAAG;AAAA,EAC/B,CAAC,gBAAgB,WAAW,GAAG;AAAA,EAC/B,CAAC,gBAAgB,gBAAgB,GAAG;AAAA,EACpC,CAAC,gBAAgB,UAAU,GAAG;AAAA,EAC9B,CAAC,gBAAgB,MAAM,GAAG;AAC5B;;;AD1KA,IAAM,oBAAoBC,GACvB,OAAO,EACP,MAAM,qBAAqB,qCAAqC;AAEnE,IAAM,kBAAkB,CAAC,WACvB,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC,EAAE,SAAS,OAAO;AAGvD,IAAM,gBAAgBA,GAAE,KAAK,oBAAoB;AAMjD,IAAM,4BAA4BA,GAAE,OAAO;AAAA,EAChD,MAAMA,GACH,MAAM,aAAa,EACnB,OAAO,iBAAiB,6BAA6B,EACrD,SAAS;AAAA,EACZ,YAAYA,GACT,MAAM,iBAAiB,EACvB,OAAO,iBAAiB,mCAAmC,EAC3D,SAAS;AACd,CAAC;","names":["z","z"]}
|
|
1
|
+
{"version":3,"sources":["../../src/validation/cvc.ts","../../src/validation/cvcStatus.ts","../../src/validation/team.ts","../../src/constants/platform-auth.ts","../../src/validation/agency.ts","../../src/cvcs/referralEntityCategory.v1.2.0.json","../../src/constants/org-type.ts","../../src/schemas/agency.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models — Controlled Vocabulary (CVC) Validation\n *\n * Zod schemas for validating CVC Source-of-Truth (SOT) JSON files and\n * individual CVC entries. Implements the locked spec §9.2 shapes.\n *\n * Used by:\n * - CI structural tests that parse every committed SOT file.\n * - The generalized seed CLI (`seedCvc`) prior to persistence.\n * - Downstream consumers that need to validate CVC payloads.\n *\n * Canonical spec:\n * /gt/docs/data/cvcs/CVC Implementation Spec 2780449faf8045258c67daab0f1c5569.md\n *\n * Format v2 (2026-04-15):\n * - Positional 7-segment codes `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (3 digits per\n * segment). Segment 1 is the Notion-aligned domain prefix:\n * `022` service_categories (CVC-22)\n * `025` service_mechanisms (CVC-25)\n * `049` service_states (CVC-49)\n * - Missingness entries are embedded per-domain (synthetic `missingness_root`\n * at `<prefix>-000-000-000-000-000-000` plus three values at segment 7 =\n * `001`/`002`/`003`). The shared `missingness.v1.0.0.json` file was\n * retired in favor of per-domain missingness.\n * - Envelope `missingness` field and the C7 invariant have been removed; the\n * shared-merge pathway no longer exists.\n */\n\nimport { z } from \"zod\";\n\n// ─── Primitive schemas ───────────────────────────────────────────────────────\n\n/**\n * 7-segment positional CVC code: `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (three digits\n * per segment). Segment 1 is the Notion-aligned domain prefix. Remaining\n * hierarchy segments are filled left-to-right as levels deepen; unused\n * segments remain `000`. See locked spec §3 (format v2).\n */\nexport const CvcCodeSchema = z.string().regex(/^\\d{3}(-\\d{3}){6}$/);\n\n/**\n * Stable machine key for a CVC entry. Must start with a lowercase letter and\n * contain only lowercase alphanumerics or underscores. Used as a cross-CVC\n * reference target (e.g. `relevantMechanisms` pointing at mechanism keys).\n * See locked spec §3.2.\n */\nexport const CvcKeySchema = z.string().regex(/^[a-z][a-z0-9_]*$/);\n\n// ─── Entry schemas ───────────────────────────────────────────────────────────\n\n/**\n * Base entry shape shared by every CVC domain. Domain-specific extensions\n * (e.g. `ServiceCategoryEntrySchema`) should use `.extend()` to add fields.\n * See locked spec §9.2.\n *\n * Uses `.passthrough()` so that domain-specific fields (like\n * `relevantMechanisms` on service-category entries) survive base parsing\n * unmodified. This keeps cross-CVC reference validation honest: the §4.5\n * structural validator needs to see the raw referenced keys, and a strip-by-\n * default schema would silently hide them.\n */\nexport const CvcEntrySchema = z\n .object({\n code: CvcCodeSchema,\n key: CvcKeySchema,\n title: z.string().min(1),\n selectable: z.boolean(),\n parentCode: CvcCodeSchema.nullable(),\n childCodes: z.array(CvcCodeSchema),\n definition: z.string().nullable(),\n })\n .passthrough();\n\n/**\n * Service-category-specific entry. Adds `relevantMechanisms` — a cross-CVC\n * reference into the `service_mechanisms` domain via entry keys. `null` means\n * \"not applicable\" (e.g. structural L1 topic rows). See locked spec §9.2.\n */\nexport const ServiceCategoryEntrySchema = CvcEntrySchema.extend({\n relevantMechanisms: z.array(CvcKeySchema).nullable(),\n});\n\n/**\n * Primary-language-specific entry. Adds:\n * - `iso6391Code` — the ISO 639-1 alpha-2 code for the language, or `null`\n * for entries without an ISO 639-1 code (missingness entries, Chinese\n * varieties Mandarin/Cantonese, `other_language`). ASL is stored as\n * `\"ase\"` (ISO 639-3) per Notion's convention; the CVC header documents\n * this caveat.\n * - `priority` — `true` for front-end short-list entries (14 total in\n * CVC-122: 13 L1 languages plus the canonical `unknown` missingness\n * entry). See locked spec §9.2.\n */\nexport const PrimaryLanguageEntrySchema = CvcEntrySchema.extend({\n iso6391Code: z.string().nullable(),\n priority: z.boolean(),\n});\n\n// ─── Envelope schema ─────────────────────────────────────────────────────────\n\n/**\n * Top-level SOT JSON envelope. One envelope per (domain, version) pair.\n *\n * `levels` is a positional map from level number (`\"0\"`, `\"1\"`, …) to a human\n * label describing the level. Missingness entries are embedded in `entries`\n * (per-domain) rather than merged in from a shared SOT file; see module\n * header for the v2 format summary.\n */\nexport const CvcEnvelopeSchema = z.object({\n domain: z.string().min(1),\n name: z.string().min(1),\n version: z.string().min(1),\n levels: z.record(z.string(), z.string()),\n entries: z.array(CvcEntrySchema),\n});\n\n// ─── Inferred types ──────────────────────────────────────────────────────────\n\nexport type CvcCode = z.infer<typeof CvcCodeSchema>;\nexport type CvcKey = z.infer<typeof CvcKeySchema>;\nexport type CvcEntry = z.infer<typeof CvcEntrySchema>;\nexport type ServiceCategoryEntry = z.infer<typeof ServiceCategoryEntrySchema>;\nexport type PrimaryLanguageEntry = z.infer<typeof PrimaryLanguageEntrySchema>;\nexport type CvcEnvelope = z.infer<typeof CvcEnvelopeSchema>;\n\n/**\n * SOT family identifier (e.g. `\"service_categories\"`, `\"service_states\"`,\n * `\"service_mechanisms\"`, `\"missingness\"`). The canonical list of domains is\n * enumerated by the SOT JSON files in `src/cvcs/`. Typed as `string` rather\n * than a closed union so adding a new SOT file does not require touching this\n * type. See locked spec §2.\n */\nexport type CvcDomain = string;\n\n// ─── Structural validator (locked spec §4 / §9.3) ───────────────────────────\n\n/**\n * Derive an entry's level from its 7-segment code per locked spec §3.3.\n *\n * - Segment 7 non-zero → level 0 (missingness value entry, e.g. `unknown`).\n * - Otherwise return the index (1..5) of the last non-zero hierarchy segment.\n * - Hierarchy segments 2..7 all zero → level 0 (per-domain missingness root,\n * e.g. `022-000-000-000-000-000-000`). Segment 1 carries the domain prefix\n * and is intentionally not consulted by the level derivation.\n */\nexport function getCvcLevel(code: string): number {\n const segments = code.split(\"-\");\n // segments[6] is the missingness slot (positional segment 7).\n if (segments[6] !== \"000\") return 0;\n // Walk hierarchy segments 6..2 (indices 5..1) looking for the deepest\n // populated level.\n for (let i = 5; i >= 1; i -= 1) {\n if (segments[i] !== \"000\") return i;\n }\n return 0;\n}\n\n/**\n * Error collected by {@link validateCvc}. Each error names the invariant it\n * violates (`C1`..`C8`, skipping the retired `C7`) so CI output points\n * straight at the locked spec rule that failed. `code` or `key` narrow the\n * error to a specific entry when the violation is entry-scoped.\n */\nexport interface CvcValidationError {\n invariant: \"C1\" | \"C2\" | \"C3\" | \"C4\" | \"C5\" | \"C6\" | \"C8\";\n message: string;\n code?: string;\n key?: string;\n}\n\n/**\n * Structural invariants to enforce on every committed SOT file per locked spec\n * §4. Zod's schema `parse()` guarantees the *shape* of the envelope; this\n * function enforces the cross-entry *semantics* that Zod cannot express.\n *\n * Invariants (locked spec §4):\n * - **C1** Code format + uniqueness (§4.1). Format v2 uses 3-digit segments.\n * - **C2** Key format + uniqueness (§4.2).\n * - **C3** Tree: every `parentCode` resolves to an existing entry or null; no\n * cycles (§4.3).\n * - **C4** `childCodes` are the exact bidirectional inverse of `parentCode`\n * (§4.3).\n * - **C5** Selectability is a boolean (§4.4).\n * - **C6** Cross-CVC `relevantMechanisms` references resolve against a\n * provided `service_mechanisms` key set (§4.5, §7). Only checked when the\n * caller supplies `options.mechanismKeys`.\n * - **C7** _Retired in format v2_ (envelope no longer carries the shared\n * `missingness` field; missingness is per-domain and embedded in\n * `entries`). The invariant slot is intentionally left empty to preserve\n * the numbering of C1/C2/C3/C4/C5/C6/C8 in historical references.\n * - **C8** No entry anywhere contains a key `'provided'` (legacy Thread UI\n * label guard; not a canonical state).\n *\n * @param envelope Parsed envelope (typically from `CvcEnvelopeSchema.parse()`).\n * @param options.mechanismKeys Optional set of valid `service_mechanisms`\n * entry keys. If provided and the envelope entries have `relevantMechanisms`\n * fields, each referenced key must be in this set (C6).\n * @returns An array of {@link CvcValidationError}. An empty array means valid.\n */\nexport function validateCvc(\n envelope: CvcEnvelope,\n options: { mechanismKeys?: ReadonlySet<string> } = {},\n): CvcValidationError[] {\n const errors: CvcValidationError[] = [];\n const { entries } = envelope;\n\n // ── C1: code format + uniqueness ──────────────────────────────────────────\n const codeRe = /^\\d{3}(-\\d{3}){6}$/;\n const seenCodes = new Set<string>();\n for (const entry of entries) {\n if (!codeRe.test(entry.code)) {\n errors.push({\n invariant: \"C1\",\n message: `code does not match /^\\\\d{3}(-\\\\d{3}){6}$/`,\n code: entry.code,\n key: entry.key,\n });\n }\n if (seenCodes.has(entry.code)) {\n errors.push({\n invariant: \"C1\",\n message: `duplicate code`,\n code: entry.code,\n key: entry.key,\n });\n }\n seenCodes.add(entry.code);\n }\n\n // ── C2: key format + uniqueness ───────────────────────────────────────────\n const keyRe = /^[a-z][a-z0-9_]*$/;\n const seenKeys = new Set<string>();\n for (const entry of entries) {\n if (!keyRe.test(entry.key)) {\n errors.push({\n invariant: \"C2\",\n message: `key does not match /^[a-z][a-z0-9_]*$/`,\n code: entry.code,\n key: entry.key,\n });\n }\n if (seenKeys.has(entry.key)) {\n errors.push({\n invariant: \"C2\",\n message: `duplicate key`,\n code: entry.code,\n key: entry.key,\n });\n }\n seenKeys.add(entry.key);\n }\n\n // Build a lookup by code for the remaining tree checks. Skip entries whose\n // code we already know is malformed — their index would be meaningless.\n const byCode = new Map<string, CvcEntry>();\n for (const entry of entries) {\n if (codeRe.test(entry.code)) byCode.set(entry.code, entry);\n }\n\n // ── C3: tree — parents resolve, no cycles ─────────────────────────────────\n for (const entry of entries) {\n if (entry.parentCode === null) continue;\n if (!byCode.has(entry.parentCode)) {\n errors.push({\n invariant: \"C3\",\n message: `parentCode ${entry.parentCode} does not resolve to any entry in this CVC`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n // Cycle detection: walk parent chain from each entry, bail if we revisit.\n for (const entry of entries) {\n const visited = new Set<string>();\n let cursor: CvcEntry | undefined = entry;\n while (cursor && cursor.parentCode !== null) {\n if (visited.has(cursor.code)) {\n errors.push({\n invariant: \"C3\",\n message: `cycle detected in parentCode chain starting from ${entry.code}`,\n code: entry.code,\n key: entry.key,\n });\n break;\n }\n visited.add(cursor.code);\n cursor = byCode.get(cursor.parentCode);\n }\n }\n\n // ── C4: childCodes are exact inverse of parentCode ────────────────────────\n // Build the set of (parent, child) edges from parentCode, then from\n // childCodes, and require they match exactly.\n const parentToChildrenFromParent = new Map<string, Set<string>>();\n for (const entry of entries) {\n if (entry.parentCode !== null) {\n let set = parentToChildrenFromParent.get(entry.parentCode);\n if (!set) {\n set = new Set();\n parentToChildrenFromParent.set(entry.parentCode, set);\n }\n set.add(entry.code);\n }\n }\n\n for (const entry of entries) {\n const declared = new Set(entry.childCodes);\n const derived = parentToChildrenFromParent.get(entry.code) ?? new Set();\n\n for (const child of declared) {\n if (!derived.has(child)) {\n errors.push({\n invariant: \"C4\",\n message: `entry lists ${child} in childCodes but that entry's parentCode is not ${entry.code}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n for (const child of derived) {\n if (!declared.has(child)) {\n errors.push({\n invariant: \"C4\",\n message: `entry ${child} has parentCode ${entry.code} but is missing from its childCodes`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n }\n\n // ── C5: selectability per §4.4 ────────────────────────────────────────────\n // Zod already enforces `selectable: boolean`; we make the invariant explicit\n // at validator level so a future schema loosening cannot silently bypass it.\n for (const entry of entries) {\n if (typeof entry.selectable !== \"boolean\") {\n errors.push({\n invariant: \"C5\",\n message: `selectable must be a boolean, got ${typeof entry.selectable}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n // ── C6: cross-CVC refs — `relevantMechanisms` resolves against provided set\n if (options.mechanismKeys) {\n for (const entry of entries) {\n const raw = (entry as unknown as Record<string, unknown>)[\n \"relevantMechanisms\"\n ];\n if (raw === undefined || raw === null) continue;\n if (!Array.isArray(raw)) {\n errors.push({\n invariant: \"C6\",\n message: `relevantMechanisms must be an array or null`,\n code: entry.code,\n key: entry.key,\n });\n continue;\n }\n for (const mechKey of raw) {\n if (\n typeof mechKey !== \"string\" ||\n !options.mechanismKeys.has(mechKey)\n ) {\n errors.push({\n invariant: \"C6\",\n message: `relevantMechanisms references unknown service_mechanisms key: ${String(mechKey)}`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n }\n }\n\n // ── C8: legacy `'provided'` key guard ─────────────────────────────────────\n // Walk every property of every entry (including nested arrays) looking for\n // a key named `'provided'`. It is a Thread UI label, not a canonical state.\n const walkForProvided = (value: unknown, entry: CvcEntry): void => {\n if (value === null || value === undefined) return;\n if (Array.isArray(value)) {\n for (const item of value) walkForProvided(item, entry);\n return;\n }\n if (typeof value === \"object\") {\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n if (k === \"provided\") {\n errors.push({\n invariant: \"C8\",\n message: `entry contains forbidden legacy key 'provided' (see locked spec §4)`,\n code: entry.code,\n key: entry.key,\n });\n }\n walkForProvided(v, entry);\n }\n }\n };\n for (const entry of entries) {\n walkForProvided(entry, entry);\n // Also guard against a literal string value of 'provided' appearing as an\n // entry's `key`, which would be an obvious smuggling attempt.\n if (entry.key === \"provided\") {\n errors.push({\n invariant: \"C8\",\n message: `entry key must not be the legacy label 'provided'`,\n code: entry.code,\n key: entry.key,\n });\n }\n }\n\n return errors;\n}\n","/**\n * @htilabs/platform-common-models — CVC `_status`/`_source` provenance parser\n *\n * Problem this solves: `_status` on a SOT envelope (`src/cvcs/*.json`) is\n * unvalidated free text (115 of 179 domains carry it; the rest predate the\n * convention). A consumer that wants to know \"is this actually a draft?\" has\n * had to eyeball a string like\n *\n * \"DRAFT — TEMPORARY: net-new value-CVC not yet in Notion; provisional\n * 900+ numbering; codes from prototype/data/cvcs/core_accommodation_type\n * .yaml; PENDING canonical Notion authoring (PAVE Auditability backlog).\"\n *\n * and get it right past two real traps observed across the current\n * population:\n * - A leading `\"CANONICAL — …\"` marker is a PROVENANCE note on an\n * ALREADY-ratified file, not a maturity warning — it must not be lumped\n * in with `\"DRAFT\"`/`\"PROVISIONAL\"`.\n * - `core_functions` is self-contradictory: it leads\n * `\"DRAFTED — NEEDS REVIEW\"` but the same string continues\n * `\"…Canonical numbering (133), NOT provisional.\"` A naive\n * leading-word reader silently picks one side; this parser flags it.\n *\n * This module is a pure, additive, standalone export. It does NOT touch\n * `CvcEnvelopeSchema` (`./cvc.ts`) — `_status`/`_source` are intentionally\n * outside that Zod schema (see its module header), and adding them there\n * would risk changing parse behavior for every existing consumer. Callers\n * pass the RAW parsed JSON object (before or instead of\n * `CvcEnvelopeSchema.parse()`), not the Zod-inferred `CvcEnvelope`.\n *\n * Classification rule (leading token of `_status`, case-insensitive):\n * - contains \"draft\" → `maturity: \"draft\"`\n * - contains \"provisional\" → `maturity: \"provisional\"`\n * - contains \"canonical\" → `maturity: \"canonical\"` (a provenance note on\n * an already-ratified file, NOT a maturity flag — kept distinct from\n * `\"final\"` below so a caller can tell \"explicitly marked ratified\"\n * apart from \"predates the convention entirely\")\n * - `_status` absent entirely → `maturity: \"final\"` (legacy/unmarked)\n *\n * One real domain (`share_purpose` — \"Synced verbatim from canonical\n * CVC-84…\") has a present `_status` whose LEADING token (\"Synced\") is none\n * of the three convention words. Rather than mis-file it as `\"final\"` (which\n * per the rule above is reserved for an ABSENT field) this parser falls back\n * to scanning the full string for a single unambiguous keyword family before\n * giving up — see `detectMaturity` below.\n */\n\n// ─── Public shape ───────────────────────────────────────────────────────────\n\n/**\n * The subset of a raw (pre-validation) SOT envelope this parser reads.\n * Deliberately NOT the Zod-inferred `CvcEnvelope` from `./cvc.ts` — that type\n * is the *parsed* shape, which does not declare `_status`/`_source` at all\n * (they live outside the locked envelope schema on purpose). Pass the raw\n * `JSON.parse()` result of a `src/cvcs/*.json` file here.\n */\nexport interface RawCvcEnvelopeProvenance {\n _status?: unknown;\n _source?: unknown;\n}\n\n/** The four observed maturity states. See module header for the rule. */\nexport type CvcMaturity = \"draft\" | \"provisional\" | \"canonical\" | \"final\";\n\nexport interface CvcStatusInfo {\n /** One of the four states; see module header for the classification rule. */\n maturity: CvcMaturity;\n /**\n * The text this parser classified. For a string `_status` this is that\n * string verbatim. For the 11 domains authored with a structured\n * `_status` object (`{ vocabStatus, authoredBy, evidence, … }` — e.g.\n * `citizenship`, `core_functions`'s sibling `countries`), this is\n * `_status.vocabStatus` — the field those envelopes use for exactly this\n * purpose — not the whole object. `null` iff `_status` is absent.\n */\n rawStatus: string | null;\n /** True iff `_source` cites a `prototype/data/cvcs/*.yaml` path. */\n sourceIsPrototype: boolean;\n /** The cited `prototype/data/cvcs/*.yaml` path, or `null` if none. */\n sourcePath: string | null;\n /**\n * True when the classification is a judgment call rather than a clean\n * read: either the leading token disagrees with a later\n * \"NOT draft\"/\"NOT provisional\"/\"NOT canonical\" qualifier in the same\n * string (the `core_functions` shape — generic, not special-cased, so any\n * future domain authored in the same self-contradictory shape is also\n * caught), or the string carries more than one maturity keyword family\n * with no leading token to arbitrate between them.\n */\n ambiguous: boolean;\n}\n\n// ─── Implementation ─────────────────────────────────────────────────────────\n\nconst MATURITY_KEYWORDS: ReadonlyArray<{\n keyword: string;\n maturity: Exclude<CvcMaturity, \"final\">;\n}> = [\n { keyword: \"draft\", maturity: \"draft\" },\n { keyword: \"provisional\", maturity: \"provisional\" },\n { keyword: \"canonical\", maturity: \"canonical\" },\n];\n\n/** Matches a `prototype/data/cvcs/<file>.yaml` citation anywhere in `_source`. */\nconst PROTOTYPE_SOURCE_RE = /(prototype\\/data\\/cvcs\\/[A-Za-z0-9_.-]+\\.yaml)/;\n\n/**\n * A maturity keyword explicitly negated (\"NOT provisional.\") anywhere in the\n * string — the self-contradiction signal. Deliberately scans the WHOLE\n * string (not just past the leading token): the qualifier that disagrees\n * with the leading word is, by construction, never the leading word itself.\n */\nconst NEGATED_MATURITY_RE = /\\bnot\\s+(draft|provisional|canonical)\\b/i;\n\n/**\n * Extract the text this parser classifies against, from either `_status`\n * shape observed in the current SOT population:\n * - `string` (104 of 115 status-bearing domains) → the string itself.\n * - `{ vocabStatus: string, … }` (11 domains — a richer, hand-authored\n * provenance record) → `vocabStatus`, the field those envelopes use for\n * exactly this classification (values seen: `\"canonical\"` and\n * `\"provisional-pending-notion-ratification\"`).\n * - Anything else present but shapeless (unseen in the current 179-domain\n * population) → `JSON.stringify` as a last resort, so a future oddity\n * still gets a best-effort classification instead of silently vanishing.\n * - Absent → `null`.\n */\nfunction extractClassificationText(status: unknown): string | null {\n if (typeof status === \"string\") return status;\n if (status !== null && typeof status === \"object\") {\n const vocabStatus = (status as Record<string, unknown>).vocabStatus;\n if (typeof vocabStatus === \"string\") return vocabStatus;\n return JSON.stringify(status);\n }\n return null;\n}\n\n/** The first \"word\" of a status string, lowercased, for the leading-token rule. */\nfunction leadingToken(text: string): string {\n return (text.trim().split(/[\\s—–:-]+/, 1)[0] ?? \"\").toLowerCase();\n}\n\n/**\n * Classify a present, non-null `_status` text into a maturity + ambiguity\n * flag. Isolated from {@link parseCvcStatus} so the fallback path (the\n * `share_purpose` shape) and the negation check are each unit-testable in\n * isolation.\n */\nfunction detectMaturity(text: string): { maturity: Exclude<CvcMaturity, \"final\">; ambiguous: boolean } {\n const lead = leadingToken(text);\n const leadMatch = MATURITY_KEYWORDS.find(({ keyword }) => lead.includes(keyword));\n\n let maturity: Exclude<CvcMaturity, \"final\">;\n if (leadMatch) {\n maturity = leadMatch.maturity;\n } else {\n // The leading token is none of the three convention words. Observed once\n // in the current population: `share_purpose`'s\n // \"Synced verbatim from canonical CVC-84…\" — \"Synced\" leads, but the\n // string is unambiguously describing an already-ratified vocabulary.\n // Fall back to scanning the WHOLE string for maturity keyword families\n // rather than defaulting to \"final\": the field IS present, and \"final\"\n // per the module-header rule is reserved for an ABSENT `_status`.\n const foundFamilies = MATURITY_KEYWORDS.filter(({ keyword }) =>\n new RegExp(`\\\\b${keyword}\\\\w*\\\\b`, \"i\").test(text),\n );\n const distinctFamilies = new Set(foundFamilies.map((f) => f.maturity));\n if (distinctFamilies.size === 1) {\n // Single unambiguous family found in the body — safe to accept.\n maturity = foundFamilies[0].maturity;\n return { maturity, ambiguous: false };\n }\n if (distinctFamilies.size > 1) {\n // Multiple families present with no leading token to arbitrate.\n // Report the first-occurring family as a best-effort primary and let\n // the caller see `ambiguous: true` — never silently pick a winner.\n maturity = foundFamilies[0].maturity;\n return { maturity, ambiguous: true };\n }\n // No maturity keyword anywhere in a present `_status` string. Unseen in\n // the current 179-domain population; treat conservatively as\n // \"provisional\" (the least-committal non-final bucket) rather than\n // silently promoting an unrecognized status to a settled one, and flag\n // it for human attention.\n return { maturity: \"provisional\", ambiguous: true };\n }\n\n return { maturity, ambiguous: NEGATED_MATURITY_RE.test(text) };\n}\n\n/**\n * Parse a SOT envelope's `_status`/`_source` provenance fields into a\n * structured, typed result. Pure function — no filesystem access, no\n * dependency on `CvcEnvelopeSchema`. See module header for the full rule and\n * the two known traps it exists to catch.\n */\nexport function parseCvcStatus(envelope: RawCvcEnvelopeProvenance): CvcStatusInfo {\n const source = typeof envelope._source === \"string\" ? envelope._source : null;\n const protoMatch = source?.match(PROTOTYPE_SOURCE_RE) ?? null;\n const sourceIsPrototype = protoMatch !== null;\n const sourcePath = protoMatch?.[1] ?? null;\n\n const text = extractClassificationText(envelope._status);\n if (text === null) {\n return { maturity: \"final\", rawStatus: null, sourceIsPrototype, sourcePath, ambiguous: false };\n }\n\n const { maturity, ambiguous } = detectMaturity(text);\n return { maturity, rawStatus: text, sourceIsPrototype, sourcePath, ambiguous };\n}\n","/**\n * @htilabs/platform-common-models — Team directory field validation\n *\n * Zod schemas for the team directory fields declared in\n * `../schemas/team.ts`, the fields the Thread→PAVE \"Refer to intake\" preset\n * reads. See that module for canon citations and the two deliberate\n * divergences (`apps` uses the {@link PLATFORM_TOOL} codes, and `canReferTo`\n * sits on the team because there is no Program model).\n *\n * This is the wire / API shape: ids are 24-hex strings, not ObjectIds. Merge\n * {@link TeamDirectoryFieldsSchema} into a consumer's team schema with\n * `.merge()` or `.extend(TeamDirectoryFieldsSchema.shape)`.\n */\n\nimport { z } from \"zod\";\nimport { PLATFORM_TOOL_VALUES } from \"../constants/platform-auth.js\";\n\n/** A Mongo ObjectId serialized as a 24-character hex string. */\nconst ObjectIdHexSchema = z\n .string()\n .regex(/^[0-9a-fA-F]{24}$/, \"must be a 24-character hex ObjectId\");\n\nconst hasNoDuplicates = (values: readonly string[]): boolean =>\n new Set(values.map((v) => v.toLowerCase())).size === values.length;\n\n/** One platform app a team works in: a {@link PLATFORM_TOOL} code. */\nexport const TeamAppSchema = z.enum(PLATFORM_TOOL_VALUES);\n\n/**\n * The team directory fields. Both are optional, so a team payload without\n * them validates unchanged. When present, neither list may repeat a value.\n */\nexport const TeamDirectoryFieldsSchema = z.object({\n apps: z\n .array(TeamAppSchema)\n .refine(hasNoDuplicates, \"apps must not repeat an app\")\n .optional(),\n canReferTo: z\n .array(ObjectIdHexSchema)\n .refine(hasNoDuplicates, \"canReferTo must not repeat a team\")\n .optional(),\n});\n\n/** A platform app code accepted on a team. */\nexport type TeamApp = z.infer<typeof TeamAppSchema>;\n\n/** Wire shape of the team directory fields (ids as hex strings). */\nexport type TeamDirectoryFieldsInput = z.infer<typeof TeamDirectoryFieldsSchema>;\n","/**\n * @htilabs/platform-common-models — Platform Authorization Constants\n *\n * Enums and labels for the platform role/function permission model.\n * Includes permission states, share view levels, tool codes, role levels,\n * and function implementation statuses.\n *\n * Source: PLATFORM_AUTH_SPEC.md Sections 5 + 6\n */\n\n// ─── Permission State (4-state role→function mapping) ──────────────\n\nexport const PERMISSION_STATE = {\n /** Role can always perform this function (mandatory, cannot disable). */\n ALWAYS: \"ALWAYS\",\n /** Default On — user can opt off. */\n PREF_YES: \"PREF_YES\",\n /** Default Off — user can opt in. */\n PREF_NO: \"PREF_NO\",\n /** Role is explicitly barred from this function. */\n NEVER: \"NEVER\",\n} as const;\n\nexport type PermissionStateValue =\n (typeof PERMISSION_STATE)[keyof typeof PERMISSION_STATE];\n\nexport const PERMISSION_STATE_VALUES = [\n PERMISSION_STATE.ALWAYS,\n PERMISSION_STATE.PREF_YES,\n PERMISSION_STATE.PREF_NO,\n PERMISSION_STATE.NEVER,\n] as const;\n\nexport const PERMISSION_STATE_LABELS: Record<PermissionStateValue, string> = {\n [PERMISSION_STATE.ALWAYS]: \"Always\",\n [PERMISSION_STATE.PREF_YES]: \"Default On\",\n [PERMISSION_STATE.PREF_NO]: \"Default Off\",\n [PERMISSION_STATE.NEVER]: \"Never\",\n};\n\n/** UI display metadata for permission states (colors, icons). */\nexport const PERMISSION_STATE_DISPLAY: Record<\n PermissionStateValue,\n { label: string; color: string; bgColor: string; icon: string }\n> = {\n [PERMISSION_STATE.ALWAYS]: {\n label: \"Always\",\n color: \"#2e7d32\",\n bgColor: \"#e8f5e9\",\n icon: \"\\u{1F512}\",\n },\n [PERMISSION_STATE.PREF_YES]: {\n label: \"Default On\",\n color: \"#1565c0\",\n bgColor: \"#e3f2fd\",\n icon: \"\\u{1F513}\",\n },\n [PERMISSION_STATE.PREF_NO]: {\n label: \"Default Off\",\n color: \"#e65100\",\n bgColor: \"#fff3e0\",\n icon: \"\\u{1F513}\",\n },\n [PERMISSION_STATE.NEVER]: {\n label: \"Never\",\n color: \"#c62828\",\n bgColor: \"#ffebee\",\n icon: \"\\u{1F512}\",\n },\n};\n\n// ─── Share View (data visibility for shared records) ───────────────\n\nexport const SHARE_VIEW = {\n /** System metadata only (partial access). */\n SYS_INFO: \"sys_info\",\n /** Full case/record content. */\n ALL: \"all\",\n /** No data access. */\n NONE: \"none\",\n} as const;\n\nexport type ShareViewValue = (typeof SHARE_VIEW)[keyof typeof SHARE_VIEW];\n\nexport const SHARE_VIEW_VALUES = [\n SHARE_VIEW.SYS_INFO,\n SHARE_VIEW.ALL,\n SHARE_VIEW.NONE,\n] as const;\n\nexport const SHARE_VIEW_LABELS: Record<ShareViewValue, string> = {\n [SHARE_VIEW.SYS_INFO]: \"System Info Only\",\n [SHARE_VIEW.ALL]: \"Full Content\",\n [SHARE_VIEW.NONE]: \"No Data Access\",\n};\n\n// ─── Platform Tool Codes ───────────────────────────────────────────\n\nexport const PLATFORM_TOOL = {\n PAVE: \"PAVE\",\n ECHO: \"ECHO\",\n LEADS: \"LEADS\",\n THREAD: \"THREAD\",\n TRAIL: \"TRAIL\",\n PLATFORM: \"PLATFORM\",\n} as const;\n\nexport type PlatformToolValue =\n (typeof PLATFORM_TOOL)[keyof typeof PLATFORM_TOOL];\n\nexport const PLATFORM_TOOL_VALUES = [\n PLATFORM_TOOL.PAVE,\n PLATFORM_TOOL.ECHO,\n PLATFORM_TOOL.LEADS,\n PLATFORM_TOOL.THREAD,\n PLATFORM_TOOL.TRAIL,\n PLATFORM_TOOL.PLATFORM,\n] as const;\n\nexport const PLATFORM_TOOL_LABELS: Record<PlatformToolValue, string> = {\n [PLATFORM_TOOL.PAVE]: \"PAVE\",\n [PLATFORM_TOOL.ECHO]: \"Echo\",\n [PLATFORM_TOOL.LEADS]: \"LEADS\",\n [PLATFORM_TOOL.THREAD]: \"Thread\",\n [PLATFORM_TOOL.TRAIL]: \"Trail\",\n [PLATFORM_TOOL.PLATFORM]: \"Platform\",\n};\n\n// ─── Role Level (hierarchy tiers) ──────────────────────────────────\n\nexport const ROLE_LEVEL = {\n /** User-facing roles (staff, volunteers, practitioners). */\n OPERATIONAL: \"operational\",\n /** Agency-level admin roles. */\n AGENCY: \"agency\",\n /** Team-level admin roles. */\n TEAM: \"team\",\n /** HTI-wide platform admin. */\n PLATFORM: \"platform\",\n /** External governance/oversight roles. */\n OVERSIGHT: \"oversight\",\n} as const;\n\nexport type RoleLevelValue = (typeof ROLE_LEVEL)[keyof typeof ROLE_LEVEL];\n\nexport const ROLE_LEVEL_VALUES = [\n ROLE_LEVEL.OPERATIONAL,\n ROLE_LEVEL.AGENCY,\n ROLE_LEVEL.TEAM,\n ROLE_LEVEL.PLATFORM,\n ROLE_LEVEL.OVERSIGHT,\n] as const;\n\nexport const ROLE_LEVEL_LABELS: Record<RoleLevelValue, string> = {\n [ROLE_LEVEL.OPERATIONAL]: \"Operational\",\n [ROLE_LEVEL.AGENCY]: \"Agency\",\n [ROLE_LEVEL.TEAM]: \"Team\",\n [ROLE_LEVEL.PLATFORM]: \"Platform\",\n [ROLE_LEVEL.OVERSIGHT]: \"Oversight\",\n};\n\n// ─── Function Implementation Status ────────────────────────────────\n\nexport const FUNCTION_STATUS = {\n NOT_STARTED: \"Not started\",\n DEFINED_NEW: \"Defined; new function\",\n DEFINED_EXISTING: \"Defined; existing PAVE function\",\n FUNCTIONAL: \"Functional on all apps\",\n FUTURE: \"Future function (not v1)\",\n} as const;\n\nexport type FunctionStatusValue =\n (typeof FUNCTION_STATUS)[keyof typeof FUNCTION_STATUS];\n\nexport const FUNCTION_STATUS_VALUES = [\n FUNCTION_STATUS.NOT_STARTED,\n FUNCTION_STATUS.DEFINED_NEW,\n FUNCTION_STATUS.DEFINED_EXISTING,\n FUNCTION_STATUS.FUNCTIONAL,\n FUNCTION_STATUS.FUTURE,\n] as const;\n\nexport const FUNCTION_STATUS_LABELS: Record<FunctionStatusValue, string> = {\n [FUNCTION_STATUS.NOT_STARTED]: \"Not Started\",\n [FUNCTION_STATUS.DEFINED_NEW]: \"Defined (New)\",\n [FUNCTION_STATUS.DEFINED_EXISTING]: \"Defined (Existing PAVE)\",\n [FUNCTION_STATUS.FUNCTIONAL]: \"Functional\",\n [FUNCTION_STATUS.FUTURE]: \"Future (Not v1)\",\n};\n","/**\n * @htilabs/platform-common-models — Agency organization-type field validation\n *\n * Zod schemas for the organization-type fields declared in\n * `../schemas/agency.ts`. These are WRITE shapes — what an Admin Hub\n * \"Organization Type\" write, a provisioning payload or a backfill row may\n * carry. They are deliberately strict: a legacy free-text `type` or a\n * `null` does not parse. Do not validate a pre-backfill `/me` or directory\n * READ with them; until the backfill lands, a read may still carry free text\n * (resolve it with `resolveAgencyTypeKey`, which answers `null` for it).\n * See `../schemas/agency.ts` and `../constants/org-type.ts` for the ruling\n * and the vocabulary.\n *\n * Merge the fields into a consumer's org / agency schema with\n * {@link withOrgTypeFields} — it adds the fields AND re-applies the two-step\n * rule in one call. The raw `orgTypeFieldsShape` is still exported for a\n * consumer that must build its own object, but `.extend(orgTypeFieldsShape)`\n * without `.refine(vspTwoStepHolds, VSP_TWO_STEP_ISSUE)` silently drops the\n * rule (review nit — the extend-without-refine footgun); prefer the helper.\n * The Mongoose mount enforces the same rule on save and update regardless,\n * so a forgotten refine is caught at the database, not persisted.\n * (ORG-TYPE-REVIEW-ROUND-2026-10-08)\n *\n * Naming: `OrgTypeSelectableKey*` means a SELECTABLE leaf (what may be set);\n * `AgencyTypeKey*` means a STORABLE value (a leaf or `unknown`). The\n * constants module's `OrgTypeKey` is wider than both — heading OR leaf — and\n * is never a write type.\n */\n\nimport { z } from \"zod\";\nimport {\n AGENCY_TYPE_KEYS,\n ORG_TYPE_SELECTABLE_KEYS,\n type AgencyTypeKey,\n type OrgTypeSelectableKey,\n} from \"../constants/org-type.js\";\nimport { VSP_TWO_STEP_ISSUE, vspTwoStepHolds } from \"../schemas/agency.js\";\n\n// The two-step predicate lives with the Mongoose mount (one definition,\n// enforced in Zod, on save, on update and in the mirror); re-exported here so\n// `validation` callers keep their import.\nexport { VSP_TWO_STEP_ISSUE, vspTwoStepHolds };\n\n/** An org type the Admin Hub may SET: a selectable CVC-48 org-type leaf. */\nexport const OrgTypeSelectableKeySchema = z.enum(ORG_TYPE_SELECTABLE_KEYS);\n\n/** An org type an agency may be STORED with: a selectable leaf or `unknown`. */\nexport const AgencyTypeKeySchema = z.enum(AGENCY_TYPE_KEYS);\n\n/**\n * The organization-type fields on an agency, as a WRITE shape. All optional,\n * so an agency payload without them validates unchanged; when present each\n * must be well-formed (`type` a storable key, the booleans booleans).\n */\nexport const orgTypeFieldsShape = {\n type: AgencyTypeKeySchema.optional(),\n vsp: z.boolean().optional(),\n vspPrivateNonprofit: z.boolean().optional(),\n} as const;\nexport const AgencyOrgTypeFieldsSchema = z\n .object(orgTypeFieldsShape)\n .refine(vspTwoStepHolds, VSP_TWO_STEP_ISSUE);\n\n/**\n * A consumer's own org / agency write shape PLUS the organization-type\n * fields, with the two-step rule applied — the one call that cannot forget\n * the refine. `withOrgTypeFields({ name: z.string() })` ≡\n * `z.object({ name, ...orgTypeFieldsShape }).refine(vspTwoStepHolds, …)`.\n */\nexport function withOrgTypeFields<T extends z.ZodRawShape>(shape: T) {\n return z\n .object({ ...shape, ...orgTypeFieldsShape })\n .refine(vspTwoStepHolds, VSP_TWO_STEP_ISSUE);\n}\n\n/** The same WRITE shape, named for its home: the Org registry row. */\nexport const OrgTypeFieldsSchema = AgencyOrgTypeFieldsSchema;\n\n/**\n * What the Admin Hub writes when it sets an organization's type: the type\n * itself (required; a selectable leaf — never `unknown`, never a heading),\n * with the two attested answers. `vsp` and `vspPrivateNonprofit` are\n * privileged writes (the sender's `vsp` decides the release check), so the\n * shape is `.strict()`: an unexpected key is rejected rather than ignored.\n * `requires_roi` is NOT written through this shape — it is not one of the\n * organization-type fields (informational, GDR § 5.17; parked Q-O5).\n */\nexport const SetOrgTypeInputSchema = z\n .object({\n type: OrgTypeSelectableKeySchema,\n vsp: z.boolean().optional(),\n vspPrivateNonprofit: z.boolean().optional(),\n })\n .strict()\n .refine(vspTwoStepHolds, VSP_TWO_STEP_ISSUE);\n\n/** A selectable leaf, as the Zod schema infers it (= {@link OrgTypeSelectableKey}). */\nexport type OrgTypeSelectableKeyInput = OrgTypeSelectableKey;\n/** A storable agency type, as the Zod schema infers it (= {@link AgencyTypeKey}). */\nexport type AgencyTypeKeyInput = AgencyTypeKey;\nexport type AgencyOrgTypeFieldsInput = z.infer<\n typeof AgencyOrgTypeFieldsSchema\n>;\nexport type SetOrgTypeInput = z.infer<typeof SetOrgTypeInputSchema>;\n\n// Compile-time pin: the Zod-inferred unions equal the constants' types.\nconst _selectablePin: z.infer<\n typeof OrgTypeSelectableKeySchema\n> extends OrgTypeSelectableKey\n ? OrgTypeSelectableKey extends z.infer<typeof OrgTypeSelectableKeySchema>\n ? true\n : never\n : never = true;\nconst _agencyPin: z.infer<typeof AgencyTypeKeySchema> extends AgencyTypeKey\n ? AgencyTypeKey extends z.infer<typeof AgencyTypeKeySchema>\n ? true\n : never\n : never = true;\nvoid [_selectablePin, _agencyPin];\n","{\n \"domain\": \"referral_entity_category\",\n \"name\": \"Core Referral Entity Category\",\n \"version\": \"1.2.0\",\n \"_status\": \"CANONICAL — Notion CVC-48 `core-referral_entity_category` (IC-58), status Active (full audit 2026-08-20, CVC48_IC58_REFERRAL_ENTITY_CATEGORY_AUDIT; `Date of last audit` 2026-09-01). Re-mirrored from prototype canon yaml v1.3 @ f1321e47 and the live Notion codebook (46 rows, compared row by row 2026-10-05). SUPERSEDES referralEntityCategory v1.0.0 (platform-common <= 0.13.0), which predated the audit. ADDITIVE: no v1.0.0 key is removed and no v1.0.0 positional code changes. ADDED (4): `adult_protective_services` (02-03-06-00), `school_academic_institution` (02-05-01-00), `legal_services_provider` (02-06-04-00), and since 0.18.0 `hotline` (02-02-01-00, canon's selectable Level-2 parent of the two hotline children) at the next free ordinal 048-006-003 with `national_hotline` / `local_other_hotline` RE-PARENTED under it — their codes are unchanged (a positional code is identity, `parentCode` is hierarchy). SELECTABLE follows canon on two rows: `education` is now a non-selectable heading (its leaf is `school_academic_institution`, which carries the HMIS R1 School rollup — ruled 2026-08-20) and `law_enforcement` is now selectable (canon Level 2 Required; its five children are optional depth). A stored `education` is still a valid key. `title` and `definition` are canon's, verbatim (yaml `name` / `definition`; the live Notion wording where the two differ: the Adult Protective Services label, the quotation marks in the Victim service provider definition, and the wording of the residual Community-based provider definition); the Level-0 rows keep the package's house missingness titles. `justice_protective_systems` no longer carries the package-authored definition v1.0.0 gave it: canon's heading (02-03-00-00) has none. Every canon-backed row carries canon's 4-segment code as `canonicalCode`; the package's own positional codes are unchanged and are NOT canon's. NOT carried: canon `hmis_r1_code` / `hmis_r1_mapping`, `required`, `voca_ovc_pmt_bucket`, `pave_2025_mapping`, `logic_notes`, `mappings_notes` (v1.0.0 carried none of them). CARRIED since 0.18.0: canon `enum_constant` as `enumConstant` on every canon-backed row (the Sean-spec constant the org registry / `agencies.typeId` spell the type with). Generated by scripts/gen-referral-entity-category.py — do not hand-edit.\",\n \"_source\": \"htilabstech/prototype/data/cvcs/core_referral_entity_category.yaml @ f1321e47 (Notion CVC-48, yaml v1.3; read from origin/main) + Notion codebook collection://3181ef14-abcd-8081-95b5-000bc30a73bd (wording of 3 cells, compared 2026-10-05)\",\n \"_supersedes\": {\n \"version\": \"1.0.0\",\n \"keyMap\": {\n \"missingness_root\": \"missingness_root\",\n \"unknown\": \"unknown\",\n \"anonymous\": \"anonymous\",\n \"data_not_collected\": \"data_not_collected\",\n \"self_referred\": \"self_referred\",\n \"family_guardian_friend\": \"family_guardian_friend\",\n \"peer\": \"peer\",\n \"other_individual\": \"other_individual\",\n \"housing_shelter_continuum\": \"housing_shelter_continuum\",\n \"outreach_project\": \"outreach_project\",\n \"temporary_shelter\": \"temporary_shelter\",\n \"residential_project\": \"residential_project\",\n \"hotlines\": \"hotlines\",\n \"national_hotline\": \"national_hotline\",\n \"local_other_hotline\": \"local_other_hotline\",\n \"justice_protective_systems\": \"justice_protective_systems\",\n \"child_welfare_cps\": \"child_welfare_cps\",\n \"juvenile_justice\": \"juvenile_justice\",\n \"law_enforcement\": \"law_enforcement\",\n \"local_law_enforcement\": \"local_law_enforcement\",\n \"state_law_enforcement\": \"state_law_enforcement\",\n \"federal_law_enforcement\": \"federal_law_enforcement\",\n \"tribal_law_enforcement\": \"tribal_law_enforcement\",\n \"other_law_enforcement\": \"other_law_enforcement\",\n \"courts_prosecution\": \"courts_prosecution\",\n \"correction_probation\": \"correction_probation\",\n \"health_behavioral_health\": \"health_behavioral_health\",\n \"inpatient_psychiatric_facility\": \"inpatient_psychiatric_facility\",\n \"healthcare_provider\": \"healthcare_provider\",\n \"education\": \"education\",\n \"victim_community_service_providers\": \"victim_community_service_providers\",\n \"child_advocacy_center\": \"child_advocacy_center\",\n \"victim_service_provider\": \"victim_service_provider\",\n \"community_based_service_provider\": \"community_based_service_provider\",\n \"coordination_governance\": \"coordination_governance\",\n \"mdt\": \"mdt\",\n \"coalition\": \"coalition\",\n \"internal\": \"internal\",\n \"own_agency_internal\": \"own_agency_internal\",\n \"other_entity\": \"other_entity\",\n \"employer\": \"employer\",\n \"benefits_public_assistance_office\": \"benefits_public_assistance_office\",\n \"other_organization\": \"other_organization\"\n },\n \"retiredCodes\": [],\n \"notes\": {\n \"education\": \"v1.0.0 `education` was a selectable leaf. Canon makes Education a heading whose only leaf is School / academic institution. `education` stays a valid stored key (now `selectable: false`); the specific successor for a school is `school_academic_institution`. Not mapped automatically.\",\n \"law_enforcement\": \"v1.0.0 `law_enforcement` was a non-selectable heading. Canon makes Law enforcement / Police a selectable leaf with five optional children.\"\n }\n },\n \"_notCarried\": [],\n \"levels\": {\n \"0\": \"Unknown or Missing\",\n \"1\": \"Category\",\n \"2\": \"Entity\",\n \"3\": \"Variant\"\n },\n \"entries\": [\n {\n \"code\": \"048-000-000-000-000-000-000\",\n \"key\": \"missingness_root\",\n \"title\": \"Unknown, Redacted, or Missing\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-000-000-000-000-000-001\",\n \"048-000-000-000-000-000-002\",\n \"048-000-000-000-000-000-003\"\n ],\n \"definition\": \"Root group for values indicating absent, withheld, or uncollected data.\"\n },\n {\n \"code\": \"048-000-000-000-000-000-001\",\n \"key\": \"unknown\",\n \"title\": \"Unknown\",\n \"selectable\": true,\n \"parentCode\": \"048-000-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Referral entity category unknown.\",\n \"canonicalCode\": \"00-00-01-00\",\n \"enumConstant\": \"EMPTY_RESPONSE_UNKNOWN\"\n },\n {\n \"code\": \"048-000-000-000-000-000-002\",\n \"key\": \"anonymous\",\n \"title\": \"Anonymous\",\n \"selectable\": true,\n \"parentCode\": \"048-000-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Referral entity category withheld or redacted.\",\n \"canonicalCode\": \"00-00-02-00\",\n \"enumConstant\": \"EMPTY_RESPONSE_ANONYMOUS\"\n },\n {\n \"code\": \"048-000-000-000-000-000-003\",\n \"key\": \"data_not_collected\",\n \"title\": \"Data not collected\",\n \"selectable\": true,\n \"parentCode\": \"048-000-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Referral entity category not collected or no signal captured.\",\n \"canonicalCode\": \"00-00-03-00\",\n \"enumConstant\": \"EMPTY_RESPONSE_NOTCOLLECTED\"\n },\n {\n \"code\": \"048-001-000-000-000-000-000\",\n \"key\": \"self_referred\",\n \"title\": \"Self-referred\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Client initiated contact or presented for services without a third-party referrer.\",\n \"canonicalCode\": \"01-00-01-00\",\n \"enumConstant\": \"INDIVIDUAL_PERSON_SELFREFERRED\"\n },\n {\n \"code\": \"048-002-000-000-000-000-000\",\n \"key\": \"family_guardian_friend\",\n \"title\": \"Family/guardian/friend/foster parent\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"A caregiver, family member, or close personal support person initiated the referral.\",\n \"canonicalCode\": \"01-00-02-00\",\n \"enumConstant\": \"INDIVIDUAL_PERSON_FAMILYGUARDIANFRIEND\"\n },\n {\n \"code\": \"048-003-000-000-000-000-000\",\n \"key\": \"peer\",\n \"title\": \"Peer / another client\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Another current or former client initiated or encouraged the referral.\",\n \"canonicalCode\": \"01-00-03-00\",\n \"enumConstant\": \"INDIVIDUAL_PERSON_PEER\"\n },\n {\n \"code\": \"048-004-000-000-000-000-000\",\n \"key\": \"other_individual\",\n \"title\": \"Other individual\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"A non-family individual initiated the referral (e.g., neighbor, community member, clergy).\",\n \"canonicalCode\": \"01-00-04-00\",\n \"enumConstant\": \"INDIVIDUAL_PERSON_OTHER\"\n },\n {\n \"code\": \"048-005-000-000-000-000-000\",\n \"key\": \"housing_shelter_continuum\",\n \"title\": \"Housing / Shelter continuum\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-005-001-000-000-000-000\",\n \"048-005-002-000-000-000-000\",\n \"048-005-003-000-000-000-000\"\n ],\n \"definition\": \"Primary function is outreach engagement, emergency shelter, or residential shelter/housing programs.\",\n \"canonicalCode\": \"02-01-00-00\",\n \"enumConstant\": \"ORGANIZATION_HOUSING\"\n },\n {\n \"code\": \"048-005-001-000-000-000-000\",\n \"key\": \"outreach_project\",\n \"title\": \"Outreach Project\",\n \"selectable\": true,\n \"parentCode\": \"048-005-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Street/community outreach program that engaged the client prior to enrollment.\",\n \"canonicalCode\": \"02-01-01-00\",\n \"enumConstant\": \"ORGANIZATION_HOUSING_OUTREACHPROJECT\"\n },\n {\n \"code\": \"048-005-002-000-000-000-000\",\n \"key\": \"temporary_shelter\",\n \"title\": \"Temporary Shelter\",\n \"selectable\": true,\n \"parentCode\": \"048-005-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Emergency/crisis shelter or short-term temporary housing program.\",\n \"canonicalCode\": \"02-01-02-00\",\n \"enumConstant\": \"ORGANIZATION_HOUSING_TEMPORARYSHELTER\"\n },\n {\n \"code\": \"048-005-003-000-000-000-000\",\n \"key\": \"residential_project\",\n \"title\": \"Residential Project\",\n \"selectable\": true,\n \"parentCode\": \"048-005-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Longer-term residential or transitional living program.\",\n \"canonicalCode\": \"02-01-03-00\",\n \"enumConstant\": \"ORGANIZATION_HOUSING_RESIDENTIALPROJECT\"\n },\n {\n \"code\": \"048-006-000-000-000-000-000\",\n \"key\": \"hotlines\",\n \"title\": \"Hotlines\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-006-003-000-000-000-000\"\n ],\n \"definition\": \"Crisis lines or call centers that connect a person to services.\",\n \"canonicalCode\": \"02-02-00-00\",\n \"enumConstant\": \"ORGANIZATION_CALLCENTERS\"\n },\n {\n \"code\": \"048-006-001-000-000-000-000\",\n \"key\": \"national_hotline\",\n \"title\": \"National hotline\",\n \"selectable\": true,\n \"parentCode\": \"048-006-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"National-level hotline network.\",\n \"canonicalCode\": \"02-02-01-01\",\n \"enumConstant\": \"ORGANIZATION_CALLCENTERS_HOTLINE_NATIONAL\"\n },\n {\n \"code\": \"048-006-002-000-000-000-000\",\n \"key\": \"local_other_hotline\",\n \"title\": \"Local/other hotline\",\n \"selectable\": true,\n \"parentCode\": \"048-006-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Local/regional hotline or non-national hotline.\",\n \"canonicalCode\": \"02-02-01-02\",\n \"enumConstant\": \"ORGANIZATION_CALLCENTERS_HOTLINE_LOCAL\"\n },\n {\n \"code\": \"048-006-003-000-000-000-000\",\n \"key\": \"hotline\",\n \"title\": \"Hotline\",\n \"selectable\": true,\n \"parentCode\": \"048-006-000-000-000-000-000\",\n \"childCodes\": [\n \"048-006-001-000-000-000-000\",\n \"048-006-002-000-000-000-000\"\n ],\n \"definition\": \"Crisis hotline or call center that connected the client to services.\",\n \"canonicalCode\": \"02-02-01-00\",\n \"enumConstant\": \"ORGANIZATION_CALLCENTERS_HOTLINE\"\n },\n {\n \"code\": \"048-007-000-000-000-000-000\",\n \"key\": \"justice_protective_systems\",\n \"title\": \"Justice & Protective Systems\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-007-001-000-000-000-000\",\n \"048-007-002-000-000-000-000\",\n \"048-007-003-000-000-000-000\",\n \"048-007-004-000-000-000-000\",\n \"048-007-005-000-000-000-000\",\n \"048-007-006-000-000-000-000\"\n ],\n \"definition\": null,\n \"canonicalCode\": \"02-03-00-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE\"\n },\n {\n \"code\": \"048-007-001-000-000-000-000\",\n \"key\": \"child_welfare_cps\",\n \"title\": \"Child Welfare / CPS\",\n \"selectable\": true,\n \"parentCode\": \"048-007-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Government child protection agency responsible for investigating child abuse/neglect and ensuring child safety.\",\n \"canonicalCode\": \"02-03-01-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_CHILDWELFARE\"\n },\n {\n \"code\": \"048-007-002-000-000-000-000\",\n \"key\": \"juvenile_justice\",\n \"title\": \"Juvenile Justice\",\n \"selectable\": true,\n \"parentCode\": \"048-007-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Juvenile probation/detention/court-related juvenile justice system initiated the referral.\",\n \"canonicalCode\": \"02-03-02-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_JUVENILE\"\n },\n {\n \"code\": \"048-007-003-000-000-000-000\",\n \"key\": \"law_enforcement\",\n \"title\": \"Law enforcement / Police\",\n \"selectable\": true,\n \"parentCode\": \"048-007-000-000-000-000-000\",\n \"childCodes\": [\n \"048-007-003-001-000-000-000\",\n \"048-007-003-002-000-000-000\",\n \"048-007-003-003-000-000-000\",\n \"048-007-003-004-000-000-000\",\n \"048-007-003-005-000-000-000\"\n ],\n \"definition\": \"Law enforcement agency initiated the referral (local/state/federal).\",\n \"canonicalCode\": \"02-03-03-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_LAWENFORCEMENT\"\n },\n {\n \"code\": \"048-007-003-001-000-000-000\",\n \"key\": \"local_law_enforcement\",\n \"title\": \"Local law enforcement\",\n \"selectable\": true,\n \"parentCode\": \"048-007-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"City/county police or sheriff.\",\n \"canonicalCode\": \"02-03-03-01\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_LAWENFORCEMENT_LOCAL\"\n },\n {\n \"code\": \"048-007-003-002-000-000-000\",\n \"key\": \"state_law_enforcement\",\n \"title\": \"State law enforcement\",\n \"selectable\": true,\n \"parentCode\": \"048-007-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"State-level law enforcement agency (e.g., state police/highway patrol/state bureau of investigation) acting in an official capacity.\",\n \"canonicalCode\": \"02-03-03-02\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_LAWENFORCEMENT_STATE\"\n },\n {\n \"code\": \"048-007-003-003-000-000-000\",\n \"key\": \"federal_law_enforcement\",\n \"title\": \"Federal law enforcement\",\n \"selectable\": true,\n \"parentCode\": \"048-007-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Federal law enforcement agency (e.g., FBI, DHS/ICE).\",\n \"canonicalCode\": \"02-03-03-03\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_LAWENFORCEMENT_FEDERAL\"\n },\n {\n \"code\": \"048-007-003-004-000-000-000\",\n \"key\": \"tribal_law_enforcement\",\n \"title\": \"Tribal law enforcement\",\n \"selectable\": true,\n \"parentCode\": \"048-007-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Tribal police.\",\n \"canonicalCode\": \"02-03-03-04\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_LAWENFORCEMENT_TRIBAL\"\n },\n {\n \"code\": \"048-007-003-005-000-000-000\",\n \"key\": \"other_law_enforcement\",\n \"title\": \"Other/ unknown LE\",\n \"selectable\": true,\n \"parentCode\": \"048-007-003-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Other law enforcement entity, or law enforcement type is unknown.\",\n \"canonicalCode\": \"02-03-03-05\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_LAWENFORCEMENT_OTHER\"\n },\n {\n \"code\": \"048-007-004-000-000-000-000\",\n \"key\": \"courts_prosecution\",\n \"title\": \"Courts or prosecution\",\n \"selectable\": true,\n \"parentCode\": \"048-007-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Court or prosecution entity (not law enforcement).\",\n \"canonicalCode\": \"02-03-04-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_COURTS\"\n },\n {\n \"code\": \"048-007-005-000-000-000-000\",\n \"key\": \"correction_probation\",\n \"title\": \"Correction / probation\",\n \"selectable\": true,\n \"parentCode\": \"048-007-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Corrections, probation, parole, or community supervision entity (not law enforcement).\",\n \"canonicalCode\": \"02-03-05-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_CORRECTIONS\"\n },\n {\n \"code\": \"048-007-006-000-000-000-000\",\n \"key\": \"adult_protective_services\",\n \"title\": \"Adult Protective Services (APS)\",\n \"selectable\": true,\n \"parentCode\": \"048-007-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Government adult protection agency responsible for investigating abuse, neglect, self-neglect, or exploitation of vulnerable or older adults and ensuring their safety. Adult analog of Child Welfare / CPS.\",\n \"canonicalCode\": \"02-03-06-00\",\n \"enumConstant\": \"ORGANIZATION_JUSTICE_ADULTPROTECTIVE\"\n },\n {\n \"code\": \"048-008-000-000-000-000-000\",\n \"key\": \"health_behavioral_health\",\n \"title\": \"Health / behavioral health\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-008-001-000-000-000-000\",\n \"048-008-002-000-000-000-000\"\n ],\n \"definition\": \"Hospitals and healthcare providers (including mental health inpatient facilities).\",\n \"canonicalCode\": \"02-04-00-00\",\n \"enumConstant\": \"ORGANIZATION_HEALTH\"\n },\n {\n \"code\": \"048-008-001-000-000-000-000\",\n \"key\": \"inpatient_psychiatric_facility\",\n \"title\": \"Inpatient psychiatric facility\",\n \"selectable\": true,\n \"parentCode\": \"048-008-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Inpatient psychiatric hospital or psychiatric facility.\",\n \"canonicalCode\": \"02-04-01-00\",\n \"enumConstant\": \"ORGANIZATION_HEALTH_PSYCHIATRIC\"\n },\n {\n \"code\": \"048-008-002-000-000-000-000\",\n \"key\": \"healthcare_provider\",\n \"title\": \"Healthcare provider (non-inpatient psychiatric)\",\n \"selectable\": true,\n \"parentCode\": \"048-008-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Any non-inpatient healthcare provider (clinic, hospital, outpatient provider, behavioral health clinic, SANE program, substance abuse clinic, etc.).\",\n \"canonicalCode\": \"02-04-02-00\",\n \"enumConstant\": \"ORGANIZATION_HEALTH_HEALTHCARE\"\n },\n {\n \"code\": \"048-009-000-000-000-000-000\",\n \"key\": \"education\",\n \"title\": \"Education\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-009-001-000-000-000-000\"\n ],\n \"definition\": \"Parent category for education-related institutions.\",\n \"canonicalCode\": \"02-05-00-00\",\n \"enumConstant\": \"ORGANIZATION_EDUCATION\"\n },\n {\n \"code\": \"048-009-001-000-000-000-000\",\n \"key\": \"school_academic_institution\",\n \"title\": \"School / academic institution\",\n \"selectable\": true,\n \"parentCode\": \"048-009-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"School system or educational institution.\",\n \"canonicalCode\": \"02-05-01-00\",\n \"enumConstant\": \"ORGANIZATION_EDUCATION_SCHOOL\"\n },\n {\n \"code\": \"048-010-000-000-000-000-000\",\n \"key\": \"victim_community_service_providers\",\n \"title\": \"Victim + Community service providers\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-010-001-000-000-000-000\",\n \"048-010-002-000-000-000-000\",\n \"048-010-003-000-000-000-000\",\n \"048-010-004-000-000-000-000\"\n ],\n \"definition\": \"Parent category for victim service providers and community-based service providers.\",\n \"canonicalCode\": \"02-06-00-00\",\n \"enumConstant\": \"ORGANIZATION_COMMUNITY\"\n },\n {\n \"code\": \"048-010-001-000-000-000-000\",\n \"key\": \"child_advocacy_center\",\n \"title\": \"Child Advocacy Center (CAC)\",\n \"selectable\": true,\n \"parentCode\": \"048-010-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"A child-centered multidisciplinary center coordinating investigation and services (forensic interview, coordination, referrals, sometimes medical or therapy) for child victims.\",\n \"canonicalCode\": \"02-06-01-00\",\n \"enumConstant\": \"ORGANIZATION_COMMUNITY_CHILDADVOCACYCENTER\"\n },\n {\n \"code\": \"048-010-002-000-000-000-000\",\n \"key\": \"victim_service_provider\",\n \"title\": \"Victim service provider / advocacy program\",\n \"selectable\": true,\n \"parentCode\": \"048-010-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Organization whose primary mission is to provide services to victims/survivors of crime (VOCA-aligned breadth: rape crisis centers, DV/dating-violence/stalking programs, anti-trafficking programs, child victim centers, homicide-survivor organizations, and similar). Whether the organization is specifically a DV/SA victim service provider — the fact HMIS 2.01 needs (Comparable Database) — is a separate per-organization attribute, self-attested by the organization at onboarding (Platform survey / Agency Hub “My agency info”), not part of this category.\",\n \"canonicalCode\": \"02-06-02-00\",\n \"enumConstant\": \"ORGANIZATION_COMMUNITY_VICTIMSERVICEPROVIDER\"\n },\n {\n \"code\": \"048-010-003-000-000-000-000\",\n \"key\": \"community_based_service_provider\",\n \"title\": \"Community-based service provider (general social services)\",\n \"selectable\": true,\n \"parentCode\": \"048-010-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"The residual community-based provider (“other community-based service provider”): a non-VSP offering practical support services, navigation, or stabilization resources that is not primarily a VSP, a legal services provider, a housing/shelter project, a government justice agency, a healthcare provider, a school, a hotline, or a public benefits office. (Ex: youth drop-in center; food pantry; reentry program.)\",\n \"canonicalCode\": \"02-06-03-00\",\n \"enumConstant\": \"ORGANIZATION_COMMUNITY_COMMUNITYSERVICEPROVIDER\"\n },\n {\n \"code\": \"048-010-004-000-000-000-000\",\n \"key\": \"legal_services_provider\",\n \"title\": \"Legal services provider\",\n \"selectable\": true,\n \"parentCode\": \"048-010-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Civil legal aid organization, immigration attorneys, victim-rights law clinic, or similar provider of legal help to the client. Distinct from Courts or prosecution (the justice-system entity itself): this is getting a lawyer's help, not being referred into proceedings.\",\n \"canonicalCode\": \"02-06-04-00\",\n \"enumConstant\": \"ORGANIZATION_COMMUNITY_LEGALSERVICES\"\n },\n {\n \"code\": \"048-011-000-000-000-000-000\",\n \"key\": \"coordination_governance\",\n \"title\": \"Coordination & Governance\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-011-001-000-000-000-000\",\n \"048-011-002-000-000-000-000\"\n ],\n \"definition\": \"Parent category for coordination and governance bodies (e.g., MDTs, coalitions).\",\n \"canonicalCode\": \"02-07-00-00\",\n \"enumConstant\": \"ORGANIZATION_GOVERNANCE\"\n },\n {\n \"code\": \"048-011-001-000-000-000-000\",\n \"key\": \"mdt\",\n \"title\": \"Multidisciplinary team (MDT)\",\n \"selectable\": true,\n \"parentCode\": \"048-011-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"A case-level team: professionals from multiple agencies (law enforcement, child welfare, medical, advocacy) who review and coordinate individual cases together; referrals arise out of case review. (E.g., a county trafficking MDT or a CAC-based team.)\",\n \"canonicalCode\": \"02-07-01-00\",\n \"enumConstant\": \"ORGANIZATION_GOVERNANCE_MDT\"\n },\n {\n \"code\": \"048-011-002-000-000-000-000\",\n \"key\": \"coalition\",\n \"title\": \"Coalition (state/regional coalition)\",\n \"selectable\": true,\n \"parentCode\": \"048-011-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"A state or regional membership body of organizations coordinating at the system level — training, standards, policy, funding — not individual cases; referrals from a coalition are typically warm handoffs to a member organization.\",\n \"canonicalCode\": \"02-07-02-00\",\n \"enumConstant\": \"ORGANIZATION_GOVERNANCE_COALITION\"\n },\n {\n \"code\": \"048-012-000-000-000-000-000\",\n \"key\": \"internal\",\n \"title\": \"Internal\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-012-001-000-000-000-000\"\n ],\n \"definition\": \"Parent category for internal referrals within the same umbrella agency.\",\n \"canonicalCode\": \"02-08-00-00\",\n \"enumConstant\": \"ORGANIZATION_INTERNAL\"\n },\n {\n \"code\": \"048-012-001-000-000-000-000\",\n \"key\": \"own_agency_internal\",\n \"title\": \"Own agency / internal referral\",\n \"selectable\": true,\n \"parentCode\": \"048-012-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Client was referred from another program or unit within the same umbrella agency.\",\n \"canonicalCode\": \"02-08-01-00\",\n \"enumConstant\": \"ORGANIZATION_INTERNAL_OWNAGENCY\"\n },\n {\n \"code\": \"048-013-000-000-000-000-000\",\n \"key\": \"other_entity\",\n \"title\": \"Other\",\n \"selectable\": false,\n \"parentCode\": null,\n \"childCodes\": [\n \"048-013-001-000-000-000-000\",\n \"048-013-002-000-000-000-000\",\n \"048-013-003-000-000-000-000\"\n ],\n \"definition\": \"Parent category for other organizations not captured by the primary sectors.\",\n \"canonicalCode\": \"02-09-00-00\",\n \"enumConstant\": \"ORGANIZATION_OTHER\"\n },\n {\n \"code\": \"048-013-001-000-000-000-000\",\n \"key\": \"employer\",\n \"title\": \"Employer\",\n \"selectable\": true,\n \"parentCode\": \"048-013-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Employer, HR, or employee assistance program initiated the referral.\",\n \"canonicalCode\": \"02-09-01-00\",\n \"enumConstant\": \"ORGANIZATION_OTHER_EMPLOYER\"\n },\n {\n \"code\": \"048-013-002-000-000-000-000\",\n \"key\": \"benefits_public_assistance_office\",\n \"title\": \"Benefits/public assistance office\",\n \"selectable\": true,\n \"parentCode\": \"048-013-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Government office administering public benefits or eligibility and enrollment (e.g., SNAP, TANF, Medicaid, SSA).\",\n \"canonicalCode\": \"02-09-02-00\",\n \"enumConstant\": \"ORGANIZATION_OTHER_PUBLICASSISTANCE\"\n },\n {\n \"code\": \"048-013-003-000-000-000-000\",\n \"key\": \"other_organization\",\n \"title\": \"Other Organization\",\n \"selectable\": true,\n \"parentCode\": \"048-013-000-000-000-000-000\",\n \"childCodes\": [],\n \"definition\": \"Other organization not otherwise captured by the listed categories.\",\n \"canonicalCode\": \"02-09-03-00\",\n \"enumConstant\": \"ORGANIZATION_OTHER_UNSPECIFIED\"\n }\n ]\n}\n","/**\n * @htilabs/platform-common-models — Organization type (CVC-48, organization half)\n *\n * THE ONE PLACE an agency's / organization's type is defined and read.\n *\n * ## Ruling of record (Crysta, 2026-10-05 — platform-common #187)\n *\n * Agency type = `core-referral_entity_category` (CVC-48). It is set ONCE on\n * the Org in the Admin Hub (\"Organization Type\", `direct`); the Agency (an\n * Org's participation on an Account) carries it from the Org; every reader\n * in every app joins on the KEY. No reader guesses the type from free text.\n *\n * Before this module, \"agency type\" existed four ways across the platform —\n * free text on Thread's `Agency.type`, a positional number on\n * `Organization.type`, the correct CVC-48 key that nothing read, and a\n * free-text recogniser (Thread's `FREE_TEXT_TYPE_MATCHERS`) that the ROI gate,\n * the mandatory-report authority set and the default session role all sat on\n * top of. PAVE kept its own `VSP_TYPE_IDS` in a third spelling. This module\n * replaces all of those with ONE vocabulary (the SOT keys) and ONE set of\n * ruling-backed classifiers over it, so Thread and PAVE answer the same\n * question the same way.\n *\n * ## IC-58 is the concept; CVC-48 is its only codeset\n *\n * IC-58 (Information Concept \"Referral Entity Category\") says WHAT the thing\n * is; CVC-48 says WHICH VALUES are allowed. The `IC_58_*` constants in\n * `./ic.ts` (`IC_58_REFERRAL_ENTITY`, `IC_58_LABELS`, `IC_58_ORG_TYPE_GROUPS`,\n * `IC_58_EXTERNAL_TIERED`) are NOT a vocabulary of their own: they are CVC-48's\n * own hierarchy written as positional numbers (0–31) for Thread's\n * `Organization.type` and `CaseRecord.referralEntity`. They are deprecated for\n * org-type use in favour of this module and stay exported only so the\n * numbers already stored can be read. {@link LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY}\n * is the one-way bridge (number → CVC-48 key), row for row by label;\n * {@link resolveOrgTypeKeyFromLegacyNumeric} applies it. (Canon's 2025 PAVE\n * pick-list, CVC-86, is a different legacy list — deprecated 2026-09-28 and\n * kept in the records repo as its own crosswalk; it is not in this package.)\n *\n * ## What is and is not derived from the type\n *\n * - DERIVED (this module): sector membership (victim-serving / law\n * enforcement / legal / healthcare / mandated-report authority), the\n * default CVC-69 session role of a person acting FROM an agency of this\n * type, labels, and spelling resolution (key ↔ Sean-spec enum constant ↔\n * canon dotted code ↔ positional code ↔ legacy number).\n * - NOT derived — captured on the org record, never inferred: `vsp` (the\n * \"is a DV/SA victim service provider\" fact HMIS 2.01 needs — captured in\n * the Admin Hub, UDD Org Data Object ruling 2026-10-05; CVC-48 ruling\n * 2026-08-20 on 02-06-02-00), `vsp_private_nonprofit`, `apps_used`, and\n * the as-built `requires_roi` (informational, GDR § 5.17 clause 2 — not\n * one of the shared organization-type fields). The type only PROPOSES\n * `vsp` ({@link orgTypeDefaultVsp} — the Admin Hub's pre-fill; set when\n * HTI Labs affirms or changes it there, Crysta 2026-10-08); a stored\n * boolean always wins. See `schemas/agency.ts`. (ORG-TYPE-REVIEW-ROUND-2026-10-08)\n *\n * ## Vocabulary\n *\n * CVC-48 is a referral-entity vocabulary whose organization half (canon codes\n * `02-XX-YY-ZZ`) doubles as the org-type typology. {@link ORG_TYPE_KEYS} is\n * that half: Level 1B sector headings (not selectable — a child is required\n * everywhere, including agency onboarding; ruled 2026-08-20) plus Level 2 /\n * Level 3 leaves. The Individual branch (Level 1A) and the missingness leaves\n * are NOT org types; {@link AGENCY_TYPE_KEYS} additionally admits `unknown`\n * as the ONE pre-backfill placeholder a stored agency may carry — the Admin\n * Hub never offers it.\n *\n * The SOT JSON (~28 KB) is imported here so `./constants` stays\n * mongoose-free for edge consumers; the cost is that JSON in the constants\n * bundle. `enumConstant` is a generator column for spelling resolution only —\n * it is not in the seeder's hashable fields and is never written to\n * `cvc_entities`.\n */\n\nimport referralEntityCategorySot from \"../cvcs/referralEntityCategory.v1.2.0.json\" with { type: \"json\" };\nimport type {\n IncidentParticipationRoleKey,\n ReferralEntityCategoryKey,\n ReferralEntityCategoryKeys,\n} from \"../generated/cvc-enums.js\";\n\n// ─── SOT entry shape (the v1.1.0 generator's per-entry columns) ─────────────\n\ninterface OrgTypeSotEntry {\n code: string;\n key: string;\n title: string;\n selectable: boolean;\n parentCode: string | null;\n childCodes: string[];\n definition: string | null;\n /** Canon's 4-segment code (`02-03-01-00`); absent on the house missingness root. */\n canonicalCode?: string;\n /** Canon's Sean-spec JSON constant (`ORGANIZATION_JUSTICE_CHILDWELFARE`). */\n enumConstant?: string;\n}\n\nconst ENTRIES =\n referralEntityCategorySot.entries as ReadonlyArray<OrgTypeSotEntry>;\nconst BY_KEY = new Map(ENTRIES.map((e) => [e.key, e]));\nconst BY_CODE = new Map(ENTRIES.map((e) => [e.code, e]));\nconst BY_CANON = new Map(\n ENTRIES.filter((e) => e.canonicalCode).map((e) => [\n e.canonicalCode as string,\n e,\n ]),\n);\nconst BY_ENUM_CONSTANT = new Map(\n ENTRIES.filter((e) => e.enumConstant).map((e) => [\n e.enumConstant as string,\n e,\n ]),\n);\n\nconst isOrgHalf = (e: OrgTypeSotEntry): boolean =>\n (e.canonicalCode ?? \"\").startsWith(\"02-\");\n\n// A canon heading is the non-selectable row of the organization half; canon\n// codes them `02-XX-00-00` (codified 2026-08-20: Level 1B is never selectable).\nconst isHeading = (e: OrgTypeSotEntry): boolean =>\n isOrgHalf(e) &&\n !e.selectable &&\n /^02-\\d\\d-00-00$/.test(e.canonicalCode ?? \"\");\n\n// ─── Key sets ───────────────────────────────────────────────────────────────\n//\n// The tuples below are HAND-PINNED literals rather than `ENTRIES.filter(...)`\n// so that the exported TYPES narrow to exactly these keys (a JSON-derived array\n// types as the whole 46-key CVC-48 union, which let `{ type: \"anonymous\" }`\n// compile — pre-review finding D2). The contract test derives the same sets\n// from the SOT and asserts each tuple equals them, so a re-mirror that adds or\n// retires a leaf fails CI here instead of drifting silently.\n\n/** The Level 1B sector headings (never stored as a type; aggregation only). */\nexport const ORG_TYPE_HEADING_KEYS = Object.freeze([\n \"housing_shelter_continuum\",\n \"hotlines\",\n \"justice_protective_systems\",\n \"health_behavioral_health\",\n \"education\",\n \"victim_community_service_providers\",\n \"coordination_governance\",\n \"internal\",\n \"other_entity\",\n] as const satisfies readonly ReferralEntityCategoryKey[]);\nexport type OrgTypeHeadingKey = (typeof ORG_TYPE_HEADING_KEYS)[number];\n\n/**\n * The org-type keys an Admin Hub picker offers: every CVC-48 organization-half\n * leaf the codebook marks `Selectable` (Level 2 Required + Optional, Level 3\n * Optional), minus the one leaf no admin may pick\n * ({@link ORG_TYPE_NONPICKABLE_LEAF_KEYS}). `school_academic_institution` IS\n * a kind of organization (Level 2 Required under Education) and is offered.\n * `hotline` (02-02-01-00, canon's Level-2 parent of the two hotline children)\n * is carried since 0.18.0 at 048-006-003 — an organization that is a hotline\n * without being national / local has its key.\n */\nexport const ORG_TYPE_SELECTABLE_KEYS = Object.freeze([\n \"outreach_project\",\n \"temporary_shelter\",\n \"residential_project\",\n \"national_hotline\",\n \"local_other_hotline\",\n \"hotline\",\n \"child_welfare_cps\",\n \"juvenile_justice\",\n \"law_enforcement\",\n \"local_law_enforcement\",\n \"state_law_enforcement\",\n \"federal_law_enforcement\",\n \"tribal_law_enforcement\",\n \"other_law_enforcement\",\n \"courts_prosecution\",\n \"correction_probation\",\n \"adult_protective_services\",\n \"inpatient_psychiatric_facility\",\n \"healthcare_provider\",\n \"school_academic_institution\",\n \"child_advocacy_center\",\n \"victim_service_provider\",\n \"community_based_service_provider\",\n \"legal_services_provider\",\n \"mdt\",\n \"coalition\",\n \"employer\",\n \"benefits_public_assistance_office\",\n \"other_organization\",\n] as const satisfies readonly ReferralEntityCategoryKey[]);\nexport type OrgTypeSelectableKey = (typeof ORG_TYPE_SELECTABLE_KEYS)[number];\n\n/**\n * Organization-half leaves the codebook marks Selectable that an Admin Hub\n * picker must NOT offer, yet a stored row may carry: `own_agency_internal`\n * (\"Own agency / internal referral\", 02-08-01-00). As a REFERRAL value the\n * codebook resolves its meaning THROUGH the receiving agency's type (\"HMIS\n * rollup derived from the receiving agency's Agency Type field — IC-58 § III\n * Edge-Case Handling\"), so no admin picks it as a kind of organization — the\n * prototype's canonical CVC-48 picker keeps it in its non-pickable annex.\n * But the platform's OWN organization carries it as built (registry row\n * `internal_hti` / HTI Labs, `type: ORGANIZATION_INTERNAL_OWNAGENCY`), and\n * the CVC-69 ruling table's \"the platform's own agency → VSP staff\" row keys\n * on exactly that stored value. So: storable ({@link AGENCY_TYPE_KEYS}),\n * resolvable, never offered ({@link ORG_TYPE_SELECTABLE_KEYS}).\n */\nexport const ORG_TYPE_NONPICKABLE_LEAF_KEYS = Object.freeze([\n \"own_agency_internal\",\n] as const satisfies readonly ReferralEntityCategoryKey[]);\n\n/** Every CVC-48 key, organization half only (headings + leaves). */\nexport const ORG_TYPE_KEYS = Object.freeze([\n ...ORG_TYPE_HEADING_KEYS,\n ...ORG_TYPE_SELECTABLE_KEYS,\n ...ORG_TYPE_NONPICKABLE_LEAF_KEYS,\n] as const);\n/** A heading OR a leaf. For \"what may be stored\" see {@link AgencyTypeKey}. */\nexport type OrgTypeKey = (typeof ORG_TYPE_KEYS)[number];\n\n/**\n * Valid stored values for `Organization.type` (home) / `Agency.type`\n * (mirror): every selectable org-type leaf, the non-pickable leaf the\n * platform's own organization carries ({@link ORG_TYPE_NONPICKABLE_LEAF_KEYS}),\n * plus `unknown` — the pre-backfill placeholder an un-typed row carries until\n * HTI Labs confirms its type (never offered by the Admin Hub; readers treat\n * it as \"no sector\"). A heading is NOT a valid stored value.\n */\nexport const AGENCY_TYPE_KEYS = Object.freeze([\n ...ORG_TYPE_SELECTABLE_KEYS,\n ...ORG_TYPE_NONPICKABLE_LEAF_KEYS,\n \"unknown\",\n] as const satisfies readonly ReferralEntityCategoryKey[]);\nexport type AgencyTypeKey = (typeof AGENCY_TYPE_KEYS)[number];\n\nconst ORG_TYPE_KEY_SET: ReadonlySet<string> = new Set(ORG_TYPE_KEYS);\nconst AGENCY_TYPE_KEY_SET: ReadonlySet<string> = new Set(AGENCY_TYPE_KEYS);\n\nexport function isOrgTypeKey(value: unknown): value is OrgTypeKey {\n return typeof value === \"string\" && ORG_TYPE_KEY_SET.has(value);\n}\n\nexport function isAgencyTypeKey(value: unknown): value is AgencyTypeKey {\n return typeof value === \"string\" && AGENCY_TYPE_KEY_SET.has(value);\n}\n\n// ─── Spelling resolution ────────────────────────────────────────────────────\n\n/**\n * The one lookup both resolvers share: the SOT key (case-insensitive), the\n * Sean-spec enum constant (case-insensitive), the canon dotted code or the\n * positional code (both exact). Never a substring match, never free text.\n */\nfunction lookup(value: unknown): OrgTypeSotEntry | null {\n if (typeof value !== \"string\") return null;\n const v = value.trim();\n if (!v) return null;\n return (\n BY_KEY.get(v.toLowerCase()) ??\n BY_ENUM_CONSTANT.get(v.toUpperCase()) ??\n BY_CANON.get(v) ??\n BY_CODE.get(v) ??\n null\n );\n}\n\n/**\n * Resolve any of the platform's STRING spellings of an org type to the ONE\n * key. Accepts the SOT key (`child_welfare_cps`), the Sean-spec enum constant\n * the org registry / `agencies.typeId` carry (`ORGANIZATION_JUSTICE_CHILDWELFARE`),\n * the canon dotted code (`02-03-01-00`) or the positional code\n * (`048-007-001-000-000-000-000`). Anything else — including every free-text\n * value the retired recognisers used to guess at, and a legacy NUMBER in any\n * form (`18`, `\"18\"`) — is `null`. The number has its own, explicit bridge:\n * {@link resolveOrgTypeKeyFromLegacyNumeric}. Case- and whitespace-insensitive;\n * never a substring match.\n */\nexport function resolveOrgTypeKey(value: unknown): OrgTypeKey | null {\n const hit = lookup(value);\n return hit && isOrgTypeKey(hit.key) ? hit.key : null;\n}\n\n/**\n * Resolve any spelling of a STORABLE agency type: a selectable org-type leaf,\n * or `unknown` (any spelling the missingness leaf has). This is the resolver\n * for reading or backfilling `Agency.type` — a heading\n * (`justice_protective_systems`, `ORGANIZATION_JUSTICE`), a v1.0.0 leaf that\n * became a heading (`education`), an individual referrer or any other\n * missingness row resolves to `null`, exactly as the Mongoose enum and the\n * Zod schemas would refuse it (pre-review finding D1: the previous version\n * returned headings typed as `AgencyTypeKey`). Use {@link resolveOrgTypeKey}\n * when a heading is an acceptable answer (aggregation, labels).\n */\nexport function resolveAgencyTypeKey(value: unknown): AgencyTypeKey | null {\n const hit = lookup(value);\n return hit && isAgencyTypeKey(hit.key) ? hit.key : null;\n}\n\n// ─── Legacy numeric bridge (Thread `Organization.type` / `CaseRecord.referralEntity`)\n\n/**\n * The positional numbers `./ic.ts` `IC_58_REFERRAL_ENTITY` assigned to CVC-48's\n * rows, → the CVC-48 key, row for row by label (`IC_58_LABELS`). One-way:\n * nothing new is ever written as a number. Three numbers name a sector HEADING\n * (17 Education, 19 \"Other External\", 26 Victim + Community) and\n * therefore resolve to an org type but NOT to a storable agency type — a row\n * Thread defaulted to 19 is an un-typed organization and reads as such\n * until the backfill gives it a leaf. Numbers 2–5 are the Individual branch:\n * referral sources, never org types.\n *\n * **Backfill-only. Not a runtime reader, and never an ROI input.** The ruled\n * shape (Org Data Object, 2026-10-02 / 2026-10-05; platform-common #187) is\n * that the type is set ONCE, as a key, in the Admin Hub, and every reader\n * joins on the key — \"no reader guesses from words\", and no reader translates\n * numbers either. This table exists so the backfill review can PROPOSE a key\n * for a numeric `Organization.type`; a consumer that still translates numbers\n * at read time (pave's `IC58_TO_REFERRAL_ENTITY_CATEGORY_KEY`, Thread's\n * `Organization.type` itself) retires that path when its rows are backfilled\n * (#187 follow-ups). Whether a share needs a release is decided by the org's\n * attested `vsp` flag, captured in the Admin Hub and never derived from the\n * type (ruling 2026-10-05) — so which key `19` proposes cannot change an ROI\n * answer anywhere. `19` → the `other_entity` HEADING is deliberate: in Thread\n * `19` was the write for \"referring organization Unknown / Anonymous\"\n * (`UNIDENTIFIED_EXTERNAL_ORG_TYPE`) and the default for every organization\n * created before leaf-only pickers, so it proposes nothing and the review\n * picks the leaf — `other_organization` only when a human says so.\n */\nexport const LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY = Object.freeze({\n 0: \"unknown\",\n 1: \"own_agency_internal\",\n 2: \"self_referred\",\n 3: \"family_guardian_friend\",\n 4: \"peer\",\n 5: \"other_individual\",\n 10: \"housing_shelter_continuum\",\n 11: \"hotline\",\n 12: \"justice_protective_systems\",\n 13: \"outreach_project\",\n 14: \"temporary_shelter\",\n 15: \"residential_project\",\n 16: \"health_behavioral_health\",\n 17: \"education\",\n 18: \"law_enforcement\",\n 19: \"other_entity\",\n 20: \"child_welfare_cps\",\n 21: \"juvenile_justice\",\n 22: \"courts_prosecution\",\n 23: \"correction_probation\",\n 24: \"inpatient_psychiatric_facility\",\n 25: \"healthcare_provider\",\n 26: \"victim_community_service_providers\",\n 27: \"child_advocacy_center\",\n 28: \"victim_service_provider\",\n 29: \"community_based_service_provider\",\n 30: \"employer\",\n 31: \"benefits_public_assistance_office\",\n} as const satisfies Readonly<Record<number, ReferralEntityCategoryKey>>);\nexport type LegacyNumericReferralEntity =\n keyof typeof LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY;\n\n/**\n * The CVC-48 key a legacy number stands for (any row — individuals included),\n * or `null` for a number the list never had. Accepts a number or its decimal\n * string (`18` / `\"18\"`), the two forms Thread has stored it in.\n */\nexport function resolveReferralEntityKeyFromLegacyNumeric(\n value: unknown,\n): ReferralEntityCategoryKey | null {\n const n =\n typeof value === \"number\"\n ? value\n : typeof value === \"string\" && /^\\s*\\d{1,2}\\s*$/.test(value)\n ? Number(value)\n : NaN;\n if (!Number.isInteger(n)) return null;\n const table: Readonly<Record<number, ReferralEntityCategoryKey>> =\n LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY;\n return table[n] ?? null;\n}\n\n/**\n * The ORG TYPE a legacy number stands for — a heading or a leaf — or `null`\n * for the Individual branch, `0` (unknown) and anything unlisted. For \"may it\n * be stored as an agency type\" pass the result through\n * {@link resolveAgencyTypeKey} (headings → `null`).\n */\nexport function resolveOrgTypeKeyFromLegacyNumeric(\n value: unknown,\n): OrgTypeKey | null {\n const k = resolveReferralEntityKeyFromLegacyNumeric(value);\n return k && isOrgTypeKey(k) ? k : null;\n}\n\n// ─── Accessors (any string; `null` on a miss) ───────────────────────────────\n\n/** The Sean-spec enum constant for a key (the org registry's spelling). */\nexport function orgTypeEnumConstant(key: string): string | null {\n return BY_KEY.get(key)?.enumConstant ?? null;\n}\n\n/** The canon dotted code for a key (`02-03-01-00`). */\nexport function orgTypeCanonicalCode(key: string): string | null {\n return BY_KEY.get(key)?.canonicalCode ?? null;\n}\n\n/** Canon's picker label for a key (`title`); `null` for a key the SOT lacks. */\nexport function orgTypeLabel(key: string): string | null {\n return BY_KEY.get(key)?.title ?? null;\n}\n\n// ─── Hierarchy ──────────────────────────────────────────────────────────────\n\n/**\n * The key and every ancestor, leaf first (`local_law_enforcement` →\n * `law_enforcement` → `justice_protective_systems`). Empty for an unknown key.\n * Guarded against a cyclic or self-referencing `parentCode` in the SOT: the\n * walk stops at the first repeat instead of hanging.\n */\nexport function orgTypeAncestry(key: string): ReferralEntityCategoryKey[] {\n const out: ReferralEntityCategoryKey[] = [];\n const seen = new Set<string>();\n let cursor = BY_KEY.get(key);\n while (cursor && !seen.has(cursor.code)) {\n seen.add(cursor.code);\n out.push(cursor.key as ReferralEntityCategoryKey);\n cursor = cursor.parentCode ? BY_CODE.get(cursor.parentCode) : undefined;\n }\n return out;\n}\n\n/**\n * Key → parent key, organization half, from the SOT's `parentCode` field —\n * the companion map a consumer uses instead of code-prefix arithmetic\n * (review nit on `fce762f`). The hierarchy is the `parentCode` FIELD, never\n * the positional code's prefix: `national_hotline` / `local_other_hotline`\n * keep their v1.0.0 codes while their parent is now the `hotline` LEAF\n * (048-006-003, carried since 0.18.0), so a child code does not lexically\n * extend its parent's. Headings map to `null`. (`hotline` is the storable\n * leaf — an organization that is a hotline; `hotlines` is the\n * non-storable heading above it. Mind the plural.)\n */\nexport const ORG_TYPE_PARENT_KEY: Readonly<\n Record<OrgTypeKey, ReferralEntityCategoryKey | null>\n> = Object.freeze(\n Object.fromEntries(\n ENTRIES.filter(isOrgHalf).map((e) => [\n e.key,\n e.parentCode\n ? ((BY_CODE.get(e.parentCode)?.key as ReferralEntityCategoryKey) ??\n null)\n : null,\n ]),\n ) as Record<OrgTypeKey, ReferralEntityCategoryKey | null>,\n);\n\n/**\n * The Level 1B sector heading a key sits under (itself if it is one); `null`\n * for a key whose chain does not end in a heading — `unknown`, the\n * individual referrers, the missingness root (pre-review finding D6: an\n * aggregator keyed on this must skip un-typed agencies, not bucket them under\n * `missingness_root`).\n */\nexport function orgTypeSector(key: string): OrgTypeHeadingKey | null {\n const chain = orgTypeAncestry(key);\n if (!chain.length) return null;\n const top = chain[chain.length - 1];\n const entry = BY_KEY.get(top);\n return entry && isHeading(entry) ? (top as OrgTypeHeadingKey) : null;\n}\n\n// ─── Sector classifiers (the ruling table) ──────────────────────────────────\n//\n// The rows of the CVC-69 ruling table (OWNER-ROLE-FROM-AGENCY, prototype #703,\n// 2026-10-05) and the canon mandated-report predicate. The sets are\n// hand-pinned (so their TYPES narrow, like the key sets above); the contract\n// test re-derives each subtree-defined set from the SOT hierarchy and fails if\n// a re-mirror adds or moves a leaf, so a new leaf under a heading is caught\n// here rather than silently left out of a classifier.\n\n/**\n * Victim-serving organization types: the two Victim + Community leaves whose\n * staff act as victim advocates — `victim_service_provider` and\n * `child_advocacy_center` (CAC ruled under Victim + Community service\n * providers 2026-08-20). `community_based_service_provider` and\n * `legal_services_provider` sit under the same heading but are NOT\n * victim-serving for this question (canon: the residual non-VSP provider; a\n * lawyer's help). `coalition` is a system-level membership body, not a\n * service provider (ruled 2026-08-20). NOTE: this is the TYPE-level default;\n * the org record's own `vsp` attestation decides the HMIS 2.01 / ROI question.\n */\nexport const VICTIM_SERVING_ORG_TYPE_KEYS = Object.freeze([\n \"victim_service_provider\",\n \"child_advocacy_center\",\n] as const satisfies readonly OrgTypeSelectableKey[]);\n\n/** Law enforcement: the `law_enforcement` leaf and its Level 3 refinements. */\nexport const LAW_ENFORCEMENT_ORG_TYPE_KEYS = Object.freeze([\n \"law_enforcement\",\n \"local_law_enforcement\",\n \"state_law_enforcement\",\n \"federal_law_enforcement\",\n \"tribal_law_enforcement\",\n \"other_law_enforcement\",\n] as const satisfies readonly OrgTypeSelectableKey[]);\n\n/** Legal: courts / prosecution, and legal services providers (a lawyer's help). */\nexport const LEGAL_ORG_TYPE_KEYS = Object.freeze([\n \"courts_prosecution\",\n \"legal_services_provider\",\n] as const satisfies readonly OrgTypeSelectableKey[]);\n\n/**\n * Healthcare incl. behavioral health: the `health_behavioral_health` subtree\n * (the heading is listed so a consumer aggregating by sector can use it; it\n * is never a stored type).\n */\nexport const HEALTHCARE_ORG_TYPE_KEYS = Object.freeze([\n \"health_behavioral_health\",\n \"inpatient_psychiatric_facility\",\n \"healthcare_provider\",\n] as const satisfies readonly OrgTypeKey[]);\n\n/**\n * Designated authorities for mandatory / authority reporting: the whole\n * Justice & Protective Systems subtree — child welfare, juvenile justice,\n * every law-enforcement leaf, courts / prosecution, corrections / probation,\n * adult protective services. This is canon's `/^ORGANIZATION_JUSTICE/`\n * predicate over the enum constants, expressed over keys.\n */\nexport const REPORT_AUTHORITY_ORG_TYPE_KEYS = Object.freeze([\n \"justice_protective_systems\",\n \"child_welfare_cps\",\n \"juvenile_justice\",\n \"law_enforcement\",\n \"local_law_enforcement\",\n \"state_law_enforcement\",\n \"federal_law_enforcement\",\n \"tribal_law_enforcement\",\n \"other_law_enforcement\",\n \"courts_prosecution\",\n \"correction_probation\",\n \"adult_protective_services\",\n] as const satisfies readonly OrgTypeKey[]);\n\n/**\n * Types that say nothing about a sector: the platform's own organization\n * (`own_agency_internal` as stored on the HTI Labs row; `internal`, its\n * heading) and the pre-backfill `unknown`. This set is the ruling table's\n * \"no type / unknown / the platform's own agency → VSP staff\" row.\n */\nexport const NO_SECTOR_ORG_TYPE_KEYS = Object.freeze([\n \"internal\",\n \"own_agency_internal\",\n \"unknown\",\n] as const satisfies readonly (OrgTypeKey | \"unknown\")[]);\n\nconst asSet = (keys: readonly string[]): ReadonlySet<string> => new Set(keys);\nconst VICTIM_SERVING = asSet(VICTIM_SERVING_ORG_TYPE_KEYS);\nconst LAW_ENFORCEMENT = asSet(LAW_ENFORCEMENT_ORG_TYPE_KEYS);\nconst LEGAL = asSet(LEGAL_ORG_TYPE_KEYS);\nconst HEALTHCARE = asSet(HEALTHCARE_ORG_TYPE_KEYS);\nconst REPORT_AUTHORITY = asSet(REPORT_AUTHORITY_ORG_TYPE_KEYS);\nconst NO_SECTOR = asSet(NO_SECTOR_ORG_TYPE_KEYS);\n\n/**\n * Each predicate accepts ANY spelling {@link resolveAgencyTypeKey} accepts and\n * answers `false` for everything it does not recognise — a free-text type is\n * never guessed at.\n */\nexport function isVictimServingOrgType(\n type: string | null | undefined,\n): boolean {\n const k = resolveAgencyTypeKey(type);\n return !!k && VICTIM_SERVING.has(k);\n}\nexport function isLawEnforcementOrgType(\n type: string | null | undefined,\n): boolean {\n const k = resolveAgencyTypeKey(type);\n return !!k && LAW_ENFORCEMENT.has(k);\n}\nexport function isLegalOrgType(type: string | null | undefined): boolean {\n const k = resolveAgencyTypeKey(type);\n return !!k && LEGAL.has(k);\n}\nexport function isHealthcareOrgType(type: string | null | undefined): boolean {\n const k = resolveAgencyTypeKey(type);\n return !!k && HEALTHCARE.has(k);\n}\n/** Is this type a designated mandatory / authority-report recipient? */\nexport function isReportAuthorityOrgType(\n type: string | null | undefined,\n): boolean {\n const k = resolveAgencyTypeKey(type);\n return !!k && REPORT_AUTHORITY.has(k);\n}\n\n/**\n * The type-level DEFAULT for the org record's `vsp` attestation: `true` for\n * `victim_service_provider`, `false` for every other recognised org type,\n * `null` when the type cannot answer — the type is unknown / own-agency\n * (nothing to default from), or it is a `child_advocacy_center` (ruled\n * 2026-10-05: a CAC is victim-serving for the session role and OCAT, but its\n * HMIS VSP standing is whatever the org attests — the registry attests FALSE\n * for the one on file — so a bare CAC type is NOT a default either way; a\n * reader on `null` takes the ROI gate's conservative branch, release\n * required). A stored `vsp` boolean on the org ALWAYS wins; this is only what\n * the Admin Hub pre-fills and what a reader falls back to when the org has\n * not attested.\n */\nexport function orgTypeDefaultVsp(\n type: string | null | undefined,\n): boolean | null {\n const k = resolveAgencyTypeKey(type);\n if (!k || NO_SECTOR.has(k) || k === \"child_advocacy_center\") return null;\n return k === \"victim_service_provider\";\n}\n\n// ─── Default session role (CVC-69) ──────────────────────────────────────────\n\n/**\n * The CVC-69 `incident_participation_roles` key a person acting FROM an\n * agency of this type defaults to — the ruling table on the CVC-69 page\n * (OWNER-ROLE-FROM-AGENCY, prototype #703, 2026-10-05):\n *\n * org attests `vsp: true` → Victim Service provider staff (checked FIRST)\n * victim-serving → Victim Service provider staff\n * law enforcement → Law enforcement personnel\n * courts / prosecution / legal → Legal professional\n * healthcare incl. behavioral health → Healthcare provider staff\n * any other recognised org type → Other Response Personnel\n * no type / unknown / own agency → Victim Service provider staff\n *\n * **This is a non-authoritative UI PRE-FILL, never an authorization input.**\n * It cannot say \"no\" — the last row is a ruled catch-all, and it also absorbs\n * a value that is PRESENT but unresolvable (legacy free text such as\n * `\"Law Enforcement\"`). That is the ruling, not an accident: the Personnel\n * roles card records (2026-10-05) \"unrecognized or empty types fall back to\n * Victim Service provider staff\", the conservative direction for an advocate\n * surface (Swap corrects it by hand). A consumer that needs to KNOW it is\n * looking at the guess calls {@link orgTypeDefaultSessionRoleOrNull} instead.\n * Any VAWA / ROI / VSP gate reads the org's stored `vsp` boolean, never this\n * role (a CAC defaults to `vsp_staff` while its attested `vsp` may be false).\n *\n * Keys are the canonical CVC-69 v1.1.0 spellings (platform-common #186):\n * `vsp_staff`, `law_enforcement_personnel`, `legal_professional`,\n * `healthcare_provider_staff`, `other_response_personnel`. A consumer still\n * on the 0.13.0 spellings (`service_provider_staff`, `responding_officer`,\n * `medical_provider_staff`, `other_incident_responder`) maps through its own\n * successor table until it repins; the test pins this table to\n * `IncidentParticipationRoleKeys` so a future rename lands here too.\n */\nexport function orgTypeDefaultSessionRole(\n type: string | null | undefined,\n /**\n * The org's attested HMIS VSP flag (`agencies.vsp`, {@link addAgencyOrgTypeFields}).\n * Canon checks it BEFORE the type (`HTI_SESSION_ROLE_FOR_ORG`, prototype\n * ~L217866; the CVC-69 ruling table's first row): a strict `true` answers\n * `vsp_staff` whatever the type says, because the flag is captured and the\n * type's sector is only a default. `false`, `null`, `undefined` and any\n * non-boolean fall through to the type. Thread's `resolveAgencySessionRole`\n * carries the same precedence (#670) and collapses onto this at the repin.\n */\n vsp?: unknown,\n): IncidentParticipationRoleKey {\n return orgTypeDefaultSessionRoleOrNull(type, vsp) ?? \"vsp_staff\";\n}\n\n/**\n * The same table, but `null` instead of the catch-all whenever the type does\n * not RESOLVE — absent, empty, free text, a legacy number, a heading. A\n * resolved `unknown` / own-agency type still answers `vsp_staff` (that row is\n * ruled, and the type was read, not guessed), and so does an attested\n * `vsp: true` with any type at all (the flag was read). Use this when the caller must\n * tell \"the ruling said VSP staff\" from \"we had nothing to go on\".\n */\nexport function orgTypeDefaultSessionRoleOrNull(\n type: string | null | undefined,\n /** See {@link orgTypeDefaultSessionRole}: a strict `true` is a READ answer, never a guess. */\n vsp?: unknown,\n): IncidentParticipationRoleKey | null {\n if (vsp === true) return \"vsp_staff\";\n const k = resolveAgencyTypeKey(type);\n if (!k) return null;\n if (NO_SECTOR.has(k)) return \"vsp_staff\";\n if (VICTIM_SERVING.has(k)) return \"vsp_staff\";\n if (LAW_ENFORCEMENT.has(k)) return \"law_enforcement_personnel\";\n if (LEGAL.has(k)) return \"legal_professional\";\n if (HEALTHCARE.has(k)) return \"healthcare_provider_staff\";\n return \"other_response_personnel\";\n}\n\n// Compile-time guard: the hand-named keys above exist in the SOT.\nconst _orgKeysNamed = [\n \"victim_service_provider\",\n \"child_advocacy_center\",\n \"community_based_service_provider\",\n \"legal_services_provider\",\n \"coalition\",\n \"courts_prosecution\",\n \"law_enforcement\",\n \"health_behavioral_health\",\n \"justice_protective_systems\",\n \"internal\",\n \"own_agency_internal\",\n \"unknown\",\n] as const satisfies readonly (keyof typeof ReferralEntityCategoryKeys)[];\nvoid _orgKeysNamed;\n","/**\n * @htilabs/platform-common-models — organization-type fields: Org home, Agency mirror\n *\n * Shared, additive fields for the kind of organization something is, with\n * the ONE vocabulary (`constants/org-type.ts`), and where they live.\n *\n * ## The three objects (UDD, ruled 2026-10-02; Org `vsp` ruled 2026-10-05)\n *\n * - **Org** — \"who is this, out in the world\": the platform-wide registry\n * row (platform-db `organizations`). It HOLDS the type and the two HMIS\n * victim-service-provider answers: `type`, `vsp`, `vspPrivateNonprofit`.\n * One Org per real-world organization, with or without any account. The\n * Admin Hub edits it here, once. (`requires_roi` stays on the org row AS\n * BUILT and is NOT one of these fields: the Org Data Object lists it under\n * \"as built today, and not part of this definition\" and GDR § 5.17 clause 2\n * makes it informational — the release check reads the sender's `vsp`,\n * never `requires_roi`. Review round ORG-TYPE-REVIEW-ROUND-2026-10-08, Crysta decision 1.)\n * - **Account** — \"who signed, and whose rules govern\": the tenancy\n * (`agencies` rows with `isAccount: true` today). Carries none of these\n * fields; points at its holding Org.\n * - **Agency** — \"how does this Org take part in that Account\": an Org with\n * an Account IS an Agency — one row per (Org, Account), keyed by\n * `organizationId` (→ `organizations._id`) and the account. The UDD Agency\n * carries NO type and NO flags of its own; it reads them off its Org.\n *\n * ## Why the Agency gets a copy anyway (the mirror)\n *\n * Every live gate reads `agencies.type` (`/me`, the ROI gate, the authority\n * set, the session-role default, recipient labels) and production's Org\n * link is nearly empty (6 of 124 prod agencies carry an `organizationId`,\n * #187). So the Agency row carries a **declared mirror** of the Org's four\n * fields: same definition, stamped FROM the Org — by provisioning when the\n * agency is created, by the backfill when it links the agency to its Org —\n * and never edited on the agency directly. {@link mirrorOrgTypeFields} is\n * the one way to produce the copy. The home is the Org; the mirror exists so\n * readers do not have to join until `organizationId` is populated\n * everywhere. A consumer that CAN join reads the Org through\n * {@link resolveEffectiveOrgTypeFields} / {@link resolveEffectiveOrgType}\n * (\"the Org wins once linked\"); {@link orgTypeFieldsDiffer} surfaces drift.\n *\n * **The mirror is TRANSITIONAL and has a sunset** (Crysta, 2026-10-08,\n * platform-common #187): the agency copy is dropped the day every agency row\n * carries `organizationId` (6 of 124 production rows today). The UDD Agency\n * carries no type and no flags — this copy is a production crutch, not an\n * Agency field, and nothing is ever \"aligned\" to it.\n *\n * **Re-stamp invariant** (Kirby, review of `9538e2e`): every write of these\n * fields on an Org re-stamps the copy on EVERY agency row linked to it\n * (`organizationId`), in the same operation as the Org write — the Admin Hub\n * and the backfill are the two writers, and both go Org first, then\n * `mirrorOrgTypeFields(org)` onto each linked agency. A reader that finds\n * `orgTypeFieldsDiffer(org, agency)` non-empty has found a broken writer,\n * not a legitimate state; it should read the Org and log the drift.\n *\n * ## This is a FRAGMENT, not an Org / Agency model\n *\n * No canonical Org or Agency schema exists in this package (same posture as\n * `schemas/team.ts`). `organizations` is written by PAVE 2.0 (`type` a\n * NUMBER 10–31 today — the IC-58 positional list; the Org mount replaces it\n * with the key), `agencies` by the auth service at provisioning (`au-q3p`)\n * and the platform Admin Hub, mirrored by Thread (`type: String` free text)\n * and legacy PAVE. Declaring the whole shapes here is out of scope; this\n * module declares ONLY the organization-type fields and mounts them on\n * either schema: {@link addOrgTypeFields} (home) /\n * {@link addAgencyOrgTypeFields} (mirror).\n *\n * ## Ruling of record (Crysta, 2026-10-05 — platform-common #187)\n *\n * Agency type = CVC-48 `core-referral_entity_category`, set ONCE on the Org\n * in the Admin Hub; the Agency carries it from the Org; every reader joins on\n * the key. `vsp` and `vspPrivateNonprofit` are captured on the org record in\n * the Admin Hub (Directory tab; Network add / edit forms — UDD Org Data\n * Object ruling 2026-10-05; the 2026-08-13 onboarding derivation\n * `isVspEntityType` is retired by that ruling) and never inferred from the\n * type. Refined 2026-10-08 (Crysta): the type PROPOSES the answer\n * (`orgTypeDefaultVsp` is what the Admin Hub pre-fills, and what a reader\n * falls back to while nothing is attested); the answer is SET only when HTI\n * Labs affirms or changes it in the Admin Hub. A proposal is never written\n * as an answer — not by onboarding, not by the backfill.\n *\n * ## Field names\n *\n * Canon's org registry spells these `type`, `vsp`, `vsp_private_nonprofit`\n * (snake_case CSV columns). The live platform-db writers use camelCase on\n * agencies (`isHTIAdminAgency`, `serviceLocation`, `apps`), so the second\n * boolean is carried camelCase here; `type` and `vsp` are spelled the same\n * in both.\n *\n * ## Backfill posture\n *\n * `type` is NOT `required` at the schema level yet: most production agencies\n * were provisioned with no type at all, and a required enum would make every\n * one of them fail validation on its next unrelated save. Not-required keeps\n * those rows saving; it does NOT protect a row that already carries a non-key\n * value (see the `type` field doc) — those are the backfill's first job. The\n * backfill (HTI Labs confirms each agency against the org registry; #187)\n * sets a key on every row; the minor that follows it flips `required: true`.\n * Until then a stored `unknown` is the ONE admitted placeholder, and readers\n * treat an absent / unresolvable type exactly like `unknown`\n * (`resolveAgencyTypeKey` → `null`).\n *\n * ## Order of adoption (review MG2) — BOTH collections\n *\n * Mongoose validates every loaded path on `save()`, so once a consumer mounts\n * these fields, a document carrying a NON-KEY `type` fails its next save of\n * any field. That is the intended fail-closed, and it means the data goes\n * first: (1) `agencies` — the handful of free-text rows (prod 3, dev 3) are\n * normalised to `unknown`, no HTI confirmation needed; (2) `organizations` —\n * EVERY row carries a numeric IC-58 type today (10–31, PAVE's writer), so the\n * numeric → key migration (proposed by `resolveOrgTypeKeyFromLegacyNumeric`,\n * confirmed by HTI Labs on the backfill sheet) runs BEFORE any consumer calls\n * {@link addOrgTypeFields} on `organizations`; (3) mount; (4) after the\n * backfill, `required: true` and the recognisers are deleted.\n * (ORG-TYPE-REVIEW-ROUND-2026-10-08)\n */\n\nimport { Error as MongooseError } from \"mongoose\";\nimport type { Document, InferRawDocType, Query, Schema } from \"mongoose\";\nimport {\n AGENCY_TYPE_KEYS,\n resolveAgencyTypeKey,\n type AgencyTypeKey,\n} from \"../constants/org-type.js\";\n\n// ─── The HMIS VSP two-step (Stage-0 ruling 4c) ──────────────────────────────\n\n/**\n * Step 2 (`vspPrivateNonprofit`) is asked only when step 1 (`vsp`) is `true`.\n * A record (or a write) that answers step 2 without `vsp: true` is MALFORMED\n * — never \"false by default\". Tri-state is preserved: an absent / `null`\n * step 2 always holds, whatever step 1 says (GDR § 1.2: never-captured is\n * never coerced). One predicate, enforced in three places: the Zod write\n * shapes (`validation/agency.ts`), the Mongoose mount (`pre('validate')` on\n * save and the update-op hook) and {@link mirrorOrgTypeFields}.\n */\nexport function vspTwoStepHolds(v: {\n vsp?: boolean | null;\n vspPrivateNonprofit?: boolean | null;\n}): boolean {\n return v.vspPrivateNonprofit == null || v.vsp === true;\n}\nexport const VSP_TWO_STEP_ISSUE: {\n message: string;\n path: (string | number)[];\n} = {\n message:\n \"vspPrivateNonprofit is step 2 of the HMIS VSP two-step and requires vsp: true\",\n path: [\"vspPrivateNonprofit\"],\n};\n\n/**\n * The two-step on an UPDATE payload (`updateOne` / `updateMany` /\n * `findOneAndUpdate`): an update cannot see the stored document, so the rule\n * it can enforce is \"step 2 is only ever written together with step 1\" — a\n * payload that sets `vspPrivateNonprofit` to a boolean must set `vsp: true`\n * in the same payload (top level or `$set`). Clearing step 2 (`null` /\n * `$unset`) always holds. Exported so it can be unit-tested without a\n * connection; the mount installs it on {@link AGENCY_ORG_TYPE_VALIDATED_UPDATE_OPS}.\n */\nexport function vspTwoStepHoldsOnUpdate(update: unknown): boolean {\n if (!update || typeof update !== \"object\") return true;\n const u = update as Record<string, unknown>;\n const set = { ...u, ...((u.$set as Record<string, unknown>) ?? {}) };\n return vspTwoStepHolds({\n vsp: set.vsp as boolean | null | undefined,\n vspPrivateNonprofit: set.vspPrivateNonprofit as boolean | null | undefined,\n });\n}\n\n// ─── Schema Definition ──────────────────────────────────────────────\n\n/**\n * The organization-type fields. ONE definition, mounted on the Org (home)\n * and on the Agency (mirror) — see the module doc.\n *\n * All three are OPTIONAL and default to `undefined`. A document written\n * before these fields existed hydrates and re-saves without gaining them, so\n * \"not attested\" (absent) stays distinct from \"attested false\".\n */\nexport const orgTypeSchemaDefinition = {\n /**\n * The agency's organization type: a CVC-48 key from\n * {@link AGENCY_TYPE_KEYS} (a selectable org-type leaf, or the pre-backfill\n * `unknown`). Set once in the Admin Hub; carried from the Org. Never free\n * text — a value outside the enum fails validation on `save()` and, when\n * the fragment is added with {@link addAgencyOrgTypeFields} (default\n * options), on `updateOne` / `updateMany` / `findOneAndUpdate` too.\n *\n * ORDER OF ADOPTION (review MG2, pinned in org-type-contract.test.ts):\n * Mongoose validates `init`-ed paths on `save()`, not only modified ones,\n * so once a consumer adds this fragment, an agency document that carries a\n * NON-KEY `type` (free text, \"UNKNOWN\", \"multi_service\", a number) fails\n * its next save of ANY field. A document with no `type` at all saves fine.\n * Backfill first (every stored value → a key or `unknown`), then adopt.\n */\n type: {\n type: String,\n enum: [...AGENCY_TYPE_KEYS],\n index: true,\n },\n /**\n * Is this organization a DV/SA victim service provider — the HMIS 2.01\n * (Comparable Database) fact. Captured in the Admin Hub (never inferred\n * from the type; the type only PROPOSES it — `orgTypeDefaultVsp`, the\n * Hub's pre-fill — and HTI Labs affirms or changes it there). Tri-state:\n * `true` / `false` / absent (not yet captured — a reader falls back to the\n * proposal).\n */\n vsp: {\n type: Boolean,\n },\n /**\n * Step 2 of the two-step: private non-profit VSP (VOCA/OVC PMT\n * distinction). Captured; tri-state; may only be `true`/`false` when\n * `vsp === true` ({@link vspTwoStepHolds}, enforced at the mount).\n */\n vspPrivateNonprofit: {\n type: Boolean,\n },\n};\n\n/** @deprecated Same object as {@link orgTypeSchemaDefinition}; kept for 0.14-era callers. */\nexport const agencyOrgTypeSchemaDefinition = orgTypeSchemaDefinition;\n\n/**\n * The field names, in one place (the mirror copies exactly these). The\n * `satisfies` ties the tuple to {@link OrgTypeFields} at compile time: a field\n * added to the definition without being listed here fails `tsc`, so the\n * mirror can never silently stop copying it (review nit).\n */\nexport const ORG_TYPE_FIELD_NAMES = Object.freeze([\n \"type\",\n \"vsp\",\n \"vspPrivateNonprofit\",\n] as const satisfies readonly (keyof OrgTypeFields)[]);\nexport type OrgTypeFieldName = (typeof ORG_TYPE_FIELD_NAMES)[number];\n\n// ─── Schema Helper ──────────────────────────────────────────────────\n\n/** Update operations on which the enum is enforced by {@link addAgencyOrgTypeFields}. */\nexport const AGENCY_ORG_TYPE_VALIDATED_UPDATE_OPS = Object.freeze([\n \"updateOne\",\n \"updateMany\",\n \"findOneAndUpdate\",\n] as const);\n\nexport interface AddAgencyOrgTypeFieldsOptions {\n /**\n * Turn `runValidators` on (unless the caller set it explicitly) in the\n * `pre` hook the mount installs on {@link AGENCY_ORG_TYPE_VALIDATED_UPDATE_OPS},\n * so the enum holds on the update paths the auth service and the Admin Hub\n * actually write through — Mongoose skips enum validators on update\n * operations by default. Default `true`. The hook itself is ALWAYS\n * installed: it also enforces the VSP two-step on the update payload\n * ({@link vspTwoStepHoldsOnUpdate}), which is a shape rule, not a\n * validator option, and cannot be opted out of.\n */\n validateOnUpdate?: boolean;\n}\n\n/**\n * The hook body, exported so it can be unit-tested without a connection:\n * sets `runValidators: true` on a query that has not said otherwise.\n */\nexport function applyRunValidatorsIfUnset(\n query: Pick<Query<unknown, unknown>, \"getOptions\" | \"setOptions\">,\n): void {\n if (query.getOptions().runValidators === undefined) {\n query.setOptions({ runValidators: true });\n }\n}\n\n/**\n * Mount the organization-type fields on a schema (shared body of the two\n * public mounts). Adds the `type` index declared above and, by default, the\n * update-path validation hook described on {@link AddAgencyOrgTypeFieldsOptions}.\n *\n * Mongoose `schema.add` REPLACES an existing `type` path wholesale: a\n * consumer's own `required`, `default`, `enum`, `lowercase` / `trim`, and a\n * numeric `type: Number` on that path are all dropped and the fragment's\n * definition (enum over {@link AGENCY_TYPE_KEYS}, NOT required, indexed)\n * stands. For Thread's free-text agency `type` and PAVE's numeric\n * organization `type` that is the intended migration — `required` must come\n * off until the backfill lands — but a consumer that relied on any other\n * option on `type` re-declares it after calling this. (Pre-review finding\n * D4 corrected the earlier wording, which claimed the opposite.) The fragment\n * is written with the default `typeKey`; a schema constructed with a custom\n * `typeKey` (none in the platform today) cannot take it as-is.\n */\nfunction mountOrgTypeFields<S extends Schema>(\n schema: S,\n options: AddAgencyOrgTypeFieldsOptions,\n): S {\n schema.add(orgTypeSchemaDefinition);\n // The two-step on save (review Blocker 2): a document with step 2 answered\n // and step 1 not `true` fails validation on `vspPrivateNonprofit`. Runs on\n // every save, so provisioning, the backfill and bulk writes through the\n // model all hit it; a Zod `.extend` that forgot `.refine` is caught here.\n // Registered through a narrow structural type: the generic `S extends\n // Schema` loses Mongoose's `pre(\"validate\")` overload, and the hook body\n // THROWS a ValidationError rather than calling `invalidate()` (Mongoose 9\n // does not surface `invalidate()` from a pre('validate') hook — verified\n // 2026-10-08 against 9.3.1; a thrown ValidationError rejects `validate()`\n // and therefore `save()` exactly like a path validator would).\n (\n schema as unknown as {\n pre: (\n method: \"validate\",\n fn: (this: Document) => void | Promise<void>,\n ) => unknown;\n }\n ).pre(\"validate\", function (this: Document) {\n const doc = this as unknown as {\n vsp?: boolean | null;\n vspPrivateNonprofit?: boolean | null;\n };\n if (!vspTwoStepHolds(doc)) {\n const err = new MongooseError.ValidationError();\n err.addError(\n \"vspPrivateNonprofit\",\n new MongooseError.ValidatorError({\n path: \"vspPrivateNonprofit\",\n message: VSP_TWO_STEP_ISSUE.message,\n value: doc.vspPrivateNonprofit,\n }),\n );\n throw err;\n }\n });\n const validateOnUpdate = options.validateOnUpdate ?? true;\n schema.pre(\n [...AGENCY_ORG_TYPE_VALIDATED_UPDATE_OPS],\n function (this: Query<unknown, unknown>) {\n // The two-step on the update paths (always on — it is a shape rule,\n // not a validator option); the enum via runValidators under the option.\n if (!vspTwoStepHoldsOnUpdate(this.getUpdate())) {\n throw new Error(VSP_TWO_STEP_ISSUE.message);\n }\n if (validateOnUpdate) applyRunValidatorsIfUnset(this);\n },\n );\n return schema;\n}\n\n/**\n * Add the organization-type fields to an **Org** (registry) schema — the\n * HOME of the type and the attested HMIS facts (UDD Org Data Object). This\n * is the mount the Admin Hub writes through.\n *\n * @param schema - The consumer's organization schema (platform-db `organizations`)\n * @param options - See {@link AddAgencyOrgTypeFieldsOptions}\n * @returns The same schema, for chaining\n */\nexport function addOrgTypeFields<S extends Schema>(\n schema: S,\n options: AddAgencyOrgTypeFieldsOptions = {},\n): S {\n return mountOrgTypeFields(schema, options);\n}\n\n/**\n * Add the organization-type fields to an **Agency** schema as a MIRROR of\n * its Org's (same definition, same enum, same hook). The copy is stamped\n * from the Org via {@link mirrorOrgTypeFields} — at provisioning, and by the\n * backfill — and is never edited on the agency directly. An agency that has\n * no `organizationId` yet carries the backfill's confirmed value until it is\n * linked; once linked, the Org wins.\n *\n * @param schema - The consumer's agency schema (platform-db `agencies`)\n * @param options - See {@link AddAgencyOrgTypeFieldsOptions}\n * @returns The same schema, for chaining\n */\nexport function addAgencyOrgTypeFields<S extends Schema>(\n schema: S,\n options: AddAgencyOrgTypeFieldsOptions = {},\n): S {\n return mountOrgTypeFields(schema, options);\n}\n\n/** Anything that may carry the fields: an Org document, an Agency document, a plain object. */\nexport type OrgTypeFieldsHolder = Partial<Record<OrgTypeFieldName, unknown>>;\n\n/** The fields, picked exactly, `null` and `undefined` both left out (no assertion — see {@link mirrorOrgTypeFields}). */\nfunction pickOrgTypeFields(\n src: OrgTypeFieldsHolder | null | undefined,\n): AgencyOrgTypeFields {\n const out: Record<string, unknown> = {};\n if (src) {\n for (const k of ORG_TYPE_FIELD_NAMES) {\n const v = src[k];\n if (v != null) out[k] = v; // review nit: `null` on the Org must not leak into the copy\n }\n }\n return out as AgencyOrgTypeFields;\n}\n\n/**\n * The one way to produce the Agency's copy: the Org's fields, exactly, with\n * absent values kept absent (an Org that never attested `vsp` yields an\n * agency that never attested it — a copy never coerces a `false`; a `null`\n * is treated as absent, not copied). Any other key on the Org document is\n * ignored. Use it wherever an agency is created from, or re-linked to, its\n * Org, and on EVERY Org write of these fields (the re-stamp invariant in the\n * module doc).\n *\n * The copy ASSERTS the two-step (review Blocker 2): a malformed Org\n * (`vspPrivateNonprofit` answered without `vsp: true`) throws here rather\n * than being laundered onto the agency.\n */\nexport function mirrorOrgTypeFields(\n org: OrgTypeFieldsHolder | null | undefined,\n): AgencyOrgTypeFields {\n const out = pickOrgTypeFields(org);\n if (!vspTwoStepHolds(out)) {\n throw new Error(`mirrorOrgTypeFields: ${VSP_TWO_STEP_ISSUE.message}`);\n }\n return out;\n}\n\n// ─── Read precedence: the Org wins once linked (review Blocker 1) ───────────\n\n/**\n * The effective organization-type fields for an agency: the Org's when the\n * agency is LINKED (`organizationId` set) and the Org was loaded; otherwise\n * the agency's own copy (the backfill's confirmed value, until the link\n * exists); `{}` when neither carries anything. No guessing: an unlinked\n * agency with no copy answers nothing, in line with the 2026-10-07 rule that\n * an org → agency read with no clear answer \"answers nobody rather than\n * guessing\". Every consumer (Thread, PAVE, tooling) goes through this during\n * the interim so the precedence cannot diverge between apps.\n *\n * @param org - The agency's Org document, if the caller joined it (`null` when not loaded / not linked)\n * @param agency - The agency document (its `organizationId` decides \"linked\")\n */\nexport function resolveEffectiveOrgTypeFields(\n org: OrgTypeFieldsHolder | null | undefined,\n agency:\n (OrgTypeFieldsHolder & { organizationId?: unknown }) | null | undefined,\n): AgencyOrgTypeFields {\n const linked = agency != null && agency.organizationId != null;\n if (linked && org) return pickOrgTypeFields(org);\n return pickOrgTypeFields(agency);\n}\n\n/** {@link resolveEffectiveOrgTypeFields}, reduced to the one key readers join on (`null` = un-typed / unresolvable, read as `unknown`). */\nexport function resolveEffectiveOrgType(\n org: OrgTypeFieldsHolder | null | undefined,\n agency:\n (OrgTypeFieldsHolder & { organizationId?: unknown }) | null | undefined,\n): AgencyTypeKey | null {\n return resolveAgencyTypeKey(resolveEffectiveOrgTypeFields(org, agency).type);\n}\n\n/**\n * The fields on which the agency's copy differs from its Org — empty when the\n * mirror is faithful. Absent and `null` compare equal to each other (both\n * are \"not captured\"); any other difference is drift from a writer that\n * skipped the re-stamp. A reader should log it and read the Org.\n */\nexport function orgTypeFieldsDiffer(\n org: OrgTypeFieldsHolder | null | undefined,\n agency: OrgTypeFieldsHolder | null | undefined,\n): OrgTypeFieldName[] {\n const a = pickOrgTypeFields(org) as Record<string, unknown>;\n const b = pickOrgTypeFields(agency) as Record<string, unknown>;\n return ORG_TYPE_FIELD_NAMES.filter((k) => a[k] !== b[k]);\n}\n\n// ─── Type Inference ─────────────────────────────────────────────────\n\n/**\n * Raw (persistence) shape of the organization-type fields. Inferred from the\n * DEFINITION, not from a compiled `Schema` (see `schemas/team.ts` for why),\n * and wrapped in `Partial` because every field is absent on documents that\n * predate them.\n */\nexport type OrgTypeFields = Partial<\n InferRawDocType<typeof orgTypeSchemaDefinition>\n>;\n/** The Agency's mirror has the Org's exact shape. */\nexport type AgencyOrgTypeFields = OrgTypeFields;\n"],"mappings":";AA4BA,SAAS,SAAS;AA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ACtC,OAAO,kBAAkB,EACzB,OAAO,iBAAiB,kBAAkB;AAQtC,SAAS,kBAA2C,OAAU;AACnE,SAAOA,GACJ,OAAO,EAAE,GAAG,OAAO,GAAG,mBAAmB,CAAC,EAC1C,OAAO,iBAAiB,kBAAkB;AAC/C;AAGO,IAAM,sBAAsB;AAW5B,IAAM,wBAAwBA,GAClC,OAAO;AAAA,EACN,MAAM;AAAA,EACN,KAAKA,GAAE,QAAQ,EAAE,SAAS;AAAA,EAC1B,qBAAqBA,GAAE,QAAQ,EAAE,SAAS;AAC5C,CAAC,EACA,OAAO,EACP,OAAO,iBAAiB,kBAAkB;","names":["z","z","z","z"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@htilabs/platform-common-models",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"description": "Shared constants, types, and models for HTI Labs applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -67,31 +67,6 @@
|
|
|
67
67
|
"dist",
|
|
68
68
|
"src"
|
|
69
69
|
],
|
|
70
|
-
"scripts": {
|
|
71
|
-
"build": "tsup",
|
|
72
|
-
"dev": "tsup --watch",
|
|
73
|
-
"typecheck": "tsc --noEmit && tsc --noEmit -p scripts/tsconfig.json",
|
|
74
|
-
"lint": "eslint src --ext .ts",
|
|
75
|
-
"lint:fix": "eslint src --ext .ts --fix",
|
|
76
|
-
"test": "vitest run",
|
|
77
|
-
"test:watch": "vitest",
|
|
78
|
-
"test:snapshot": "UPDATE_SNAPSHOT=1 vitest run",
|
|
79
|
-
"clean": "rm -rf dist",
|
|
80
|
-
"codegen:cvc": "tsx scripts/codegen-cvc-enums.ts",
|
|
81
|
-
"codegen:cvc:check": "tsx scripts/codegen-cvc-enums.ts --check",
|
|
82
|
-
"import:cvcs": "node scripts/import-prototype-cvcs.mjs",
|
|
83
|
-
"sot:pins": "tsx scripts/sot-pins.ts",
|
|
84
|
-
"sot:pins:check": "tsx scripts/sot-pins.ts --check",
|
|
85
|
-
"gate:cvc": "vitest run src/__tests__/cvc-drift-gate.test.ts",
|
|
86
|
-
"bridge:codebook": "tsx scripts/codebook-bridge.ts",
|
|
87
|
-
"bridge:codebook:check": "tsx scripts/codebook-bridge.ts --check",
|
|
88
|
-
"test:bridge": "node --import tsx --test scripts/codebook-bridge.test.ts",
|
|
89
|
-
"seed:cvc": "tsx scripts/seed-cvc.ts",
|
|
90
|
-
"seed:cvc:all": "tsx scripts/seed-all-cvcs.ts",
|
|
91
|
-
"test:seed": "node --import tsx --test scripts/seed-cvc.test.ts",
|
|
92
|
-
"test:guard": "node --import tsx --test scripts/lib/confirmTargetDb.test.ts",
|
|
93
|
-
"prepublishOnly": "npm run build"
|
|
94
|
-
},
|
|
95
70
|
"keywords": [
|
|
96
71
|
"hti",
|
|
97
72
|
"platform-common",
|
|
@@ -126,5 +101,29 @@
|
|
|
126
101
|
},
|
|
127
102
|
"engines": {
|
|
128
103
|
"node": ">=18.0.0"
|
|
104
|
+
},
|
|
105
|
+
"scripts": {
|
|
106
|
+
"build": "tsup",
|
|
107
|
+
"dev": "tsup --watch",
|
|
108
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p scripts/tsconfig.json",
|
|
109
|
+
"lint": "eslint src --ext .ts",
|
|
110
|
+
"lint:fix": "eslint src --ext .ts --fix",
|
|
111
|
+
"test": "vitest run",
|
|
112
|
+
"test:watch": "vitest",
|
|
113
|
+
"test:snapshot": "UPDATE_SNAPSHOT=1 vitest run",
|
|
114
|
+
"clean": "rm -rf dist",
|
|
115
|
+
"codegen:cvc": "tsx scripts/codegen-cvc-enums.ts",
|
|
116
|
+
"codegen:cvc:check": "tsx scripts/codegen-cvc-enums.ts --check",
|
|
117
|
+
"import:cvcs": "node scripts/import-prototype-cvcs.mjs",
|
|
118
|
+
"sot:pins": "tsx scripts/sot-pins.ts",
|
|
119
|
+
"sot:pins:check": "tsx scripts/sot-pins.ts --check",
|
|
120
|
+
"gate:cvc": "vitest run src/__tests__/cvc-drift-gate.test.ts",
|
|
121
|
+
"bridge:codebook": "tsx scripts/codebook-bridge.ts",
|
|
122
|
+
"bridge:codebook:check": "tsx scripts/codebook-bridge.ts --check",
|
|
123
|
+
"test:bridge": "node --import tsx --test scripts/codebook-bridge.test.ts",
|
|
124
|
+
"seed:cvc": "tsx scripts/seed-cvc.ts",
|
|
125
|
+
"seed:cvc:all": "tsx scripts/seed-all-cvcs.ts",
|
|
126
|
+
"test:seed": "node --import tsx --test scripts/seed-cvc.test.ts",
|
|
127
|
+
"test:guard": "node --import tsx --test scripts/lib/confirmTargetDb.test.ts"
|
|
129
128
|
}
|
|
130
|
-
}
|
|
129
|
+
}
|
|
@@ -159,8 +159,8 @@
|
|
|
159
159
|
"hash": "18375cd14466851a6bcbd9bf3c37c28568d77cf6e26dc9ec76fa297900e9fbe6"
|
|
160
160
|
},
|
|
161
161
|
"referral_entity_category": {
|
|
162
|
-
"count":
|
|
163
|
-
"hash": "
|
|
162
|
+
"count": 47,
|
|
163
|
+
"hash": "4071e985c03bdd944d564355b2da4a9eed2f3caf3b0c58b4a5ae7f6b9f52115e"
|
|
164
164
|
},
|
|
165
165
|
"income_benefits_sources": {
|
|
166
166
|
"count": 41,
|
|
@@ -575,8 +575,8 @@
|
|
|
575
575
|
"hash": "8f650b786261619b2468eb3982c6146c21fa2ee3b1aa4504aa1084ad82543548"
|
|
576
576
|
},
|
|
577
577
|
"core_functions": {
|
|
578
|
-
"count":
|
|
579
|
-
"hash": "
|
|
578
|
+
"count": 82,
|
|
579
|
+
"hash": "2a9b7ed4af3c984d4818d7eb7a7997d9aa04cd0f74f22a48d80787282316be9c"
|
|
580
580
|
},
|
|
581
581
|
"needs_assessment_change_type": {
|
|
582
582
|
"count": 13,
|
|
@@ -584,7 +584,7 @@
|
|
|
584
584
|
},
|
|
585
585
|
"roi_scope": {
|
|
586
586
|
"count": 31,
|
|
587
|
-
"hash": "
|
|
587
|
+
"hash": "d6c1a419806b7ba629cdde796a1fe1e62084944142a78bb2b51fca96277156f6"
|
|
588
588
|
},
|
|
589
589
|
"roi_status": {
|
|
590
590
|
"count": 9,
|