@htilabs/platform-common-models 0.8.13 → 0.8.14

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 (72) hide show
  1. package/README.md +44 -0
  2. package/dist/config/index.cjs +4 -0
  3. package/dist/config/index.cjs.map +1 -1
  4. package/dist/config/index.d.cts +16 -1
  5. package/dist/config/index.d.ts +16 -1
  6. package/dist/config/index.js +2 -0
  7. package/dist/config/index.js.map +1 -1
  8. package/dist/constants/index.cjs +10 -0
  9. package/dist/constants/index.cjs.map +1 -1
  10. package/dist/constants/index.d.cts +1 -1
  11. package/dist/constants/index.d.ts +1 -1
  12. package/dist/constants/index.js +10 -0
  13. package/dist/constants/index.js.map +1 -1
  14. package/dist/cvcs/index.cjs +505 -2
  15. package/dist/cvcs/index.cjs.map +1 -1
  16. package/dist/cvcs/index.d.cts +2642 -2084
  17. package/dist/cvcs/index.d.ts +2642 -2084
  18. package/dist/cvcs/index.js +500 -2
  19. package/dist/cvcs/index.js.map +1 -1
  20. package/dist/{index-I-DiX9eQ.d.ts → index-CDoqrfc1.d.ts} +1 -1
  21. package/dist/{index-CoVr1jIV.d.cts → index-Zu_mOJRn.d.cts} +1 -1
  22. package/dist/index.cjs +582 -4
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +111 -7
  25. package/dist/index.d.ts +111 -7
  26. package/dist/index.js +571 -4
  27. package/dist/index.js.map +1 -1
  28. package/dist/models/index.d.cts +2 -2
  29. package/dist/models/index.d.ts +2 -2
  30. package/dist/mongo/index.cjs +383 -0
  31. package/dist/mongo/index.cjs.map +1 -0
  32. package/dist/mongo/index.d.cts +221 -0
  33. package/dist/mongo/index.d.ts +221 -0
  34. package/dist/mongo/index.js +351 -0
  35. package/dist/mongo/index.js.map +1 -0
  36. package/dist/{platform-auth-BfCMuAlC.d.cts → platform-auth-AsfnIXfK.d.cts} +2 -2
  37. package/dist/{platform-auth-BfCMuAlC.d.ts → platform-auth-AsfnIXfK.d.ts} +2 -2
  38. package/dist/schemas/index.cjs +5 -1
  39. package/dist/schemas/index.cjs.map +1 -1
  40. package/dist/schemas/index.d.cts +29 -25
  41. package/dist/schemas/index.d.ts +29 -25
  42. package/dist/schemas/index.js +5 -1
  43. package/dist/schemas/index.js.map +1 -1
  44. package/dist/types/index.d.cts +2 -2
  45. package/dist/types/index.d.ts +2 -2
  46. package/package.json +10 -1
  47. package/src/__sot__/coreIndicators.pin.json +6 -1
  48. package/src/__tests__/__snapshots__/cvc-sot.snap +18 -2
  49. package/src/__tests__/cvc-136-scoring-invariant.test.ts +6 -3
  50. package/src/__tests__/cvc-drift-gate.test.ts +14 -3
  51. package/src/__tests__/cvc-sot-snapshot.test.ts +13 -1
  52. package/src/__tests__/cvc-structural.test.ts +6 -0
  53. package/src/__tests__/mongo-verifier.test.ts +502 -0
  54. package/src/config/index.ts +8 -2
  55. package/src/constants/ic.ts +31 -2
  56. package/src/cvcs/assertionStatus.v1.0.0.json +80 -0
  57. package/src/cvcs/coreIndicators.v1.0.0.json +67 -2
  58. package/src/cvcs/createdBySystem.v1.0.0.json +89 -0
  59. package/src/cvcs/hmisSex.v1.0.0.json +89 -0
  60. package/src/cvcs/index.ts +18 -0
  61. package/src/cvcs/minorAdultStatus.v1.0.0.json +80 -0
  62. package/src/cvcs/subjectType.v1.0.0.json +80 -0
  63. package/src/generated/cvc-enums.ts +76 -2
  64. package/src/index.ts +20 -0
  65. package/src/mongo/catalog.ts +65 -0
  66. package/src/mongo/contract.ts +157 -0
  67. package/src/mongo/index.ts +343 -0
  68. package/src/mongo/similarity.ts +133 -0
  69. package/src/mongo/uri.ts +53 -0
  70. package/src/schemas/common.ts +4 -0
  71. package/dist/{cvcEntry-BCj1OWqL.d.cts → cvcEntry-0BIB9sen.d.cts} +8 -8
  72. package/dist/{cvcEntry-BCj1OWqL.d.ts → cvcEntry-0BIB9sen.d.ts} +8 -8
