@htilabs/platform-common-models 0.2.0-beta.3 → 0.3.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +38 -0
  2. package/dist/constants/index.cjs +0 -140
  3. package/dist/constants/index.cjs.map +1 -1
  4. package/dist/constants/index.d.cts +146 -5
  5. package/dist/constants/index.d.ts +146 -5
  6. package/dist/constants/index.js +0 -128
  7. package/dist/constants/index.js.map +1 -1
  8. package/dist/{platform-role-AHv1l5Og.d.cts → cvcEntry-wqktWfzE.d.cts} +231 -37
  9. package/dist/{platform-role-AHv1l5Og.d.ts → cvcEntry-wqktWfzE.d.ts} +231 -37
  10. package/dist/cvcs/index.cjs +2184 -0
  11. package/dist/cvcs/index.cjs.map +1 -0
  12. package/dist/cvcs/index.d.cts +2384 -0
  13. package/dist/cvcs/index.d.ts +2384 -0
  14. package/dist/cvcs/index.js +2154 -0
  15. package/dist/cvcs/index.js.map +1 -0
  16. package/dist/index--NCIPluF.d.cts +378 -0
  17. package/dist/index-CFOrHA8l.d.ts +378 -0
  18. package/dist/index.cjs +2962 -140
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +217 -3
  21. package/dist/index.d.ts +217 -3
  22. package/dist/index.js +2934 -128
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.cjs +211 -0
  25. package/dist/models/index.cjs.map +1 -1
  26. package/dist/models/index.d.cts +3 -292
  27. package/dist/models/index.d.ts +3 -292
  28. package/dist/models/index.js +209 -0
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{platform-auth-DHSJP7XP.d.cts → platform-auth-C-G2qeGM.d.cts} +1 -36
  31. package/dist/{platform-auth-DHSJP7XP.d.ts → platform-auth-C-G2qeGM.d.ts} +1 -36
  32. package/dist/schemas/index.cjs +195 -116
  33. package/dist/schemas/index.cjs.map +1 -1
  34. package/dist/schemas/index.d.cts +11 -11
  35. package/dist/schemas/index.d.ts +11 -11
  36. package/dist/schemas/index.js +189 -116
  37. package/dist/schemas/index.js.map +1 -1
  38. package/dist/services/index.cjs +1442 -0
  39. package/dist/services/index.cjs.map +1 -0
  40. package/dist/services/index.d.cts +305 -0
  41. package/dist/services/index.d.ts +305 -0
  42. package/dist/services/index.js +1417 -0
  43. package/dist/services/index.js.map +1 -0
  44. package/dist/types/index.d.cts +2 -2
  45. package/dist/types/index.d.ts +2 -2
  46. package/dist/validation/index.cjs +261 -0
  47. package/dist/validation/index.cjs.map +1 -0
  48. package/dist/validation/index.d.cts +251 -0
  49. package/dist/validation/index.d.ts +251 -0
  50. package/dist/validation/index.js +228 -0
  51. package/dist/validation/index.js.map +1 -0
  52. package/package.json +36 -12
  53. package/src/__tests__/__snapshots__/cvc-sot.snap +22 -0
  54. package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
  55. package/src/__tests__/cvc-structural.test.ts +130 -0
  56. package/src/constants/ic.ts +0 -154
  57. package/src/constants/service-catalog.ts +146 -4
  58. package/src/cvcs/index.ts +31 -0
  59. package/src/cvcs/missingness.v1.0.0.json +50 -0
  60. package/src/cvcs/serviceCategories.v1.0.0.json +1947 -0
  61. package/src/cvcs/serviceMechanisms.v1.0.0.json +47 -0
  62. package/src/cvcs/serviceStates.v1.0.0.json +106 -0
  63. package/src/generated/cvc-enums.ts +215 -0
  64. package/src/index.ts +61 -1
  65. package/src/models/cvcEntryModel.ts +32 -0
  66. package/src/models/cvcRegistryModel.ts +35 -0
  67. package/src/models/index.ts +8 -0
  68. package/src/schemas/cvcEntry.ts +158 -0
  69. package/src/schemas/cvcRegistry.ts +149 -0
  70. package/src/schemas/index.ts +16 -0
  71. package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
  72. package/src/services/cvcRegistryService.ts +729 -0
  73. package/src/services/index.ts +21 -0
  74. package/src/validation/cvc.ts +414 -0
  75. package/src/validation/index.ts +15 -0
