@htilabs/platform-common-models 0.12.2 → 0.12.4
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/cvcs/index.cjs +170 -21
- package/dist/cvcs/index.cjs.map +1 -1
- package/dist/cvcs/index.d.cts +182 -27
- package/dist/cvcs/index.d.ts +182 -27
- package/dist/cvcs/index.js +170 -21
- package/dist/cvcs/index.js.map +1 -1
- package/dist/enums/index.cjs +2 -0
- package/dist/enums/index.cjs.map +1 -1
- package/dist/enums/index.d.cts +5 -3
- package/dist/enums/index.d.ts +5 -3
- package/dist/enums/index.js +2 -0
- package/dist/enums/index.js.map +1 -1
- package/dist/{index-4DiJrn7y.d.ts → index-C0J3f169.d.ts} +1 -1
- package/dist/{index-qreOzXYS.d.cts → index-EPjPjR0z.d.cts} +1 -1
- package/dist/index.cjs +227 -28
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +222 -28
- 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/schemas/index.cjs +41 -7
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +130 -26
- package/dist/schemas/index.d.ts +130 -26
- package/dist/schemas/index.js +38 -7
- package/dist/schemas/index.js.map +1 -1
- package/dist/{cvc-Cp4uWnAa.d.cts → team-C4LJ5Tex.d.cts} +36 -1
- package/dist/{cvc-Cp4uWnAa.d.ts → team-C4LJ5Tex.d.ts} +36 -1
- package/dist/validation/index.cjs +155 -0
- package/dist/validation/index.cjs.map +1 -1
- package/dist/validation/index.d.cts +1 -1
- package/dist/validation/index.d.ts +1 -1
- package/dist/validation/index.js +153 -0
- package/dist/validation/index.js.map +1 -1
- package/package.json +1 -1
- package/src/__tests__/__snapshots__/cvc-sot.snap +5 -1
- package/src/__tests__/core-information-scope-invariant.test.ts +179 -2
- package/src/__tests__/cvc-sot-snapshot.test.ts +10 -0
- package/src/__tests__/cvc-structural.test.ts +3 -0
- package/src/__tests__/location-type-routing-invariant.test.ts +202 -0
- package/src/__tests__/team-directory-fields.test.ts +252 -0
- package/src/cvcs/coreInformationScope.v1.0.0.json +39 -5
- package/src/cvcs/index.ts +3 -0
- package/src/cvcs/locationType.v1.0.0.json +131 -16
- package/src/generated/cvc-enums.ts +5 -3
- package/src/index.ts +7 -0
- package/src/schemas/index.ts +8 -0
- package/src/schemas/team.ts +118 -0
- package/src/validation/index.ts +1 -0
- package/src/validation/team.ts +48 -0
- package/dist/{cvcEntry-ctHTp2df.d.cts → cvcEntry-DaDrEuTa.d.cts} +8 -8
- package/dist/{cvcEntry-ctHTp2df.d.ts → cvcEntry-DaDrEuTa.d.ts} +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/validation/cvc.ts","../../src/validation/cvcStatus.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"],"mappings":";AA4BA,SAAS,SAAS;AAUX,IAAM,gBAAgB,EAAE,OAAO,EAAE,MAAM,oBAAoB;AAQ3D,IAAM,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB;AAez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,IAAI,cAAc,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC;AACrE,QAAI,iBAAiB,SAAS,GAAG;AAE/B,iBAAW,cAAc,CAAC,EAAE;AAC5B,aAAO,EAAE,UAAU,WAAW,MAAM;AAAA,IACtC;AACA,QAAI,iBAAiB,OAAO,GAAG;AAI7B,iBAAW,cAAc,CAAC,EAAE;AAC5B,aAAO,EAAE,UAAU,WAAW,KAAK;AAAA,IACrC;AAMA,WAAO,EAAE,UAAU,eAAe,WAAW,KAAK;AAAA,EACpD;AAEA,SAAO,EAAE,UAAU,WAAW,oBAAoB,KAAK,IAAI,EAAE;AAC/D;AAQO,SAAS,eAAe,UAAmD;AAChF,QAAM,SAAS,OAAO,SAAS,YAAY,WAAW,SAAS,UAAU;AACzE,QAAM,aAAa,QAAQ,MAAM,mBAAmB,KAAK;AACzD,QAAM,oBAAoB,eAAe;AACzC,QAAM,aAAa,aAAa,CAAC,KAAK;AAEtC,QAAM,OAAO,0BAA0B,SAAS,OAAO;AACvD,MAAI,SAAS,MAAM;AACjB,WAAO,EAAE,UAAU,SAAS,WAAW,MAAM,mBAAmB,YAAY,WAAW,MAAM;AAAA,EAC/F;AAEA,QAAM,EAAE,UAAU,UAAU,IAAI,eAAe,IAAI;AACnD,SAAO,EAAE,UAAU,WAAW,MAAM,mBAAmB,YAAY,UAAU;AAC/E;","names":[]}
|
|
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,EAAE,OAAO;AAAA,EACxC,QAAQ,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACxB,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACtB,SAAS,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EACzB,QAAQ,EAAE,OAAO,EAAE,OAAO,GAAG,EAAE,OAAO,CAAC;AAAA,EACvC,SAAS,EAAE,MAAM,cAAc;AACjC,CAAC;AA+BM,SAAS,YAAY,MAAsB;AAChD,QAAM,WAAW,KAAK,MAAM,GAAG;AAE/B,MAAI,SAAS,CAAC,MAAM,MAAO,QAA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,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"]}
|
package/package.json
CHANGED
|
@@ -156,7 +156,7 @@
|
|
|
156
156
|
},
|
|
157
157
|
"location_type": {
|
|
158
158
|
"count": 17,
|
|
159
|
-
"hash": "
|
|
159
|
+
"hash": "18375cd14466851a6bcbd9bf3c37c28568d77cf6e26dc9ec76fa297900e9fbe6"
|
|
160
160
|
},
|
|
161
161
|
"referral_entity_category": {
|
|
162
162
|
"count": 43,
|
|
@@ -701,6 +701,10 @@
|
|
|
701
701
|
"minor_adult_status": {
|
|
702
702
|
"count": 7,
|
|
703
703
|
"hash": "9d8972c65373a9981aab6b8749661659ecc632004e67bc9c2b3c88aa76f30977"
|
|
704
|
+
},
|
|
705
|
+
"core_information_scope": {
|
|
706
|
+
"count": 72,
|
|
707
|
+
"hash": "452561ad017b567f82f448bae1edbc482b8a6ef06b8ecdff3171edd46bec13b4"
|
|
704
708
|
}
|
|
705
709
|
}
|
|
706
710
|
}
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Two vocabularies describe the same thing at different grains:
|
|
6
6
|
*
|
|
7
7
|
* `roi_scope` flat item vocabulary, 27 substantive keys, no category axis
|
|
8
|
-
* `core_information_scope` 12 policy-grain CATEGORIES +
|
|
8
|
+
* `core_information_scope` 12 policy-grain CATEGORIES + 56 authorization-grain UNITS
|
|
9
9
|
*
|
|
10
10
|
* PAVE and Thread are both pinned to `roi_scope` today, and both persist stored
|
|
11
11
|
* ROIs against it. Migrating them to this domain is safe for exactly one reason:
|
|
@@ -41,6 +41,9 @@ interface Entry {
|
|
|
41
41
|
shareableDefault?: boolean;
|
|
42
42
|
required?: boolean;
|
|
43
43
|
platformFloor?: boolean;
|
|
44
|
+
levelFloor?: number;
|
|
45
|
+
appRelevance?: string[];
|
|
46
|
+
specialDataType?: string;
|
|
44
47
|
}
|
|
45
48
|
|
|
46
49
|
const read = (f: string): { entries: Entry[]; levels: Record<string, string> } =>
|
|
@@ -87,7 +90,7 @@ describe("core_information_scope — adoption invariants", () => {
|
|
|
87
90
|
|
|
88
91
|
it("is a strict superset — the additions are additions, not renames", () => {
|
|
89
92
|
expect(units.length).toBeGreaterThan(27);
|
|
90
|
-
expect(units).toHaveLength(
|
|
93
|
+
expect(units).toHaveLength(56);
|
|
91
94
|
});
|
|
92
95
|
|
|
93
96
|
it("keeps the two grains distinct: categories decide policy, units carry consent", () => {
|
|
@@ -132,3 +135,177 @@ describe("core_information_scope — adoption invariants", () => {
|
|
|
132
135
|
expect(of((u) => u.required === true)).toEqual(["system_info"]);
|
|
133
136
|
});
|
|
134
137
|
});
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Codes are POSITIONAL (category slot, unit slot within it), so a canon
|
|
141
|
+
* reorder or mid-list insertion would silently renumber codes already stored
|
|
142
|
+
* on ROIs and shares. The generator refuses that (its FROZEN table); this pins
|
|
143
|
+
* the same published assignment from the consumer side, so a hand-edit or a
|
|
144
|
+
* generator change that renumbers fails here too. New units APPEND inside
|
|
145
|
+
* their category; new categories APPEND at the end. Never reorder this table.
|
|
146
|
+
*/
|
|
147
|
+
const PUBLISHED: ReadonlyArray<readonly [string, readonly string[]]> = [
|
|
148
|
+
["identifying", ["names", "dob", "addresses", "additional_ids", "demographics"]],
|
|
149
|
+
[
|
|
150
|
+
"risk",
|
|
151
|
+
[
|
|
152
|
+
"screen_indicators",
|
|
153
|
+
"victimization",
|
|
154
|
+
"ida_full",
|
|
155
|
+
"ida_consid",
|
|
156
|
+
"initial_screen",
|
|
157
|
+
"tra",
|
|
158
|
+
"lap",
|
|
159
|
+
"danger_assessment",
|
|
160
|
+
"injury_and_strangulation",
|
|
161
|
+
"stalking_assessment",
|
|
162
|
+
"ae_intake",
|
|
163
|
+
"hope_scale",
|
|
164
|
+
"assessment_records",
|
|
165
|
+
"determinations",
|
|
166
|
+
"offender_facilitator",
|
|
167
|
+
"system_involvement",
|
|
168
|
+
"derived_risk_signals",
|
|
169
|
+
],
|
|
170
|
+
],
|
|
171
|
+
["contact", ["contact_info", "safe_locations", "priorities_safety", "encounter_location"]],
|
|
172
|
+
["services", ["contact_history", "service_history", "plans_goals"]],
|
|
173
|
+
["notes", ["screen_notes", "case_notes", "background"]],
|
|
174
|
+
[
|
|
175
|
+
"health_accommodation",
|
|
176
|
+
[
|
|
177
|
+
"accommodation_needs",
|
|
178
|
+
"disability_subtypes",
|
|
179
|
+
"mental_health_status",
|
|
180
|
+
"substance_use_status",
|
|
181
|
+
"chronic_health_status",
|
|
182
|
+
"hiv_status",
|
|
183
|
+
"mental_health_screen",
|
|
184
|
+
"trauma_and_coping_screen",
|
|
185
|
+
"behavioral_health_intake",
|
|
186
|
+
],
|
|
187
|
+
],
|
|
188
|
+
[
|
|
189
|
+
"immigration_legal_status",
|
|
190
|
+
[
|
|
191
|
+
"immigration_status",
|
|
192
|
+
"uscis_alien_number",
|
|
193
|
+
"federal_protection_applications",
|
|
194
|
+
"tvap_enrollment",
|
|
195
|
+
"le_report_status",
|
|
196
|
+
],
|
|
197
|
+
],
|
|
198
|
+
["system", ["system_info"]],
|
|
199
|
+
["network_associations", ["network_membership", "persona_links"]],
|
|
200
|
+
["commercial_activity", ["ad_content", "commercial_patterns"]],
|
|
201
|
+
["investigative_work_product", ["case_determinations", "case_lifecycle", "case_attachments"]],
|
|
202
|
+
["object_identifiers", ["phone_identifiers", "object_identity_attributes"]],
|
|
203
|
+
];
|
|
204
|
+
|
|
205
|
+
const seg = (n: number): string => String(n).padStart(3, "0");
|
|
206
|
+
const codeOf = (cat: number, unit = 0): string =>
|
|
207
|
+
`236-${seg(cat)}-${seg(unit)}-000-000-000-000`;
|
|
208
|
+
const byKey = new Map(scope.entries.map((e) => [e.key, e]));
|
|
209
|
+
|
|
210
|
+
describe("core_information_scope — published codes never move", () => {
|
|
211
|
+
it("keeps every published category and unit at its frozen positional code", () => {
|
|
212
|
+
const actual = [...categories, ...units].map((e): [string, string] => [e.key, e.code]);
|
|
213
|
+
const expected = PUBLISHED.flatMap(([cat, us], ci): [string, string][] => [
|
|
214
|
+
[cat, codeOf(ci + 1)],
|
|
215
|
+
...us.map((u, ui): [string, string] => [u, codeOf(ci + 1, ui + 1)]),
|
|
216
|
+
]);
|
|
217
|
+
// Exact equality, both directions: an unlisted addition fails too, so the
|
|
218
|
+
// table above is updated (by APPENDING) in the same change that mints it.
|
|
219
|
+
expect(new Map(actual)).toEqual(new Map(expected));
|
|
220
|
+
});
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* `priorities_safety` — canon CVC-236 amendment 2026-09-29
|
|
225
|
+
* (PRIORITIES-SAFETY-SCOPE-UNIT, Crysta R1; prototype `data/cvcs/
|
|
226
|
+
* core_information_scope.yaml` @ 285a9f1d). Thread's Priorities & Safety
|
|
227
|
+
* answers (immediate danger, safe place, dependents at risk) had NO unit, so
|
|
228
|
+
* they were unauthorizable and could not ride a share or an ROI at all.
|
|
229
|
+
*/
|
|
230
|
+
describe("core_information_scope — priorities_safety (2026-09-29)", () => {
|
|
231
|
+
const unit = byKey.get("priorities_safety");
|
|
232
|
+
|
|
233
|
+
it("is ONE selectable unit under Contact & safety, at the next contact slot", () => {
|
|
234
|
+
// R1: one unit for the whole step — not split across contact + services.
|
|
235
|
+
expect(unit).toBeDefined();
|
|
236
|
+
expect(unit?.code).toBe("236-003-003-000-000-000-000");
|
|
237
|
+
expect(unit?.selectable).toBe(true);
|
|
238
|
+
expect(unit?.parentCode).toBe(byKey.get("contact")?.code);
|
|
239
|
+
expect(byKey.get("contact")?.childCodes).toContain(unit?.code);
|
|
240
|
+
expect(
|
|
241
|
+
scope.entries.filter((e) => e.key.startsWith("priorities")).map((e) => e.key),
|
|
242
|
+
).toEqual(["priorities_safety"]);
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
it("carries canon's posture: shareable by default, never the platform floor", () => {
|
|
246
|
+
// R1 rejected heightened protection: the most action-relevant answers on
|
|
247
|
+
// the record must not be the hardest to pass to the next advocate.
|
|
248
|
+
expect(unit?.shareableDefault).toBe(true);
|
|
249
|
+
// R2: locations follow the location, never the question — the floor stays
|
|
250
|
+
// on safe_locations alone, nothing is carved out of this unit by hand.
|
|
251
|
+
expect(unit?.platformFloor).toBeUndefined();
|
|
252
|
+
expect(unit?.required).toBeUndefined();
|
|
253
|
+
expect(unit?.levelFloor).toBe(3);
|
|
254
|
+
expect(unit?.specialDataType).toBe("survivor_confidential");
|
|
255
|
+
expect(unit?.appRelevance).toEqual(["PAVE", "Thread"]);
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* `encounter_location` — canon CVC-236 amendment 2026-10-01
|
|
261
|
+
* (LOCATION-TYPE-LOGIC, Crysta R2; prototype `data/cvcs/
|
|
262
|
+
* core_information_scope.yaml` @ 55088d44). The session's own location
|
|
263
|
+
* entries — where the advocate met the survivor, or where the incident
|
|
264
|
+
* happened (CVC-191 reasons MEET_LOC + INCIDENT) — belonged to no person, so no
|
|
265
|
+
* share could reach them, and Thread was sending every session location under
|
|
266
|
+
* the `addresses` pick. They now ride this one unit.
|
|
267
|
+
*/
|
|
268
|
+
describe("core_information_scope — encounter_location (2026-10-01)", () => {
|
|
269
|
+
const unit = byKey.get("encounter_location");
|
|
270
|
+
|
|
271
|
+
it("is ONE selectable unit under Contact & safety, appended at the next contact slot", () => {
|
|
272
|
+
expect(unit).toBeDefined();
|
|
273
|
+
expect(unit?.code).toBe("236-003-004-000-000-000-000");
|
|
274
|
+
expect(unit?.selectable).toBe(true);
|
|
275
|
+
expect(unit?.parentCode).toBe(byKey.get("contact")?.code);
|
|
276
|
+
// Appended after priorities_safety: no published contact code moved.
|
|
277
|
+
expect(byKey.get("contact")?.childCodes).toEqual([
|
|
278
|
+
"236-003-001-000-000-000-000",
|
|
279
|
+
"236-003-002-000-000-000-000",
|
|
280
|
+
"236-003-003-000-000-000-000",
|
|
281
|
+
"236-003-004-000-000-000-000",
|
|
282
|
+
]);
|
|
283
|
+
// R2: one new unit. No second "residence" unit — residence vs. incident
|
|
284
|
+
// is already split by the CVC-191 reason.
|
|
285
|
+
expect(
|
|
286
|
+
scope.entries.filter((e) => e.key.includes("encounter")).map((e) => e.key),
|
|
287
|
+
).toEqual(["encounter_location"]);
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it("carries canon's posture: shareable by default, never the platform floor", () => {
|
|
291
|
+
// R2: where the survivor was found or met is the safety fact the next
|
|
292
|
+
// advocate needs, so the picker pre-checks it.
|
|
293
|
+
expect(unit?.shareableDefault).toBe(true);
|
|
294
|
+
// The floor stays on safe_locations alone; a shelter address picked as an
|
|
295
|
+
// encounter location is still caught by the floor, not by this unit.
|
|
296
|
+
expect(unit?.platformFloor).toBeUndefined();
|
|
297
|
+
expect(unit?.required).toBeUndefined();
|
|
298
|
+
expect(unit?.levelFloor).toBe(3);
|
|
299
|
+
expect(unit?.specialDataType).toBe("survivor_confidential");
|
|
300
|
+
expect(unit?.appRelevance).toEqual(["PAVE", "Thread"]);
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
it("leaves addresses where it was: the survivor's own whereabouts keep riding it", () => {
|
|
304
|
+
// R3: addresses keeps its code and posture; only its definition gains the
|
|
305
|
+
// type-grain routing note.
|
|
306
|
+
const addresses = byKey.get("addresses");
|
|
307
|
+
expect(addresses?.code).toBe("236-001-003-000-000-000-000");
|
|
308
|
+
expect(addresses?.shareableDefault).toBe(true);
|
|
309
|
+
expect(addresses?.platformFloor).toBeUndefined();
|
|
310
|
+
});
|
|
311
|
+
});
|
|
@@ -724,6 +724,16 @@ const SOT_SPECS: readonly SotSpec[] = [
|
|
|
724
724
|
// 3 substantive age bands (@pave/domain AGE_BANDS_AT_EVENT minus `unknown`,
|
|
725
725
|
// which maps to the missingness sentinel) + 4 missingness = 7
|
|
726
726
|
{ file: "minorAdultStatus.v1.0.0.json", domain: "minor_adult_status", expectedCount: 7 },
|
|
727
|
+
// CVC-236 — 12 policy-grain categories + 56 authorization-grain units
|
|
728
|
+
// (priorities_safety, 236-003-003, added 2026-09-29; encounter_location,
|
|
729
|
+
// 236-003-004, added 2026-10-01) + 1 missingness root + 3
|
|
730
|
+
// workspace-standard missingness children = 72. Generated by
|
|
731
|
+
// scripts/gen-core-information-scope.py; codes are FROZEN there.
|
|
732
|
+
{
|
|
733
|
+
file: "coreInformationScope.v1.0.0.json",
|
|
734
|
+
domain: "core_information_scope",
|
|
735
|
+
expectedCount: 72,
|
|
736
|
+
},
|
|
727
737
|
] as const;
|
|
728
738
|
|
|
729
739
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
@@ -233,6 +233,9 @@ const SOT_FILES: readonly SotFile[] = [
|
|
|
233
233
|
{ file: "sessionNoteVisibility.v1.0.0.json", expectedDomain: "session_note_visibility" },
|
|
234
234
|
{ file: "specialNeedsDisabilities.v1.0.0.json", expectedDomain: "special_needs_disabilities" },
|
|
235
235
|
{ file: "suggestionSource.v1.0.0.json", expectedDomain: "suggestion_source" },
|
|
236
|
+
// CVC-236 — generated by scripts/gen-core-information-scope.py. Omitted from
|
|
237
|
+
// this list since it was authored; added with the priorities_safety unit.
|
|
238
|
+
{ file: "coreInformationScope.v1.0.0.json", expectedDomain: "core_information_scope" },
|
|
236
239
|
// ─── GDR §10.1 CAR-contract vocabularies (provisional 900-block; PAVE
|
|
237
240
|
// @pave/domain verbatim; bead pv-pgdr-cvc-source-gdr-10-1-bulk-publish). ───
|
|
238
241
|
{ file: "assertionStatus.v1.0.0.json", expectedDomain: "assertion_status" },
|