@@ -0,0 +1,502 @@
1
+ /**
2
+ * MongoDB connection/collection verifier — unit tests
3
+ *
4
+ * Covers:
5
+ * - env-affinity shape rule (no connection required)
6
+ * - typo vs unseeded severity split
7
+ * - the ordinal-sibling guard (leads-platform-demo2, cypress-tests-3)
8
+ * - lazy-creation semantics (declared collection with no documents)
9
+ * - undeclared collections reported, never fatal
10
+ * - db name embedded in the connection string (auth's shape)
11
+ * - multi-error aggregation, exit(1) vs throwOnFailure
12
+ * - the READ-ONLY guarantee: only listDatabases/listCollections are called
13
+ *
14
+ * Tests inject a fake catalogue, matching how runCvcBootCheck injects exit and
15
+ * logger. The package's test suite stays free of a real MongoDB.
16
+ *
17
+ * NOTE: because the catalogue is faked, these tests cannot prove that the real
18
+ * driver reports a documents-free collection as absent. That premise was
19
+ * verified once, read-only, against the live cluster: thread registers the
20
+ * Mongoose model `AgencyInfo` (collection `agencyinfos`), which exists in
21
+ * neither platform-test nor platform-dev. See co-9mk.
22
+ */
23
+
24
+ import { writeFileSync, unlinkSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { tmpdir } from "node:os";
27
+
28
+ import { describe, it, expect, vi } from "vitest";
29
+
30
+ import { verifyMongo, type MongoCatalog } from "../mongo/index.js";
31
+ import {
32
+ editDistance,
33
+ isOrdinalSibling,
34
+ nearestNames,
35
+ formatSuggestions,
36
+ } from "../mongo/similarity.js";
37
+ import { parseMongoBlock, checkEnvAffinity } from "../mongo/contract.js";
38
+
39
+ // ─── helpers ─────────────────────────────────────────────────────────────────
40
+
41
+ /** A catalogue backed by a plain object, recording every call it receives. */
42
+ function fakeCatalog(shape: Record<string, string[]>): MongoCatalog & {
43
+ calls: string[];
44
+ } {
45
+ const calls: string[] = [];
46
+ return {
47
+ calls,
48
+ async listDatabases() {
49
+ calls.push("listDatabases");
50
+ return Object.keys(shape);
51
+ },
52
+ async listCollections(database: string) {
53
+ calls.push(`listCollections:${database}`);
54
+ return shape[database] ?? [];
55
+ },
56
+ };
57
+ }
58
+
59
+ function writeContract(body: string, variables = "variables: {}"): string {
60
+ const path = join(tmpdir(), `mongo-contract-${Math.random().toString(36).slice(2)}.yaml`);
61
+ writeFileSync(
62
+ path,
63
+ `service: test-svc\nversion: 1\nenvironments: [local, test, dev, prod]\n${variables}\n${body}`,
64
+ "utf8",
65
+ );
66
+ return path;
67
+ }
68
+
69
+ const BASIC_CONTRACT = `mongo:
70
+ env_affinity:
71
+ test: "-test"
72
+ databases:
73
+ - db_var: THREAD_DB
74
+ uri_var: MONGODB_CLUSTER
75
+ collections: [caserecords, households]
76
+ `;
77
+
78
+ async function run(
79
+ contractBody: string,
80
+ env: NodeJS.ProcessEnv,
81
+ catalog: MongoCatalog,
82
+ envName = "local",
83
+ ) {
84
+ const path = writeContract(contractBody);
85
+ try {
86
+ return await verifyMongo(path, {
87
+ catalog,
88
+ env: envName,
89
+ processEnv: env,
90
+ throwOnFailure: true,
91
+ logger: { error: vi.fn(), warn: vi.fn() },
92
+ });
93
+ } finally {
94
+ unlinkSync(path);
95
+ }
96
+ }
97
+
98
+ // ─── similarity primitives ───────────────────────────────────────────────────
99
+
100
+ describe("editDistance", () => {
101
+ it("returns 0 for identical strings", () => {
102
+ expect(editDistance("thread-test", "thread-test")).toBe(0);
103
+ });
104
+
105
+ it("counts a single substitution", () => {
106
+ expect(editDistance("thread-tst", "thread-test")).toBe(1);
107
+ });
108
+
109
+ it("bails out early beyond the bound", () => {
110
+ // Bounded result only needs to exceed max, not be exact.
111
+ expect(editDistance("thread-pr-4821", "platform-prod", 2)).toBeGreaterThan(2);
112
+ });
113
+
114
+ it("scores an adjacent transposition as ONE edit", () => {
115
+ // platform-dve is a transposition of platform-dev. Plain Levenshtein would
116
+ // score 2 and tie with the production name platform-db.
117
+ expect(editDistance("platform-dve", "platform-dev")).toBe(1);
118
+ expect(editDistance("platform-dve", "platform-db")).toBe(2);
119
+ });
120
+ });
121
+
122
+ describe("formatSuggestions", () => {
123
+ it("renders one, two, and three names", () => {
124
+ expect(formatSuggestions(["a"])).toBe('"a"');
125
+ expect(formatSuggestions(["a", "b"])).toBe('"a" or "b"');
126
+ expect(formatSuggestions(["a", "b", "c"])).toBe('"a", "b" or "c"');
127
+ });
128
+ });
129
+
130
+ describe("isOrdinalSibling", () => {
131
+ it("treats leads-platform-demo and demo2 as siblings", () => {
132
+ expect(isOrdinalSibling("leads-platform-demo3", "leads-platform-demo2")).toBe(true);
133
+ expect(isOrdinalSibling("leads-platform-demo", "leads-platform-demo2")).toBe(true);
134
+ });
135
+
136
+ it("treats cypress-tests-4 and cypress-tests-3 as siblings", () => {
137
+ expect(isOrdinalSibling("cypress-tests-4", "cypress-tests-3")).toBe(true);
138
+ });
139
+
140
+ it("does NOT treat a real typo as a sibling", () => {
141
+ expect(isOrdinalSibling("thread-tst", "thread-test")).toBe(false);
142
+ });
143
+
144
+ it("is false for identical names", () => {
145
+ expect(isOrdinalSibling("thread-test", "thread-test")).toBe(false);
146
+ });
147
+ });
148
+
149
+ describe("nearestNames", () => {
150
+ it("finds a one-edit typo", () => {
151
+ expect(nearestNames("thread-tst", ["thread-test", "thread-dev"])).toEqual([
152
+ "thread-test",
153
+ ]);
154
+ });
155
+
156
+ it("returns empty when nothing is close", () => {
157
+ expect(nearestNames("thread-pr-4821", ["thread-test", "platform-dev"])).toEqual([]);
158
+ });
159
+
160
+ it("EXCLUDES ordinal siblings so a new numbered env is never a typo", () => {
161
+ // The guard that keeps a healthy new environment from being grounded.
162
+ expect(nearestNames("leads-platform-demo3", ["leads-platform-demo2"])).toEqual([]);
163
+ expect(nearestNames("cypress-tests-4", ["cypress-tests-3", "cypress-tests-2"])).toEqual([]);
164
+ });
165
+
166
+ it("returns ALL tied candidates rather than guessing", () => {
167
+ // thread-dv is one edit from both thread-dev and the PRODUCTION thread-db.
168
+ // Picking one by iteration order could steer an operator into production.
169
+ expect(nearestNames("thread-dv", ["thread-db", "thread-dev", "thread-test"])).toEqual([
170
+ "thread-db",
171
+ "thread-dev",
172
+ ]);
173
+ });
174
+
175
+ it("prefers the transposed neighbour over an unrelated production name", () => {
176
+ // platform-dve -> platform-dev (transposition, 1) beats platform-db (2).
177
+ expect(nearestNames("platform-dve", ["platform-db", "platform-dev"])).toEqual([
178
+ "platform-dev",
179
+ ]);
180
+ });
181
+ });
182
+
183
+ // ─── contract parsing + env affinity ─────────────────────────────────────────
184
+
185
+ describe("parseMongoBlock", () => {
186
+ it("returns null when no mongo block is declared", () => {
187
+ expect(parseMongoBlock(undefined, "x.yaml")).toBeNull();
188
+ });
189
+
190
+ it("rejects an empty databases list", () => {
191
+ expect(() => parseMongoBlock({ databases: [] }, "x.yaml")).toThrow(/non-empty list/);
192
+ });
193
+
194
+ it("rejects a database missing db_var", () => {
195
+ expect(() =>
196
+ parseMongoBlock({ databases: [{ uri_var: "U", collections: [] }] }, "x.yaml"),
197
+ ).toThrow(/db_var/);
198
+ });
199
+ });
200
+
201
+ describe("checkEnvAffinity", () => {
202
+ it("passes when the suffix matches", () => {
203
+ expect(checkEnvAffinity("thread-test", "THREAD_DB", "test", { test: "-test" })).toBeNull();
204
+ });
205
+
206
+ it("fails a prod-shaped name in a test environment", () => {
207
+ const msg = checkEnvAffinity("platform-db", "PLATFORM_DB", "test", { test: "-test" });
208
+ expect(msg).toContain('must end with "-test"');
209
+ });
210
+
211
+ it("is inert for environments with no declared affinity", () => {
212
+ expect(checkEnvAffinity("anything", "X", "local", { test: "-test" })).toBeNull();
213
+ });
214
+ });
215
+
216
+ // ─── verifyMongo ─────────────────────────────────────────────────────────────
217
+
218
+ describe("verifyMongo", () => {
219
+ it("passes when every database and collection exists", async () => {
220
+ const catalog = fakeCatalog({ "thread-test": ["caserecords", "households"] });
221
+ const report = await run(BASIC_CONTRACT, { THREAD_DB: "thread-test" }, catalog);
222
+ expect(report.ok).toBe(true);
223
+ expect(report.findings).toEqual([]);
224
+ });
225
+
226
+ it("is a no-op success when the contract declares no mongo block", async () => {
227
+ const catalog = fakeCatalog({});
228
+ const report = await run("", {}, catalog);
229
+ expect(report.ok).toBe(true);
230
+ expect(catalog.calls).toEqual([]);
231
+ });
232
+
233
+ it("FATAL: database absent with a near neighbour is a typo", async () => {
234
+ const catalog = fakeCatalog({ "thread-test": ["caserecords", "households"] });
235
+ await expect(
236
+ run(BASIC_CONTRACT, { THREAD_DB: "thread-tst" }, catalog),
237
+ ).rejects.toThrow(/does not exist\. Did you mean "thread-test"\?/);
238
+ });
239
+
240
+ it("WARN: database absent with no neighbour is an unseeded environment", async () => {
241
+ const catalog = fakeCatalog({ "thread-test": ["caserecords"] });
242
+ const report = await run(BASIC_CONTRACT, { THREAD_DB: "thread-pr-4821" }, catalog);
243
+ expect(report.ok).toBe(true);
244
+ expect(report.findings).toHaveLength(1);
245
+ expect(report.findings[0]).toMatchObject({
246
+ severity: "warn",
247
+ kind: "db_absent_unseeded",
248
+ });
249
+ });
250
+
251
+ it("WARN (not fatal): a legitimately-numbered new environment boots", async () => {
252
+ // The regression guard. demo3 is one edit from demo2 -- must NOT be fatal.
253
+ const contract = `mongo:
254
+ databases:
255
+ - db_var: LEADS_DB
256
+ uri_var: MONGO_LEADS_URI
257
+ collections: [leads]
258
+ `;
259
+ const catalog = fakeCatalog({ "leads-platform-demo2": ["leads"] });
260
+ const report = await run(contract, { LEADS_DB: "leads-platform-demo3" }, catalog);
261
+ expect(report.ok).toBe(true);
262
+ expect(report.findings[0].kind).toBe("db_absent_unseeded");
263
+ });
264
+
265
+ it("FATAL: env-affinity violation, without probing the database", async () => {
266
+ const catalog = fakeCatalog({ "platform-db": ["users"] });
267
+ await expect(
268
+ run(BASIC_CONTRACT, { THREAD_DB: "platform-db" }, catalog, "test"),
269
+ ).rejects.toThrow(/must end with "-test"/);
270
+ // Shape violations short-circuit: the database is never inspected.
271
+ expect(catalog.calls).not.toContain("listCollections:platform-db");
272
+ });
273
+
274
+ it("WARN: declared collection with no documents (lazy creation)", async () => {
275
+ // thread's `agencyinfos`: model registered, collection never created.
276
+ const contract = `mongo:
277
+ databases:
278
+ - db_var: PLATFORM_DB
279
+ uri_var: MONGODB_CLUSTER
280
+ collections: [users, agencyinfos]
281
+ `;
282
+ const catalog = fakeCatalog({ "platform-test": ["users"] });
283
+ const report = await run(contract, { PLATFORM_DB: "platform-test" }, catalog);
284
+ expect(report.ok).toBe(true);
285
+ expect(report.findings).toHaveLength(1);
286
+ expect(report.findings[0]).toMatchObject({
287
+ severity: "warn",
288
+ kind: "collection_absent_unseeded",
289
+ collection: "agencyinfos",
290
+ });
291
+ });
292
+
293
+ it("FATAL: declared collection that is a typo of an existing one", async () => {
294
+ const contract = `mongo:
295
+ databases:
296
+ - db_var: THREAD_DB
297
+ uri_var: MONGODB_CLUSTER
298
+ collections: [caserecord]
299
+ `;
300
+ const catalog = fakeCatalog({ "thread-test": ["caserecords"] });
301
+ await expect(
302
+ run(contract, { THREAD_DB: "thread-test" }, catalog),
303
+ ).rejects.toThrow(/"caserecord" does not exist\. Did you mean "caserecords"\?/);
304
+ });
305
+
306
+ it("WARN: collections present in Mongo but undeclared", async () => {
307
+ const catalog = fakeCatalog({
308
+ "thread-test": ["caserecords", "households", "counters"],
309
+ });
310
+ const report = await run(BASIC_CONTRACT, { THREAD_DB: "thread-test" }, catalog);
311
+ expect(report.ok).toBe(true);
312
+ expect(report.findings).toHaveLength(1);
313
+ expect(report.findings[0]).toMatchObject({
314
+ kind: "collection_undeclared",
315
+ collection: "counters",
316
+ });
317
+ });
318
+
319
+ it("an empty collections list checks the database NAME only", async () => {
320
+ // Incremental adoption: expansion reaches the leads databases but cannot
321
+ // practically enumerate their collections. listCollections must not run.
322
+ const contract = `mongo:
323
+ databases:
324
+ - db_var: LEADS_DB
325
+ uri_var: MONGO_LEADS_URI
326
+ collections: []
327
+ `;
328
+ const catalog = fakeCatalog({ "leads-platform": ["leads", "dataaccessrules"] });
329
+ const report = await run(contract, { LEADS_DB: "leads-platform" }, catalog);
330
+ expect(report.ok).toBe(true);
331
+ expect(report.findings).toEqual([]);
332
+ expect(catalog.calls).toEqual(["listDatabases"]);
333
+ });
334
+
335
+ it("an empty collections list still catches a database typo", async () => {
336
+ const contract = `mongo:
337
+ databases:
338
+ - db_var: LEADS_DB
339
+ uri_var: MONGO_LEADS_URI
340
+ collections: []
341
+ `;
342
+ const catalog = fakeCatalog({ "leads-platform": [] });
343
+ await expect(
344
+ run(contract, { LEADS_DB: "leads-platfrom" }, catalog),
345
+ ).rejects.toThrow(/Did you mean "leads-platform"\?/);
346
+ });
347
+
348
+ it("FATAL: required db_var missing from the environment", async () => {
349
+ const catalog = fakeCatalog({ "thread-test": [] });
350
+ await expect(run(BASIC_CONTRACT, {}, catalog)).rejects.toThrow(
351
+ /THREAD_DB: required by mongo contract but not set/,
352
+ );
353
+ });
354
+
355
+ it("SKIPS an optional database that is not configured", async () => {
356
+ // thread's PAVE_DB is `required: false`; its absence must not fail boot.
357
+ const variables = [
358
+ "variables:",
359
+ " PAVE_DB:",
360
+ " type: string",
361
+ " required: false",
362
+ " secret: false",
363
+ " description: optional pave db",
364
+ ].join("\n");
365
+ const contract = `mongo:
366
+ databases:
367
+ - db_var: PAVE_DB
368
+ uri_var: MONGODB_CLUSTER
369
+ collections: [agencies]
370
+ `;
371
+ const catalog = fakeCatalog({ "pave-test": ["agencies"] });
372
+ const path = writeContract(contract, variables);
373
+ try {
374
+ const report = await verifyMongo(path, {
375
+ catalog,
376
+ env: "local",
377
+ processEnv: {},
378
+ throwOnFailure: true,
379
+ logger: { error: vi.fn(), warn: vi.fn() },
380
+ });
381
+ expect(report.ok).toBe(true);
382
+ expect(report.findings).toEqual([]);
383
+ // Nothing was configured, so nothing was probed.
384
+ expect(catalog.calls).toEqual([]);
385
+ } finally {
386
+ unlinkSync(path);
387
+ }
388
+ });
389
+
390
+ it("applies the contract's per-environment default", async () => {
391
+ // thread declares PLATFORM_DB.default.prod: platform-prod. Reading
392
+ // process.env alone would miss it and report a false fatal.
393
+ const variables = [
394
+ "variables:",
395
+ " PLATFORM_DB:",
396
+ " type: string",
397
+ " required: true",
398
+ " secret: false",
399
+ " description: platform db",
400
+ " default:",
401
+ " prod: platform-prod",
402
+ ].join("\n");
403
+ const contract = `mongo:
404
+ databases:
405
+ - db_var: PLATFORM_DB
406
+ uri_var: MONGODB_CLUSTER
407
+ collections: [users]
408
+ `;
409
+ const catalog = fakeCatalog({ "platform-prod": ["users"] });
410
+ const path = writeContract(contract, variables);
411
+ try {
412
+ const report = await verifyMongo(path, {
413
+ catalog,
414
+ env: "prod",
415
+ processEnv: {}, // deliberately empty: the default must supply the name
416
+ throwOnFailure: true,
417
+ logger: { error: vi.fn(), warn: vi.fn() },
418
+ });
419
+ expect(report.ok).toBe(true);
420
+ expect(catalog.calls).toContain("listCollections:platform-prod");
421
+ } finally {
422
+ unlinkSync(path);
423
+ }
424
+ });
425
+
426
+ it("parses the database name out of the URI when db_var === uri_var", async () => {
427
+ // auth's shape: LEADS_MONGODB_URI embeds the database name.
428
+ const contract = `mongo:
429
+ databases:
430
+ - db_var: LEADS_MONGODB_URI
431
+ uri_var: LEADS_MONGODB_URI
432
+ collections: [leads]
433
+ `;
434
+ const catalog = fakeCatalog({ "leads-platform-test": ["leads"] });
435
+ const report = await run(
436
+ contract,
437
+ { LEADS_MONGODB_URI: "mongodb+srv://u:p@c.mongodb.net/leads-platform-test?w=1" },
438
+ catalog,
439
+ );
440
+ expect(report.ok).toBe(true);
441
+ });
442
+
443
+ it("FATAL: db_var === uri_var but the URI carries no database name", async () => {
444
+ const contract = `mongo:
445
+ databases:
446
+ - db_var: LEADS_MONGODB_URI
447
+ uri_var: LEADS_MONGODB_URI
448
+ collections: [leads]
449
+ `;
450
+ const catalog = fakeCatalog({});
451
+ await expect(
452
+ run(contract, { LEADS_MONGODB_URI: "mongodb://localhost:27017" }, catalog),
453
+ ).rejects.toThrow(/carries no database name/);
454
+ });
455
+
456
+ it("aggregates every fatal finding before failing", async () => {
457
+ const contract = `mongo:
458
+ databases:
459
+ - db_var: A_DB
460
+ uri_var: U
461
+ collections: []
462
+ - db_var: B_DB
463
+ uri_var: U
464
+ collections: []
465
+ `;
466
+ const catalog = fakeCatalog({ "a-test": [] });
467
+ await expect(run(contract, {}, catalog)).rejects.toThrow(
468
+ /2 fatal finding\(s\)[\s\S]*A_DB[\s\S]*B_DB/,
469
+ );
470
+ });
471
+
472
+ it("calls exit(1) rather than throwing when throwOnFailure is unset", async () => {
473
+ const catalog = fakeCatalog({ "thread-test": [] });
474
+ const exit = vi.fn() as unknown as (code: number) => never;
475
+ const logger = { error: vi.fn(), warn: vi.fn() };
476
+ const path = writeContract(BASIC_CONTRACT);
477
+ try {
478
+ await verifyMongo(path, {
479
+ catalog,
480
+ env: "local",
481
+ processEnv: { THREAD_DB: "thread-tst" },
482
+ exit,
483
+ logger,
484
+ });
485
+ } finally {
486
+ unlinkSync(path);
487
+ }
488
+ expect(exit).toHaveBeenCalledWith(1);
489
+ expect(logger.error).toHaveBeenCalledOnce();
490
+ });
491
+
492
+ it("READ-ONLY: issues only listDatabases and listCollections", async () => {
493
+ const catalog = fakeCatalog({ "thread-test": ["caserecords", "households"] });
494
+ await run(BASIC_CONTRACT, { THREAD_DB: "thread-test" }, catalog);
495
+ expect(catalog.calls).toEqual(["listDatabases", "listCollections:thread-test"]);
496
+ // The MongoCatalog interface exposes no write operation at all.
497
+ expect(Object.keys(catalog).filter((k) => k !== "calls").sort()).toEqual([
498
+ "listCollections",
499
+ "listDatabases",
500
+ ]);
501
+ });
502
+ });
@@ -43,6 +43,12 @@ export interface ServiceContract {
43
43
  port?: number;
44
44
  build_secrets?: string[];
45
45
  variables: Record<string, VariableSpec>;
46
+ /**
47
+ * Optional MongoDB declaration consumed by `@htilabs/platform-common-models/mongo`.
48
+ * Left untyped here to keep `config` free of a dependency on `mongo`; the
49
+ * verifier validates its shape via `parseMongoBlock`.
50
+ */
51
+ mongo?: unknown;
46
52
  }
47
53
 
48
54
  /** Typed config accessor returned by validateAgainstContract. */
@@ -80,7 +86,7 @@ export type RouteHandler = (
80
86
 
81
87
  // ─── YAML parser ──────────────────────────────────────────────────────────────
82
88
 
83
- function loadContract(runtimeYamlPath: string): ServiceContract {
89
+ export function loadContract(runtimeYamlPath: string): ServiceContract {
84
90
  let raw: string;
85
91
  try {
86
92
  raw = readFileSync(runtimeYamlPath, "utf8");
@@ -172,7 +178,7 @@ function coerce(
172
178
  * Exact env match only — defaults are per-environment and MUST NOT bleed
173
179
  * across envs. (A local default stays local; it does not fall back into prod.)
174
180
  */
175
- function resolveDefault(
181
+ export function resolveDefault(
176
182
  spec: VariableSpec,
177
183
  env: string,
178
184
  ): string | undefined {
@@ -5245,10 +5245,10 @@ export const CVC_136_OPTIONS: readonly CVC136Option[] = Object.entries(
5245
5245
  categoryLabel: CVC_136_CATEGORY_LABELS[category],
5246
5246
  }));
5247
5247
 
5248
- // ─── CVC-136: full core-indicators value set (CANONICAL, 210 codes) ─────
5248
+ // ─── CVC-136: full core-indicators value set (CANONICAL, 215 codes) ─────
5249
5249
  // The complete CVC-136 'core - indicators' vocabulary. As of 0.8.13 the
5250
5250
  // AUTHORITATIVE surface for this domain is the SOT JSON
5251
- // `src/cvcs/coreIndicators.v1.0.0.json` (214 entries = 210 substantive + the
5251
+ // `src/cvcs/coreIndicators.v1.0.0.json` (219 entries = 215 substantive + the
5252
5252
  // missingness quadruplet), which also carries the canonical `family`,
5253
5253
  // `polarity`, `severity`, `isAlert` and `alertWhen` entry attributes. This
5254
5254
  // hand-coded array is kept in lockstep with that JSON as a flat key list for
@@ -5272,6 +5272,25 @@ export const CVC_136_OPTIONS: readonly CVC136Option[] = Object.entries(
5272
5272
  // `emits_by_code` (weights/risk.weights.json @ 9b5d654) is present here.
5273
5273
  // Enforced by `src/__tests__/cvc-136-scoring-invariant.test.ts`.
5274
5274
  //
5275
+ // 0.11.1 — 210 → 215 (catalog refresh, prototype a596eb9 → 84a1b677).
5276
+ // The upstream catalog grew by 5 and withdrew none. All five are minted
5277
+ // upstream with `code_status: canonical` (three carry the 2026-07-17
5278
+ // TRA-vetting provenance), so this is catalog CATCH-UP, not invention —
5279
+ // GATE B in `cvc-drift-gate.test.ts` flagged them only because the pin was
5280
+ // stale. `coreIndicators.pin.json` is refreshed to 84a1b677 (213 codes) in
5281
+ // the same change; the 2 scoring-ahead codes remain absent upstream and
5282
+ // stay on the `SCORING_AHEAD_OF_CATALOG` allowlist, unchanged.
5283
+ // + clients_unaware_of_third_party_coordination (TRA-7-aware)
5284
+ // + depends_on_spouse_or_family_for_immigration_status (TRA-14 × TRA-22)
5285
+ // + sexualized_content_in_person_performance_activity (DH § II 2.2.3)
5286
+ // + sexualized_content_online_performance_activity (DH § II 2.2.2)
5287
+ // + trauma_perpetrator_is_current_manager (engine-derived)
5288
+ // PAVE 2.0 needs the first two to express `trafficking_risk_assessment`
5289
+ // emissions; without them the TRA writes assertions against codes that
5290
+ // resolve to nothing.
5291
+ // New SOT entries are APPENDED at positional codes 136-211…136-215 so
5292
+ // every previously issued code keeps its number.
5293
+ //
5275
5294
  // CVC_136_ALERT_INDICATOR above is a legacy Thread-only surface with NO
5276
5295
  // canonical basis; it is deliberately left untouched in 0.8.13 (a separate
5277
5296
  // Thread cleanup). The canonical alert axis is the `isAlert` ATTRIBUTE on
@@ -5309,6 +5328,7 @@ export const CVC_136_CORE_INDICATOR_VALUES = [
5309
5328
  "cannot_stop_working_or_freely_leave",
5310
5329
  "child_not_abusers_in_household",
5311
5330
  "child_welfare_system_involvement",
5331
+ "clients_unaware_of_third_party_coordination",
5312
5332
  "coerced_to_misrepresent_identity_or_activity",
5313
5333
  "coercive_debt_pressure",
5314
5334
  "coercive_debt_pressure_youth",
@@ -5331,6 +5351,7 @@ export const CVC_136_CORE_INDICATOR_VALUES = [
5331
5351
  "debt_terms_deceptive_youth",
5332
5352
  "denied_basic_needs",
5333
5353
  "depends_on_employer_for_immigration_status",
5354
+ "depends_on_spouse_or_family_for_immigration_status",
5334
5355
  "does_not_control_finances_or_earnings",
5335
5356
  "does_not_control_identity_documents",
5336
5357
  "elevated_lethality_risk_signal",
@@ -5424,6 +5445,8 @@ export const CVC_136_CORE_INDICATOR_VALUES = [
5424
5445
  "several_cell_phones_or_frequent_number_changes",
5425
5446
  "sex_acts_in_own_residence",
5426
5447
  "sexual_exploitation",
5448
+ "sexualized_content_in_person_performance_activity",
5449
+ "sexualized_content_online_performance_activity",
5427
5450
  "sexualized_content_performance_activity",
5428
5451
  "shared_contact_network",
5429
5452
  "signs_of_physical_abuse_confinement_or_neglect",
@@ -5469,6 +5492,7 @@ export const CVC_136_CORE_INDICATOR_VALUES = [
5469
5492
  "trafficking_experience_past_10plusy",
5470
5493
  "trafficking_experience_past_3to10y",
5471
5494
  "trafficking_experience_past_lt3y",
5495
+ "trauma_perpetrator_is_current_manager",
5472
5496
  "travel_organized_by_third_party",
5473
5497
  "tricked_or_pressured_into_unwanted_acts",
5474
5498
  "under_18_advertised_age",
@@ -5525,6 +5549,7 @@ export const CVC_136_CORE_INDICATOR_LABELS: Record<CVC136CoreIndicator, string>
5525
5549
  "cannot_stop_working_or_freely_leave": "Cannot stop working or freely leave home/work",
5526
5550
  "child_not_abusers_in_household": "Child in household who is not the abuser's biological child",
5527
5551
  "child_welfare_system_involvement": "Child welfare system involvement (history)",
5552
+ "clients_unaware_of_third_party_coordination": "Clients unaware they are coordinating with a third party (concealed dispatch)",
5528
5553
  "coerced_to_misrepresent_identity_or_activity": "Coerced to misrepresent age, identity, or work activity to outsiders",
5529
5554
  "coercive_debt_pressure": "Pressured to do things to pay off debt (coercive debt repayment)",
5530
5555
  "coercive_debt_pressure_youth": "Pressured to do things to pay off debt (youth missing-from-care)",
@@ -5547,6 +5572,7 @@ export const CVC_136_CORE_INDICATOR_LABELS: Record<CVC136CoreIndicator, string>
5547
5572
  "debt_terms_deceptive_youth": "Debt repayment terms differed from what was expected (youth missing-from-care)",
5548
5573
  "denied_basic_needs": "Denied basic needs (food, water, sleep, medical care)",
5549
5574
  "depends_on_employer_for_immigration_status": "Depends on employer for immigration status (tied visa / living with employer)",
5575
+ "depends_on_spouse_or_family_for_immigration_status": "Depends on spouse / family member for immigration status (tied family visa)",
5550
5576
  "does_not_control_finances_or_earnings": "Limited independence: does not control finances or earnings",
5551
5577
  "does_not_control_identity_documents": "Limited independence: does not control identity documents",
5552
5578
  "elevated_lethality_risk_signal": "Elevated lethality risk",
@@ -5640,6 +5666,8 @@ export const CVC_136_CORE_INDICATOR_LABELS: Record<CVC136CoreIndicator, string>
5640
5666
  "several_cell_phones_or_frequent_number_changes": "Several cell phones or frequently changing phone number",
5641
5667
  "sex_acts_in_own_residence": "Sex acts take place in person's own residence",
5642
5668
  "sexual_exploitation": "Sexual exploitation (general)",
5669
+ "sexualized_content_in_person_performance_activity": "In-person sexualized performance / appearance-based activity",
5670
+ "sexualized_content_online_performance_activity": "Online sexual performance / interactive sexual content activity",
5643
5671
  "sexualized_content_performance_activity": "Sexualized content, performance, or communications activity",
5644
5672
  "shared_contact_network": "Shares a contact network (phones/handles)",
5645
5673
  "signs_of_physical_abuse_confinement_or_neglect": "Signs of physical abuse, confinement, or neglect (observed)",
@@ -5685,6 +5713,7 @@ export const CVC_136_CORE_INDICATOR_LABELS: Record<CVC136CoreIndicator, string>
5685
5713
  "trafficking_experience_past_10plusy": "Trafficking experience recency: 10+ years since last experience",
5686
5714
  "trafficking_experience_past_3to10y": "Trafficking experience recency: 3–10 years since last experience",
5687
5715
  "trafficking_experience_past_lt3y": "Trafficking experience recency: less than 3 years since last experience",
5716
+ "trauma_perpetrator_is_current_manager": "Trauma perpetrator is a current manager / facilitator (trauma-bonded control)",
5688
5717
  "travel_organized_by_third_party": "Travel organized by a third party (sex provider does not control own movement)",
5689
5718
  "tricked_or_pressured_into_unwanted_acts": "Tricked or pressured into unwanted acts or activities (generic coercion)",
5690
5719
  "under_18_advertised_age": "Under 18 (ad-derived / advertised age)",