@@ -0,0 +1,21 @@
1
+ /**
2
+ * @htilabs/platform-common-models — Services
3
+ *
4
+ * Runtime services that operate on the platform models. Currently houses
5
+ * the CVC registry runtime API; future services (form resolution, etc.)
6
+ * should follow the same export pattern.
7
+ */
8
+
9
+ export {
10
+ CvcRegistryService,
11
+ cascadeExclusions,
12
+ applyEntryOverrides,
13
+ resolveRegistryWithInheritance,
14
+ cvcVersionsToRecord,
15
+ type RegistryScope,
16
+ type CvcRegistryServiceOptions,
17
+ type ICvcRegistry,
18
+ type ICvcEntry,
19
+ type RegistryLoader,
20
+ type EntryLoader,
21
+ } from "./cvcRegistryService.js";
@@ -0,0 +1,414 @@
1
+ /**
2
+ * @htilabs/platform-common-models — Controlled Vocabulary (CVC) Validation
3
+ *
4
+ * Zod schemas for validating CVC Source-of-Truth (SOT) JSON files and
5
+ * individual CVC entries. Implements the locked spec §9.2 shapes.
6
+ *
7
+ * Used by:
8
+ * - CI structural tests that parse every committed SOT file.
9
+ * - The generalized seed CLI (`seedCvc`) prior to persistence.
10
+ * - Downstream consumers that need to validate CVC payloads.
11
+ *
12
+ * Canonical spec:
13
+ * /gt/docs/data/cvcs/CVC Implementation Spec 2780449faf8045258c67daab0f1c5569.md
14
+ *
15
+ * Locked decisions (2026-04-10):
16
+ * - Positional 7-segment codes `XX-XX-XX-XX-XX-XX-XX` (§3).
17
+ * - `missingness` envelope field is an optional `string[]`; `["all"]` is the
18
+ * sentinel meaning "merge all missingness values" (§2.1, §5.2).
19
+ * - `missingness.v1.0.0.json` wraps its values under a synthetic root
20
+ * (`missingness_root`) which is the one sanctioned parent-child exception
21
+ * for level-consistency, scoped by segment-1 domain prefix (§5.1).
22
+ */
23
+
24
+ import { z } from "zod";
25
+
26
+ // ─── Primitive schemas ───────────────────────────────────────────────────────
27
+
28
+ /**
29
+ * 7-segment positional CVC code: `XX-XX-XX-XX-XX-XX-XX` (two digits per
30
+ * segment). Segments are filled left-to-right as levels deepen; unused
31
+ * segments remain `00`. See locked spec §3.
32
+ */
33
+ export const CvcCodeSchema = z.string().regex(/^\d{2}(-\d{2}){6}$/);
34
+
35
+ /**
36
+ * Stable machine key for a CVC entry. Must start with a lowercase letter and
37
+ * contain only lowercase alphanumerics or underscores. Used as a cross-CVC
38
+ * reference target (e.g. `relevantMechanisms` pointing at mechanism keys).
39
+ * See locked spec §3.2.
40
+ */
41
+ export const CvcKeySchema = z.string().regex(/^[a-z][a-z0-9_]*$/);
42
+
43
+ // ─── Entry schemas ───────────────────────────────────────────────────────────
44
+
45
+ /**
46
+ * Base entry shape shared by every CVC domain. Domain-specific extensions
47
+ * (e.g. `ServiceCategoryEntrySchema`) should use `.extend()` to add fields.
48
+ * See locked spec §9.2.
49
+ *
50
+ * Uses `.passthrough()` so that domain-specific fields (like
51
+ * `relevantMechanisms` on service-category entries) survive base parsing
52
+ * unmodified. This keeps cross-CVC reference validation honest: the §4.5
53
+ * structural validator needs to see the raw referenced keys, and a strip-by-
54
+ * default schema would silently hide them.
55
+ */
56
+ export const CvcEntrySchema = z
57
+ .object({
58
+ code: CvcCodeSchema,
59
+ key: CvcKeySchema,
60
+ title: z.string().min(1),
61
+ selectable: z.boolean(),
62
+ parentCode: CvcCodeSchema.nullable(),
63
+ childCodes: z.array(CvcCodeSchema),
64
+ definition: z.string().nullable(),
65
+ })
66
+ .passthrough();
67
+
68
+ /**
69
+ * Service-category-specific entry. Adds `relevantMechanisms` — a cross-CVC
70
+ * reference into the `service_mechanisms` domain via entry keys. `null` means
71
+ * "not applicable" (e.g. structural L1 topic rows). See locked spec §9.2.
72
+ */
73
+ export const ServiceCategoryEntrySchema = CvcEntrySchema.extend({
74
+ relevantMechanisms: z.array(CvcKeySchema).nullable(),
75
+ });
76
+
77
+ // ─── Envelope schema ─────────────────────────────────────────────────────────
78
+
79
+ /**
80
+ * Top-level SOT JSON envelope. One envelope per (domain, version) pair.
81
+ *
82
+ * `missingness` is an optional array of missingness keys to merge into this
83
+ * CVC at seed time. `["all"]` is the sentinel meaning "merge the missingness
84
+ * root plus all three value entries". Individual keys merge only those.
85
+ * Absent, empty, or null means "skip missingness merge". The missingness CVC
86
+ * file itself omits this field because merging missingness into itself is
87
+ * nonsensical. See locked spec §2.1 and §5.2.
88
+ *
89
+ * `levels` is a positional map from level number (`"0"`, `"1"`, …) to a human
90
+ * label describing the level.
91
+ */
92
+ export const CvcEnvelopeSchema = z.object({
93
+ domain: z.string().min(1),
94
+ name: z.string().min(1),
95
+ version: z.string().min(1),
96
+ missingness: z.array(z.string()).optional(),
97
+ levels: z.record(z.string(), z.string()),
98
+ entries: z.array(CvcEntrySchema),
99
+ });
100
+
101
+ // ─── Inferred types ──────────────────────────────────────────────────────────
102
+
103
+ export type CvcCode = z.infer<typeof CvcCodeSchema>;
104
+ export type CvcKey = z.infer<typeof CvcKeySchema>;
105
+ export type CvcEntry = z.infer<typeof CvcEntrySchema>;
106
+ export type ServiceCategoryEntry = z.infer<typeof ServiceCategoryEntrySchema>;
107
+ export type CvcEnvelope = z.infer<typeof CvcEnvelopeSchema>;
108
+
109
+ /**
110
+ * SOT family identifier (e.g. `"service_categories"`, `"service_states"`,
111
+ * `"service_mechanisms"`, `"missingness"`). The canonical list of domains is
112
+ * enumerated by the SOT JSON files in `src/cvcs/`. Typed as `string` rather
113
+ * than a closed union so adding a new SOT file does not require touching this
114
+ * type. See locked spec §2.
115
+ */
116
+ export type CvcDomain = string;
117
+
118
+ // ─── Structural validator (locked spec §4 / §9.3) ───────────────────────────
119
+
120
+ /**
121
+ * Derive an entry's level from its 7-segment code per locked spec §3.3.
122
+ *
123
+ * - Segment 7 non-zero → level 0 (missingness value entry, e.g. `unknown`).
124
+ * - Otherwise return the index (1..5) of the last non-zero hierarchy segment.
125
+ * - All segments zero → level 0 (missingness root, `00-00-00-00-00-00-00`).
126
+ */
127
+ export function getCvcLevel(code: string): number {
128
+ const segments = code.split("-");
129
+ // segments[6] is the missingness slot (positional segment 7).
130
+ if (segments[6] !== "00") return 0;
131
+ // Walk hierarchy segments 6..2 (indices 5..1) looking for the deepest
132
+ // populated level.
133
+ for (let i = 5; i >= 1; i -= 1) {
134
+ if (segments[i] !== "00") return i;
135
+ }
136
+ return 0;
137
+ }
138
+
139
+ /**
140
+ * Error collected by {@link validateCvc}. Each error names the invariant it
141
+ * violates (`C1`..`C8`) so CI output points straight at the locked spec rule
142
+ * that failed. `code` or `key` narrow the error to a specific entry when the
143
+ * violation is entry-scoped.
144
+ */
145
+ export interface CvcValidationError {
146
+ invariant: "C1" | "C2" | "C3" | "C4" | "C5" | "C6" | "C7" | "C8";
147
+ message: string;
148
+ code?: string;
149
+ key?: string;
150
+ }
151
+
152
+ /**
153
+ * Structural invariants to enforce on every committed SOT file per locked spec
154
+ * §4. Zod's schema `parse()` guarantees the *shape* of the envelope; this
155
+ * function enforces the cross-entry *semantics* that Zod cannot express.
156
+ *
157
+ * Invariants (locked spec §4):
158
+ * - **C1** Code format + uniqueness (§4.1).
159
+ * - **C2** Key format + uniqueness (§4.2).
160
+ * - **C3** Tree: every `parentCode` resolves to an existing entry or null; no
161
+ * cycles (§4.3).
162
+ * - **C4** `childCodes` are the exact bidirectional inverse of `parentCode`
163
+ * (§4.3).
164
+ * - **C5** Selectability is a boolean (§4.4).
165
+ * - **C6** Cross-CVC `relevantMechanisms` references resolve against a
166
+ * provided `service_mechanisms` key set (§4.5, §7). Only checked when the
167
+ * caller supplies `options.mechanismKeys`.
168
+ * - **C7** Envelope has all 6 required fields (`domain`, `name`, `version`,
169
+ * `missingness`, `levels`, `entries`) — treating the optional-in-Zod
170
+ * `missingness` as required at CI time (§4.6).
171
+ * - **C8** No entry anywhere contains a key `'provided'` (legacy Thread UI
172
+ * label guard; not a canonical state).
173
+ *
174
+ * @param envelope Parsed envelope (typically from `CvcEnvelopeSchema.parse()`).
175
+ * @param options.mechanismKeys Optional set of valid `service_mechanisms`
176
+ * entry keys. If provided and the envelope entries have `relevantMechanisms`
177
+ * fields, each referenced key must be in this set (C6).
178
+ * @returns An array of {@link CvcValidationError}. An empty array means valid.
179
+ */
180
+ export function validateCvc(
181
+ envelope: CvcEnvelope,
182
+ options: { mechanismKeys?: ReadonlySet<string> } = {},
183
+ ): CvcValidationError[] {
184
+ const errors: CvcValidationError[] = [];
185
+ const { entries } = envelope;
186
+
187
+ // C7: envelope-level required fields. Zod already rejects missing `domain`,
188
+ // `name`, `version`, `levels`, and `entries`. We additionally require
189
+ // `missingness` to be present (even as an empty array) at CI time so the
190
+ // seed CLI sees an explicit "opt-out" rather than an undefined field.
191
+ //
192
+ // Exemption: the `missingness` CVC file itself legitimately omits this
193
+ // field because merging missingness into itself is nonsensical (locked spec
194
+ // §9.2). This is the one sanctioned omission.
195
+ if (envelope.domain !== "missingness" && envelope.missingness === undefined) {
196
+ errors.push({
197
+ invariant: "C7",
198
+ message:
199
+ "envelope is missing required field `missingness` (must be an array, " +
200
+ "use `[]` to opt out of the missingness merge)",
201
+ });
202
+ }
203
+
204
+ // ── C1: code format + uniqueness ──────────────────────────────────────────
205
+ const codeRe = /^\d{2}(-\d{2}){6}$/;
206
+ const seenCodes = new Set<string>();
207
+ for (const entry of entries) {
208
+ if (!codeRe.test(entry.code)) {
209
+ errors.push({
210
+ invariant: "C1",
211
+ message: `code does not match /^\\d{2}(-\\d{2}){6}$/`,
212
+ code: entry.code,
213
+ key: entry.key,
214
+ });
215
+ }
216
+ if (seenCodes.has(entry.code)) {
217
+ errors.push({
218
+ invariant: "C1",
219
+ message: `duplicate code`,
220
+ code: entry.code,
221
+ key: entry.key,
222
+ });
223
+ }
224
+ seenCodes.add(entry.code);
225
+ }
226
+
227
+ // ── C2: key format + uniqueness ───────────────────────────────────────────
228
+ const keyRe = /^[a-z][a-z0-9_]*$/;
229
+ const seenKeys = new Set<string>();
230
+ for (const entry of entries) {
231
+ if (!keyRe.test(entry.key)) {
232
+ errors.push({
233
+ invariant: "C2",
234
+ message: `key does not match /^[a-z][a-z0-9_]*$/`,
235
+ code: entry.code,
236
+ key: entry.key,
237
+ });
238
+ }
239
+ if (seenKeys.has(entry.key)) {
240
+ errors.push({
241
+ invariant: "C2",
242
+ message: `duplicate key`,
243
+ code: entry.code,
244
+ key: entry.key,
245
+ });
246
+ }
247
+ seenKeys.add(entry.key);
248
+ }
249
+
250
+ // Build a lookup by code for the remaining tree checks. Skip entries whose
251
+ // code we already know is malformed — their index would be meaningless.
252
+ const byCode = new Map<string, CvcEntry>();
253
+ for (const entry of entries) {
254
+ if (codeRe.test(entry.code)) byCode.set(entry.code, entry);
255
+ }
256
+
257
+ // ── C3: tree — parents resolve, no cycles ─────────────────────────────────
258
+ for (const entry of entries) {
259
+ if (entry.parentCode === null) continue;
260
+ if (!byCode.has(entry.parentCode)) {
261
+ errors.push({
262
+ invariant: "C3",
263
+ message: `parentCode ${entry.parentCode} does not resolve to any entry in this CVC`,
264
+ code: entry.code,
265
+ key: entry.key,
266
+ });
267
+ }
268
+ }
269
+
270
+ // Cycle detection: walk parent chain from each entry, bail if we revisit.
271
+ for (const entry of entries) {
272
+ const visited = new Set<string>();
273
+ let cursor: CvcEntry | undefined = entry;
274
+ while (cursor && cursor.parentCode !== null) {
275
+ if (visited.has(cursor.code)) {
276
+ errors.push({
277
+ invariant: "C3",
278
+ message: `cycle detected in parentCode chain starting from ${entry.code}`,
279
+ code: entry.code,
280
+ key: entry.key,
281
+ });
282
+ break;
283
+ }
284
+ visited.add(cursor.code);
285
+ cursor = byCode.get(cursor.parentCode);
286
+ }
287
+ }
288
+
289
+ // ── C4: childCodes are exact inverse of parentCode ────────────────────────
290
+ // Build the set of (parent, child) edges from parentCode, then from
291
+ // childCodes, and require they match exactly.
292
+ const parentToChildrenFromParent = new Map<string, Set<string>>();
293
+ for (const entry of entries) {
294
+ if (entry.parentCode !== null) {
295
+ let set = parentToChildrenFromParent.get(entry.parentCode);
296
+ if (!set) {
297
+ set = new Set();
298
+ parentToChildrenFromParent.set(entry.parentCode, set);
299
+ }
300
+ set.add(entry.code);
301
+ }
302
+ }
303
+
304
+ for (const entry of entries) {
305
+ const declared = new Set(entry.childCodes);
306
+ const derived = parentToChildrenFromParent.get(entry.code) ?? new Set();
307
+
308
+ for (const child of declared) {
309
+ if (!derived.has(child)) {
310
+ errors.push({
311
+ invariant: "C4",
312
+ message: `entry lists ${child} in childCodes but that entry's parentCode is not ${entry.code}`,
313
+ code: entry.code,
314
+ key: entry.key,
315
+ });
316
+ }
317
+ }
318
+ for (const child of derived) {
319
+ if (!declared.has(child)) {
320
+ errors.push({
321
+ invariant: "C4",
322
+ message: `entry ${child} has parentCode ${entry.code} but is missing from its childCodes`,
323
+ code: entry.code,
324
+ key: entry.key,
325
+ });
326
+ }
327
+ }
328
+ }
329
+
330
+ // ── C5: selectability per §4.4 ────────────────────────────────────────────
331
+ // Zod already enforces `selectable: boolean`; we make the invariant explicit
332
+ // at validator level so a future schema loosening cannot silently bypass it.
333
+ for (const entry of entries) {
334
+ if (typeof entry.selectable !== "boolean") {
335
+ errors.push({
336
+ invariant: "C5",
337
+ message: `selectable must be a boolean, got ${typeof entry.selectable}`,
338
+ code: entry.code,
339
+ key: entry.key,
340
+ });
341
+ }
342
+ }
343
+
344
+ // ── C6: cross-CVC refs — `relevantMechanisms` resolves against provided set
345
+ if (options.mechanismKeys) {
346
+ for (const entry of entries) {
347
+ const raw = (entry as unknown as Record<string, unknown>)[
348
+ "relevantMechanisms"
349
+ ];
350
+ if (raw === undefined || raw === null) continue;
351
+ if (!Array.isArray(raw)) {
352
+ errors.push({
353
+ invariant: "C6",
354
+ message: `relevantMechanisms must be an array or null`,
355
+ code: entry.code,
356
+ key: entry.key,
357
+ });
358
+ continue;
359
+ }
360
+ for (const mechKey of raw) {
361
+ if (
362
+ typeof mechKey !== "string" ||
363
+ !options.mechanismKeys.has(mechKey)
364
+ ) {
365
+ errors.push({
366
+ invariant: "C6",
367
+ message: `relevantMechanisms references unknown service_mechanisms key: ${String(mechKey)}`,
368
+ code: entry.code,
369
+ key: entry.key,
370
+ });
371
+ }
372
+ }
373
+ }
374
+ }
375
+
376
+ // ── C8: legacy `'provided'` key guard ─────────────────────────────────────
377
+ // Walk every property of every entry (including nested arrays) looking for
378
+ // a key named `'provided'`. It is a Thread UI label, not a canonical state.
379
+ const walkForProvided = (value: unknown, entry: CvcEntry): void => {
380
+ if (value === null || value === undefined) return;
381
+ if (Array.isArray(value)) {
382
+ for (const item of value) walkForProvided(item, entry);
383
+ return;
384
+ }
385
+ if (typeof value === "object") {
386
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
387
+ if (k === "provided") {
388
+ errors.push({
389
+ invariant: "C8",
390
+ message: `entry contains forbidden legacy key 'provided' (see locked spec §4)`,
391
+ code: entry.code,
392
+ key: entry.key,
393
+ });
394
+ }
395
+ walkForProvided(v, entry);
396
+ }
397
+ }
398
+ };
399
+ for (const entry of entries) {
400
+ walkForProvided(entry, entry);
401
+ // Also guard against a literal string value of 'provided' appearing as an
402
+ // entry's `key`, which would be an obvious smuggling attempt.
403
+ if (entry.key === "provided") {
404
+ errors.push({
405
+ invariant: "C8",
406
+ message: `entry key must not be the legacy label 'provided'`,
407
+ code: entry.code,
408
+ key: entry.key,
409
+ });
410
+ }
411
+ }
412
+
413
+ return errors;
414
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @htilabs/platform-common-models — Validation barrel
3
+ *
4
+ * Public entry point for the Zod validation surface. Consumers that want
5
+ * the canonical Zod-inferred `CvcEntry` (rather than the Mongoose persistence
6
+ * shape exported from the package root) should import from here:
7
+ *
8
+ * ```ts
9
+ * import { CvcEntry, CvcEntrySchema } from '@htilabs/platform-common-models/validation';
10
+ * ```
11
+ *
12
+ * See `./cvc.ts` for the schema and type definitions.
13
+ */
14
+
15
+ export * from "./cvc.js";