@htilabs/platform-common-models 0.2.0-beta.4 → 0.4.0-beta.1

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 (74) hide show
  1. package/README.md +38 -0
  2. package/dist/constants/index.cjs +0 -843
  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 -786
  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 +2350 -0
  11. package/dist/cvcs/index.cjs.map +1 -0
  12. package/dist/cvcs/index.d.cts +2449 -0
  13. package/dist/cvcs/index.d.ts +2449 -0
  14. package/dist/cvcs/index.js +2321 -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 +3132 -843
  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 +3106 -786
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.cjs +212 -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 +210 -0
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{platform-auth-BTbQIY3b.d.cts → platform-auth-C-G2qeGM.d.cts} +1 -297
  31. package/dist/{platform-auth-BTbQIY3b.d.ts → platform-auth-C-G2qeGM.d.ts} +1 -297
  32. package/dist/schemas/index.cjs +196 -729
  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 +190 -729
  37. package/dist/schemas/index.js.map +1 -1
  38. package/dist/services/index.cjs +1443 -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 +1418 -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 +254 -0
  47. package/dist/validation/index.cjs.map +1 -0
  48. package/dist/validation/index.d.cts +252 -0
  49. package/dist/validation/index.d.ts +252 -0
  50. package/dist/validation/index.js +221 -0
  51. package/dist/validation/index.js.map +1 -0
  52. package/package.json +36 -12
  53. package/src/__tests__/__snapshots__/cvc-sot.snap +18 -0
  54. package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
  55. package/src/__tests__/cvc-structural.test.ts +129 -0
  56. package/src/constants/ic.ts +0 -925
  57. package/src/constants/service-catalog.ts +146 -4
  58. package/src/cvcs/index.ts +30 -0
  59. package/src/cvcs/serviceCategories.v1.0.0.json +2077 -0
  60. package/src/cvcs/serviceMechanisms.v1.0.0.json +87 -0
  61. package/src/cvcs/serviceStates.v1.0.0.json +146 -0
  62. package/src/generated/cvc-enums.ts +213 -0
  63. package/src/index.ts +61 -1
  64. package/src/models/cvcEntryModel.ts +32 -0
  65. package/src/models/cvcRegistryModel.ts +35 -0
  66. package/src/models/index.ts +8 -0
  67. package/src/schemas/cvcEntry.ts +159 -0
  68. package/src/schemas/cvcRegistry.ts +150 -0
  69. package/src/schemas/index.ts +16 -0
  70. package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
  71. package/src/services/cvcRegistryService.ts +729 -0
  72. package/src/services/index.ts +21 -0
  73. package/src/validation/cvc.ts +397 -0
  74. 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,397 @@
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
+ * Format v2 (2026-04-15):
16
+ * - Positional 7-segment codes `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (3 digits per
17
+ * segment). Segment 1 is the Notion-aligned domain prefix:
18
+ * `022` service_categories (CVC-22)
19
+ * `025` service_mechanisms (CVC-25)
20
+ * `049` service_state (CVC-49)
21
+ * - Missingness entries are embedded per-domain (synthetic `missingness_root`
22
+ * at `<prefix>-000-000-000-000-000-000` plus three values at segment 7 =
23
+ * `001`/`002`/`003`). The shared `missingness.v1.0.0.json` file was
24
+ * retired in favor of per-domain missingness.
25
+ * - Envelope `missingness` field and the C7 invariant have been removed; the
26
+ * shared-merge pathway no longer exists.
27
+ */
28
+
29
+ import { z } from "zod";
30
+
31
+ // ─── Primitive schemas ───────────────────────────────────────────────────────
32
+
33
+ /**
34
+ * 7-segment positional CVC code: `XXX-XXX-XXX-XXX-XXX-XXX-XXX` (three digits
35
+ * per segment). Segment 1 is the Notion-aligned domain prefix. Remaining
36
+ * hierarchy segments are filled left-to-right as levels deepen; unused
37
+ * segments remain `000`. See locked spec §3 (format v2).
38
+ */
39
+ export const CvcCodeSchema = z.string().regex(/^\d{3}(-\d{3}){6}$/);
40
+
41
+ /**
42
+ * Stable machine key for a CVC entry. Must start with a lowercase letter and
43
+ * contain only lowercase alphanumerics or underscores. Used as a cross-CVC
44
+ * reference target (e.g. `relevantMechanisms` pointing at mechanism keys).
45
+ * See locked spec §3.2.
46
+ */
47
+ export const CvcKeySchema = z.string().regex(/^[a-z][a-z0-9_]*$/);
48
+
49
+ // ─── Entry schemas ───────────────────────────────────────────────────────────
50
+
51
+ /**
52
+ * Base entry shape shared by every CVC domain. Domain-specific extensions
53
+ * (e.g. `ServiceCategoryEntrySchema`) should use `.extend()` to add fields.
54
+ * See locked spec §9.2.
55
+ *
56
+ * Uses `.passthrough()` so that domain-specific fields (like
57
+ * `relevantMechanisms` on service-category entries) survive base parsing
58
+ * unmodified. This keeps cross-CVC reference validation honest: the §4.5
59
+ * structural validator needs to see the raw referenced keys, and a strip-by-
60
+ * default schema would silently hide them.
61
+ */
62
+ export const CvcEntrySchema = z
63
+ .object({
64
+ code: CvcCodeSchema,
65
+ key: CvcKeySchema,
66
+ title: z.string().min(1),
67
+ selectable: z.boolean(),
68
+ parentCode: CvcCodeSchema.nullable(),
69
+ childCodes: z.array(CvcCodeSchema),
70
+ definition: z.string().nullable(),
71
+ })
72
+ .passthrough();
73
+
74
+ /**
75
+ * Service-category-specific entry. Adds `relevantMechanisms` — a cross-CVC
76
+ * reference into the `service_mechanisms` domain via entry keys. `null` means
77
+ * "not applicable" (e.g. structural L1 topic rows). See locked spec §9.2.
78
+ */
79
+ export const ServiceCategoryEntrySchema = CvcEntrySchema.extend({
80
+ relevantMechanisms: z.array(CvcKeySchema).nullable(),
81
+ });
82
+
83
+ // ─── Envelope schema ─────────────────────────────────────────────────────────
84
+
85
+ /**
86
+ * Top-level SOT JSON envelope. One envelope per (domain, version) pair.
87
+ *
88
+ * `levels` is a positional map from level number (`"0"`, `"1"`, …) to a human
89
+ * label describing the level. Missingness entries are embedded in `entries`
90
+ * (per-domain) rather than merged in from a shared SOT file; see module
91
+ * header for the v2 format summary.
92
+ */
93
+ export const CvcEnvelopeSchema = z.object({
94
+ domain: z.string().min(1),
95
+ name: z.string().min(1),
96
+ version: z.string().min(1),
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_state"`,
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
+ * - Hierarchy segments 2..7 all zero → level 0 (per-domain missingness root,
126
+ * e.g. `022-000-000-000-000-000-000`). Segment 1 carries the domain prefix
127
+ * and is intentionally not consulted by the level derivation.
128
+ */
129
+ export function getCvcLevel(code: string): number {
130
+ const segments = code.split("-");
131
+ // segments[6] is the missingness slot (positional segment 7).
132
+ if (segments[6] !== "000") return 0;
133
+ // Walk hierarchy segments 6..2 (indices 5..1) looking for the deepest
134
+ // populated level.
135
+ for (let i = 5; i >= 1; i -= 1) {
136
+ if (segments[i] !== "000") return i;
137
+ }
138
+ return 0;
139
+ }
140
+
141
+ /**
142
+ * Error collected by {@link validateCvc}. Each error names the invariant it
143
+ * violates (`C1`..`C8`, skipping the retired `C7`) so CI output points
144
+ * straight at the locked spec rule that failed. `code` or `key` narrow the
145
+ * error to a specific entry when the violation is entry-scoped.
146
+ */
147
+ export interface CvcValidationError {
148
+ invariant: "C1" | "C2" | "C3" | "C4" | "C5" | "C6" | "C8";
149
+ message: string;
150
+ code?: string;
151
+ key?: string;
152
+ }
153
+
154
+ /**
155
+ * Structural invariants to enforce on every committed SOT file per locked spec
156
+ * §4. Zod's schema `parse()` guarantees the *shape* of the envelope; this
157
+ * function enforces the cross-entry *semantics* that Zod cannot express.
158
+ *
159
+ * Invariants (locked spec §4):
160
+ * - **C1** Code format + uniqueness (§4.1). Format v2 uses 3-digit segments.
161
+ * - **C2** Key format + uniqueness (§4.2).
162
+ * - **C3** Tree: every `parentCode` resolves to an existing entry or null; no
163
+ * cycles (§4.3).
164
+ * - **C4** `childCodes` are the exact bidirectional inverse of `parentCode`
165
+ * (§4.3).
166
+ * - **C5** Selectability is a boolean (§4.4).
167
+ * - **C6** Cross-CVC `relevantMechanisms` references resolve against a
168
+ * provided `service_mechanisms` key set (§4.5, §7). Only checked when the
169
+ * caller supplies `options.mechanismKeys`.
170
+ * - **C7** _Retired in format v2_ (envelope no longer carries the shared
171
+ * `missingness` field; missingness is per-domain and embedded in
172
+ * `entries`). The invariant slot is intentionally left empty to preserve
173
+ * the numbering of C1/C2/C3/C4/C5/C6/C8 in historical references.
174
+ * - **C8** No entry anywhere contains a key `'provided'` (legacy Thread UI
175
+ * label guard; not a canonical state).
176
+ *
177
+ * @param envelope Parsed envelope (typically from `CvcEnvelopeSchema.parse()`).
178
+ * @param options.mechanismKeys Optional set of valid `service_mechanisms`
179
+ * entry keys. If provided and the envelope entries have `relevantMechanisms`
180
+ * fields, each referenced key must be in this set (C6).
181
+ * @returns An array of {@link CvcValidationError}. An empty array means valid.
182
+ */
183
+ export function validateCvc(
184
+ envelope: CvcEnvelope,
185
+ options: { mechanismKeys?: ReadonlySet<string> } = {},
186
+ ): CvcValidationError[] {
187
+ const errors: CvcValidationError[] = [];
188
+ const { entries } = envelope;
189
+
190
+ // ── C1: code format + uniqueness ──────────────────────────────────────────
191
+ const codeRe = /^\d{3}(-\d{3}){6}$/;
192
+ const seenCodes = new Set<string>();
193
+ for (const entry of entries) {
194
+ if (!codeRe.test(entry.code)) {
195
+ errors.push({
196
+ invariant: "C1",
197
+ message: `code does not match /^\\d{3}(-\\d{3}){6}$/`,
198
+ code: entry.code,
199
+ key: entry.key,
200
+ });
201
+ }
202
+ if (seenCodes.has(entry.code)) {
203
+ errors.push({
204
+ invariant: "C1",
205
+ message: `duplicate code`,
206
+ code: entry.code,
207
+ key: entry.key,
208
+ });
209
+ }
210
+ seenCodes.add(entry.code);
211
+ }
212
+
213
+ // ── C2: key format + uniqueness ───────────────────────────────────────────
214
+ const keyRe = /^[a-z][a-z0-9_]*$/;
215
+ const seenKeys = new Set<string>();
216
+ for (const entry of entries) {
217
+ if (!keyRe.test(entry.key)) {
218
+ errors.push({
219
+ invariant: "C2",
220
+ message: `key does not match /^[a-z][a-z0-9_]*$/`,
221
+ code: entry.code,
222
+ key: entry.key,
223
+ });
224
+ }
225
+ if (seenKeys.has(entry.key)) {
226
+ errors.push({
227
+ invariant: "C2",
228
+ message: `duplicate key`,
229
+ code: entry.code,
230
+ key: entry.key,
231
+ });
232
+ }
233
+ seenKeys.add(entry.key);
234
+ }
235
+
236
+ // Build a lookup by code for the remaining tree checks. Skip entries whose
237
+ // code we already know is malformed — their index would be meaningless.
238
+ const byCode = new Map<string, CvcEntry>();
239
+ for (const entry of entries) {
240
+ if (codeRe.test(entry.code)) byCode.set(entry.code, entry);
241
+ }
242
+
243
+ // ── C3: tree — parents resolve, no cycles ─────────────────────────────────
244
+ for (const entry of entries) {
245
+ if (entry.parentCode === null) continue;
246
+ if (!byCode.has(entry.parentCode)) {
247
+ errors.push({
248
+ invariant: "C3",
249
+ message: `parentCode ${entry.parentCode} does not resolve to any entry in this CVC`,
250
+ code: entry.code,
251
+ key: entry.key,
252
+ });
253
+ }
254
+ }
255
+
256
+ // Cycle detection: walk parent chain from each entry, bail if we revisit.
257
+ for (const entry of entries) {
258
+ const visited = new Set<string>();
259
+ let cursor: CvcEntry | undefined = entry;
260
+ while (cursor && cursor.parentCode !== null) {
261
+ if (visited.has(cursor.code)) {
262
+ errors.push({
263
+ invariant: "C3",
264
+ message: `cycle detected in parentCode chain starting from ${entry.code}`,
265
+ code: entry.code,
266
+ key: entry.key,
267
+ });
268
+ break;
269
+ }
270
+ visited.add(cursor.code);
271
+ cursor = byCode.get(cursor.parentCode);
272
+ }
273
+ }
274
+
275
+ // ── C4: childCodes are exact inverse of parentCode ────────────────────────
276
+ // Build the set of (parent, child) edges from parentCode, then from
277
+ // childCodes, and require they match exactly.
278
+ const parentToChildrenFromParent = new Map<string, Set<string>>();
279
+ for (const entry of entries) {
280
+ if (entry.parentCode !== null) {
281
+ let set = parentToChildrenFromParent.get(entry.parentCode);
282
+ if (!set) {
283
+ set = new Set();
284
+ parentToChildrenFromParent.set(entry.parentCode, set);
285
+ }
286
+ set.add(entry.code);
287
+ }
288
+ }
289
+
290
+ for (const entry of entries) {
291
+ const declared = new Set(entry.childCodes);
292
+ const derived = parentToChildrenFromParent.get(entry.code) ?? new Set();
293
+
294
+ for (const child of declared) {
295
+ if (!derived.has(child)) {
296
+ errors.push({
297
+ invariant: "C4",
298
+ message: `entry lists ${child} in childCodes but that entry's parentCode is not ${entry.code}`,
299
+ code: entry.code,
300
+ key: entry.key,
301
+ });
302
+ }
303
+ }
304
+ for (const child of derived) {
305
+ if (!declared.has(child)) {
306
+ errors.push({
307
+ invariant: "C4",
308
+ message: `entry ${child} has parentCode ${entry.code} but is missing from its childCodes`,
309
+ code: entry.code,
310
+ key: entry.key,
311
+ });
312
+ }
313
+ }
314
+ }
315
+
316
+ // ── C5: selectability per §4.4 ────────────────────────────────────────────
317
+ // Zod already enforces `selectable: boolean`; we make the invariant explicit
318
+ // at validator level so a future schema loosening cannot silently bypass it.
319
+ for (const entry of entries) {
320
+ if (typeof entry.selectable !== "boolean") {
321
+ errors.push({
322
+ invariant: "C5",
323
+ message: `selectable must be a boolean, got ${typeof entry.selectable}`,
324
+ code: entry.code,
325
+ key: entry.key,
326
+ });
327
+ }
328
+ }
329
+
330
+ // ── C6: cross-CVC refs — `relevantMechanisms` resolves against provided set
331
+ if (options.mechanismKeys) {
332
+ for (const entry of entries) {
333
+ const raw = (entry as unknown as Record<string, unknown>)[
334
+ "relevantMechanisms"
335
+ ];
336
+ if (raw === undefined || raw === null) continue;
337
+ if (!Array.isArray(raw)) {
338
+ errors.push({
339
+ invariant: "C6",
340
+ message: `relevantMechanisms must be an array or null`,
341
+ code: entry.code,
342
+ key: entry.key,
343
+ });
344
+ continue;
345
+ }
346
+ for (const mechKey of raw) {
347
+ if (typeof mechKey !== "string" || !options.mechanismKeys.has(mechKey)) {
348
+ errors.push({
349
+ invariant: "C6",
350
+ message: `relevantMechanisms references unknown service_mechanisms key: ${String(mechKey)}`,
351
+ code: entry.code,
352
+ key: entry.key,
353
+ });
354
+ }
355
+ }
356
+ }
357
+ }
358
+
359
+ // ── C8: legacy `'provided'` key guard ─────────────────────────────────────
360
+ // Walk every property of every entry (including nested arrays) looking for
361
+ // a key named `'provided'`. It is a Thread UI label, not a canonical state.
362
+ const walkForProvided = (value: unknown, entry: CvcEntry): void => {
363
+ if (value === null || value === undefined) return;
364
+ if (Array.isArray(value)) {
365
+ for (const item of value) walkForProvided(item, entry);
366
+ return;
367
+ }
368
+ if (typeof value === "object") {
369
+ for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
370
+ if (k === "provided") {
371
+ errors.push({
372
+ invariant: "C8",
373
+ message: `entry contains forbidden legacy key 'provided' (see locked spec §4)`,
374
+ code: entry.code,
375
+ key: entry.key,
376
+ });
377
+ }
378
+ walkForProvided(v, entry);
379
+ }
380
+ }
381
+ };
382
+ for (const entry of entries) {
383
+ walkForProvided(entry, entry);
384
+ // Also guard against a literal string value of 'provided' appearing as an
385
+ // entry's `key`, which would be an obvious smuggling attempt.
386
+ if (entry.key === "provided") {
387
+ errors.push({
388
+ invariant: "C8",
389
+ message: `entry key must not be the legacy label 'provided'`,
390
+ code: entry.code,
391
+ key: entry.key,
392
+ });
393
+ }
394
+ }
395
+
396
+ return errors;
397
+ }
@@ -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";