@htilabs/platform-common-models 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/cvcs/index.cjs +4867 -639
  2. package/dist/cvcs/index.cjs.map +1 -1
  3. package/dist/cvcs/index.d.cts +5145 -609
  4. package/dist/cvcs/index.d.ts +5145 -609
  5. package/dist/cvcs/index.js +4867 -639
  6. package/dist/cvcs/index.js.map +1 -1
  7. package/dist/enums/index.cjs +74 -1
  8. package/dist/enums/index.cjs.map +1 -1
  9. package/dist/enums/index.d.cts +77 -4
  10. package/dist/enums/index.d.ts +77 -4
  11. package/dist/enums/index.js +74 -1
  12. package/dist/enums/index.js.map +1 -1
  13. package/dist/{index-I-DiX9eQ.d.ts → index-CDoqrfc1.d.ts} +1 -1
  14. package/dist/{index-CoVr1jIV.d.cts → index-Zu_mOJRn.d.cts} +1 -1
  15. package/dist/index.cjs +5382 -588
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +3 -2
  18. package/dist/index.d.ts +3 -2
  19. package/dist/index.js +5371 -588
  20. package/dist/index.js.map +1 -1
  21. package/dist/information-scope/index.cjs +521 -0
  22. package/dist/information-scope/index.cjs.map +1 -0
  23. package/dist/information-scope/index.d.cts +442 -0
  24. package/dist/information-scope/index.d.ts +442 -0
  25. package/dist/information-scope/index.js +484 -0
  26. package/dist/information-scope/index.js.map +1 -0
  27. package/dist/models/index.d.cts +2 -2
  28. package/dist/models/index.d.ts +2 -2
  29. package/dist/schemas/index.d.cts +25 -25
  30. package/dist/schemas/index.d.ts +25 -25
  31. package/dist/services/index.cjs +495 -2
  32. package/dist/services/index.cjs.map +1 -1
  33. package/dist/services/index.d.cts +1 -0
  34. package/dist/services/index.d.ts +1 -0
  35. package/dist/services/index.js +483 -1
  36. package/dist/services/index.js.map +1 -1
  37. package/package.json +32 -26
  38. package/src/__tests__/__snapshots__/cvc-sot.snap +3 -3
  39. package/src/__tests__/core-information-scope-invariant.test.ts +835 -456
  40. package/src/__tests__/cvc-sot-snapshot.test.ts +17 -17
  41. package/src/__tests__/cvc-structural.test.ts +2 -2
  42. package/src/__tests__/location-type-routing-invariant.test.ts +25 -8
  43. package/src/cvcs/coreInformationScope.v2.1.0.json +5498 -0
  44. package/src/cvcs/index.ts +2 -2
  45. package/src/cvcs/roiScope.v1.4.0.json +360 -0
  46. package/src/generated/cvc-enums.ts +77 -4
  47. package/src/services/__tests__/fixtures/infoscope-v4/information_scope_v3_placements.projection.csv +12 -0
  48. package/src/services/__tests__/fixtures/infoscope-v4/information_scope_v4.migrations.csv +106 -0
  49. package/src/services/__tests__/fixtures/infoscope-v4/information_scope_v4.rows.csv +117 -0
  50. package/src/services/__tests__/fixtures/infoscope-v4/loadInfoscopeV4Fixtures.ts +187 -0
  51. package/src/services/__tests__/informationScopeResolver.test.ts +1278 -0
  52. package/src/services/index.ts +10 -3
  53. package/src/services/informationScope.ts +10 -0
  54. package/src/services/informationScopeResolver.ts +879 -0
  55. package/src/services/informationScopeSot.ts +203 -0
  56. package/src/cvcs/coreInformationScope.v1.1.0.json +0 -1290
  57. package/src/cvcs/roiScope.v1.2.0.json +0 -340
  58. package/dist/{cvcEntry-BCj1OWqL.d.cts → cvcEntry-0BIB9sen.d.cts} +8 -8
  59. package/dist/{cvcEntry-BCj1OWqL.d.ts → cvcEntry-0BIB9sen.d.ts} +8 -8
@@ -0,0 +1,1278 @@
1
+ /**
2
+ * CVC-236 v4 information-scope resolver.
3
+ *
4
+ * PRIMARY binding: the package SOT (`coreInformationScope.v2.1.0.json`, co-o73.1)
5
+ * through `scopeRowsFromSot` / `scopeMigrationsFromSot`. CROSS-CHECK: the canon's
6
+ * generated CSV pair (prototype @ e86dd89c SIGNED-GRAIN, byte-identical at 7ca7e586)
7
+ * must equal the adapter output row for row.
8
+ *
9
+ * Spec: INFOSCOPE_V4_DEV_HANDOFF_2026-10-09.md § 2 rules 1–7, § 3, § 7 row 6;
10
+ * scenarios from INFOSCOPE_PHASE4_STRESS_TEST_2026-10-09.md § 1 and the runner
11
+ * tools/infoscope/phase4_stress_test.py (the synthetic case: Jane, Dale, Mika,
12
+ * Maria, Tom; record homes from information_scope_v4.fields.csv); defaults from
13
+ * INFOSCOPE_PHASE3_NOTES_2026-10-08.md § 2 (D1, D5, D11).
14
+ */
15
+
16
+ import { describe, expect, it } from "vitest";
17
+
18
+ import { coreInformationScopeSot } from "../../cvcs/index.js";
19
+ import {
20
+ INFORMATION_SCOPE_SYSTEM_INFO as SYS,
21
+ INFORMATION_SCOPE_VERSION,
22
+ createInformationScopeResolver,
23
+ isScopeInstrumentRow,
24
+ isScopeRestRow,
25
+ isSelectableScopeRow,
26
+ kindForPerson,
27
+ type ScopeRow,
28
+ type ScopeSubjectKind,
29
+ } from "../informationScopeResolver.js";
30
+ import {
31
+ scopeMigrationsFromSot,
32
+ scopeRowsFromSot,
33
+ type CoreInformationScopeSot,
34
+ } from "../informationScopeSot.js";
35
+ import {
36
+ INFOSCOPE_V3_PLACEMENTS,
37
+ INFOSCOPE_V4_CANON_BLOBS,
38
+ INFOSCOPE_V4_CANON_SHA,
39
+ fixtureBodyBlobSha,
40
+ fixtureText,
41
+ loadCsvMigrations,
42
+ loadCsvRows,
43
+ loadV3Placements,
44
+ type InfoscopeFixture,
45
+ } from "./fixtures/infoscope-v4/loadInfoscopeV4Fixtures.js";
46
+
47
+ const sot = coreInformationScopeSot as CoreInformationScopeSot & {
48
+ _supersedes: { version: string; keyMap: Record<string, string> };
49
+ };
50
+ const rows = scopeRowsFromSot(sot);
51
+ const migrations = scopeMigrationsFromSot(sot);
52
+ const scope = createInformationScopeResolver({ rows, migrations });
53
+
54
+ const codes = rows.map((r) => r.scopeCode);
55
+ const containers = codes.filter((c) => scope.childrenOf(c).length > 0);
56
+ const descendants = (code: string): string[] =>
57
+ scope.childrenOf(code).flatMap((c) => [c, ...descendants(c)]);
58
+ const chainHas = (code: string, pred: (c: string) => boolean): boolean =>
59
+ scope.ancestorsOf(code).some(pred);
60
+ const isFloor = (c: string): boolean => scope.row(c)?.platformFloor === true;
61
+ const isOff = (c: string): boolean => scope.row(c)?.shareableDefault === false;
62
+ const ENABLED_ALL = codes.filter((c) => isOff(c) && !isFloor(c));
63
+ const KINDS = ["offenders", "family", "others"] as const;
64
+ /** Whose list is read (ruling 2026-10-09: required, no default). */
65
+ const RELEASE = { subject: "release" } as const;
66
+ const SHARE = { subject: "share" } as const;
67
+ const POLICY = { subject: "policy" } as const;
68
+ const SUBJECTS = [RELEASE, SHARE, POLICY] as const;
69
+ /** Order-insensitive list equality (output order follows the bound tree's row order). */
70
+ const same = (got: readonly string[], want: readonly string[]): void =>
71
+ expect([...got].sort()).toEqual([...want].sort());
72
+
73
+ // ─── The synthetic case (Phase 4 § 1; homes per fields.csv) ─────────────────
74
+
75
+ interface CaseRecord {
76
+ id: string;
77
+ subject: ScopeSubjectKind;
78
+ home: string;
79
+ }
80
+ const rec = (id: string, subject: ScopeSubjectKind, home: string): CaseRecord => ({
81
+ id,
82
+ subject,
83
+ home,
84
+ });
85
+ const CASE: CaseRecord[] = [
86
+ // Jane — the client
87
+ rec("jane.names", "client", "names"),
88
+ rec("jane.dob", "client", "dob"),
89
+ rec("jane.address", "client", "addresses"),
90
+ rec("jane.encounter", "client", "encounter_location"),
91
+ rec("jane.case_id", "client", "additional_ids"),
92
+ rec("jane.race", "client", "demographics"),
93
+ rec("jane.living_situation", "client", "identifying"),
94
+ rec("jane.vehicle", "client", "identifying"),
95
+ rec("jane.phone", "client", "contact_info"),
96
+ rec("jane.ec_designation_maria", "client", "contact_info"),
97
+ rec("jane.priorities", "client", "priorities_safety"),
98
+ rec("jane.accommodations", "client", "accommodation_needs"),
99
+ rec("jane.mental_health", "client", "health_status"),
100
+ rec("jane.hiv", "client", "health_status"),
101
+ rec("jane.pregnancy", "client", "health_status"),
102
+ rec("jane.immigration_status", "client", "immigration_status"),
103
+ rec("jane.t_visa_application", "client", "immigration_applications"),
104
+ rec("jane.indicator", "client", "screen_indicators"),
105
+ rec("jane.victimization", "client", "victimization"),
106
+ rec("jane.worker_subrole", "client", "victimization"),
107
+ rec("jane.protection_order", "client", "system_involvement"),
108
+ rec("jane.relationship_dale", "client", "relationships_household"),
109
+ rec("jane.household_roster", "client", "relationships_household"),
110
+ rec("jane.pet", "client", "relationships_household"),
111
+ rec("jane.contact_history", "client", "contact_history"),
112
+ rec("jane.services", "client", "service_history"),
113
+ rec("jane.service_plan", "client", "plans_goals"),
114
+ rec("jane.da_summary", "client", "summary_danger_assessment"),
115
+ rec("jane.da_full", "client", "full_danger_assessment"),
116
+ rec("jane.findings", "client", "summary_findings"),
117
+ rec("jane.case_note_pregnancy", "client", "case_notes"),
118
+ rec("jane.session_summary", "client", "session_summary"),
119
+ rec("jane.safe_location", "client", "safe_locations"),
120
+ // Dale — caused harm; lives with Jane
121
+ rec("dale.names", "offenders", "names"),
122
+ rec("dale.dob", "offenders", "dob"),
123
+ rec("dale.address", "offenders", "addresses"),
124
+ rec("dale.phone", "offenders", "contact_info"),
125
+ rec("dale.description", "offenders", "identifying"),
126
+ rec("dale.truck", "offenders", "identifying"),
127
+ rec("dale.offender_status", "offenders", "offenders.risk"),
128
+ rec("dale.facilitator_role", "offenders", "offenders.risk"),
129
+ rec("dale.trafficking_role", "offenders", "victimization"),
130
+ rec("dale.tra_perpetrator_record", "offenders", "offenders.risk"),
131
+ rec("dale.tra_run", "offenders", "summary_tra"),
132
+ rec("dale.immigration_status", "offenders", "immigration_status"),
133
+ rec("dale.record_note", "offenders", "risk"),
134
+ // Mika — eligible family member
135
+ rec("mika.names", "family", "names"),
136
+ rec("mika.dob", "family", "dob"),
137
+ rec("mika.child_profile", "family", "family.identifying"),
138
+ rec("mika.school_phone", "family", "contact_info"),
139
+ rec("mika.health", "family", "health_status"),
140
+ // Maria — the sister (emergency contact); Tom — a witness
141
+ rec("maria.names", "others", "names"),
142
+ rec("maria.address", "others", "addresses"),
143
+ rec("maria.phone", "others", "contact_info"),
144
+ rec("tom.names", "others", "names"),
145
+ rec("tom.tra_cross_person", "others", "victimization"),
146
+ ];
147
+
148
+ const deliver = (selection: readonly string[], enabled: readonly string[] = []): Set<string> =>
149
+ new Set(
150
+ CASE.filter((r) =>
151
+ scope.isIncludedOnShare(selection, scope.rowForSubject(r.home, r.subject), {
152
+ enabledOffByDefault: enabled,
153
+ }),
154
+ ).map((r) => r.id),
155
+ );
156
+ const ids = (pred: (r: CaseRecord) => boolean): string[] => CASE.filter(pred).map((r) => r.id);
157
+
158
+ // ─── Binding: SOT primary, CSV cross-check ──────────────────────────────────
159
+
160
+ describe("binding — the SOT through the adapters; the canon CSV pair as cross-check", () => {
161
+ it("binds the live v4 tree: 115 rows, 28 instrument rows, one rest row, 12 rows per kind", () => {
162
+ expect(rows).toHaveLength(115);
163
+ expect(rows.filter(isScopeInstrumentRow)).toHaveLength(28);
164
+ expect(rows.filter(isScopeRestRow).map((r) => r.scopeCode)).toEqual(["identifying.other"]);
165
+ for (const kind of KINDS) expect(rows.filter((r) => r.kindBranch === kind)).toHaveLength(12);
166
+ expect(scope.version).toBe(4);
167
+ expect(INFORMATION_SCOPE_VERSION).toBe(4);
168
+ });
169
+
170
+ it("selection codes are canon's dotted codes, never SOT keys or wire codes", () => {
171
+ expect(codes.some((c) => c.includes("__"))).toBe(false);
172
+ expect(codes.some((c) => /^\d{3}-/.test(c))).toBe(false);
173
+ expect(codes).toContain("offenders.risk");
174
+ for (const e of sot.entries) {
175
+ if (e.canonicalCode) expect(e.canonicalCode).toBe(e.key.replace(/__/g, "."));
176
+ }
177
+ });
178
+
179
+ it("leaves the 27 tombstones and the missingness group out of the tree", () => {
180
+ const left = sot.entries.filter((e) => !scope.row(e.canonicalCode ?? e.key));
181
+ expect(left.filter((e) => e.status === "retired")).toHaveLength(27);
182
+ same(
183
+ left.filter((e) => e.status !== "retired").map((e) => e.key),
184
+ ["missingness_root", "unknown", "anonymous", "data_not_collected"],
185
+ );
186
+ });
187
+
188
+ it.each(Object.entries(INFOSCOPE_V4_CANON_BLOBS))(
189
+ "fixture %s is the canon blob verbatim (%s)",
190
+ (file, blob) => {
191
+ expect(fixtureText(file as InfoscopeFixture).split("\n")[0]).toContain(INFOSCOPE_V4_CANON_SHA);
192
+ expect(fixtureBodyBlobSha(file as InfoscopeFixture)).toBe(blob);
193
+ },
194
+ );
195
+
196
+ it("the adapter's rows equal the canon rows CSV, row for row", () => {
197
+ const csv = loadCsvRows();
198
+ expect(csv).toHaveLength(rows.length);
199
+ const csvBy = new Map(csv.map((r) => [r.scopeCode, r]));
200
+ for (const r of rows) expect(r, r.scopeCode).toEqual(csvBy.get(r.scopeCode));
201
+ });
202
+
203
+ it("the adapter's migration table equals the canon migrations CSV (one duplicate line aside)", () => {
204
+ const line = (m: { from: string; to: readonly string[]; rule: string }): string =>
205
+ `${m.from}|${m.rule}|${m.to.join(" ")}`;
206
+ const csv = loadCsvMigrations();
207
+ expect(csv).toHaveLength(104);
208
+ expect(migrations).toHaveLength(103);
209
+ same([...new Set(csv.map(line))], migrations.map(line));
210
+ // Canon's qualified labels are exactly the SOT's qualifier fields.
211
+ const merge = csv.filter((m) => m.label === "row (merge; signed release keeps its grain)");
212
+ same(
213
+ merge.map((m) => m.from),
214
+ migrations.filter((m) => m.releaseReading === "retain").map((m) => m.from),
215
+ );
216
+ same(
217
+ csv.filter((m) => m.informational === true).map((m) => m.from),
218
+ migrations.filter((m) => m.informational === true).map((m) => m.from),
219
+ );
220
+ for (const m of migrations) {
221
+ const c = csv.find((x) => x.from === m.from && x.rule === m.rule);
222
+ expect(m.note, m.from).toBe(c?.note);
223
+ }
224
+ });
225
+
226
+ it("binding the CSV pair directly gives the same resolver answers", () => {
227
+ const viaCsv = createInformationScopeResolver({
228
+ rows: loadCsvRows(),
229
+ migrations: loadCsvMigrations(),
230
+ });
231
+ const all = [SYS, "primary_client"];
232
+ for (const c of codes) {
233
+ for (const kind of KINDS) {
234
+ expect(viaCsv.rowForSubject(c, kind)).toBe(scope.rowForSubject(c, kind));
235
+ }
236
+ expect(viaCsv.isCovered(all, c)).toBe(scope.isCovered(all, c));
237
+ }
238
+ });
239
+
240
+ it("a live SOT entry missing a field the resolver needs fails closed (throws)", () => {
241
+ const broken = {
242
+ ...sot,
243
+ entries: sot.entries.map((e) => (e.key === "names" ? { ...e, apps: undefined } : e)),
244
+ };
245
+ expect(() => scopeRowsFromSot(broken)).toThrow(/"names" has apps/);
246
+ const noSdt = {
247
+ ...sot,
248
+ entries: sot.entries.map((e) => (e.key === "dob" ? { ...e, specialDataType: undefined } : e)),
249
+ };
250
+ expect(() => scopeRowsFromSot(noSdt)).toThrow(/"dob" has specialDataType/);
251
+ });
252
+ });
253
+
254
+ // ─── Rule 2: coverage ───────────────────────────────────────────────────────
255
+
256
+ describe("rule 2 — a row is covered when it or any ancestor is in the flat list", () => {
257
+ it.each([
258
+ [["primary_client"], "names", true],
259
+ [["primary_client"], "full_lap", true],
260
+ [["primary_client"], "offenders.identifying", false],
261
+ [["offenders"], "offenders.instrument_full", true],
262
+ [["offenders"], "names", false],
263
+ [["other_named_persons"], "family.contact", true],
264
+ [["identifying"], "dob", true],
265
+ [["names"], "identifying", false],
266
+ [["instrument_summary"], "summary_lap", true],
267
+ [["instrument_summary"], "full_lap", false],
268
+ [["risk"], "offenders.risk", false],
269
+ [[], "names", false],
270
+ [["primary_client"], "not_a_code", false],
271
+ ] as const)("%j covers %s → %s", (selection, code, expected) => {
272
+ expect(scope.isCovered(selection, code)).toBe(expected);
273
+ });
274
+ });
275
+
276
+ describe("System metadata is always covered (handoff § 1: always included, never a choice)", () => {
277
+ it.each([SYS, "system"])("%s is covered by every selection, even an empty or null one", (code) => {
278
+ expect(scope.isCovered([], code)).toBe(true);
279
+ expect(scope.isCovered(null, code)).toBe(true);
280
+ expect(scope.isIncludedOnShare([], code)).toBe(true);
281
+ });
282
+
283
+ it("a record homed on `system` (where fields.csv homes the 260 system fields) rides every share", () => {
284
+ for (const kind of ["client", ...KINDS] as const) {
285
+ expect(scope.rowForSubject("system", kind)).toBe("system");
286
+ }
287
+ expect(scope.isIncludedOnShare([SYS, "names"], "system")).toBe(true);
288
+ expect(scope.isCovered([], "notes")).toBe(false);
289
+ });
290
+ });
291
+
292
+ // ─── Rule 3: the category_rest row ──────────────────────────────────────────
293
+
294
+ describe("rule 3 — identifying.other keeps the category-grain facts", () => {
295
+ it("is not selectable, is covered with its category, and covers a record homed on the category", () => {
296
+ expect(isSelectableScopeRow(scope.row("identifying.other"))).toBe(false);
297
+ expect(isScopeRestRow(scope.row("identifying.other"))).toBe(true);
298
+ expect(scope.isCovered(["identifying"], "identifying.other")).toBe(true);
299
+ expect(scope.isCovered(["identifying.other"], "identifying")).toBe(true);
300
+ expect(scope.isCovered(["identifying.other"], "names")).toBe(false);
301
+ });
302
+
303
+ it("is written when a picker expands the category, so un-ticking Demographics keeps living situation", () => {
304
+ same(scope.expandSelectAll("identifying"), [
305
+ "names",
306
+ "dob",
307
+ "addresses",
308
+ "additional_ids",
309
+ "demographics",
310
+ "identifying.other",
311
+ ]);
312
+ const sel = scope.deselectChild([SYS, "identifying"], "demographics");
313
+ expect(sel).toContain("identifying.other");
314
+ expect(sel).not.toContain("demographics");
315
+ const got = deliver(sel);
316
+ expect(got.has("jane.living_situation")).toBe(true);
317
+ expect(got.has("jane.vehicle")).toBe(true);
318
+ expect(got.has("jane.race")).toBe(false);
319
+ });
320
+ });
321
+
322
+ // ─── Rules 4 + 5: off-by-default and the floor ─────────────────────────────
323
+
324
+ describe("rule 4 — off-by-default rows need enabling, not only selecting", () => {
325
+ it("select-all at every container never silently enables an off-by-default row or the floor", () => {
326
+ expect(containers.length).toBeGreaterThan(20);
327
+ for (const c of containers) {
328
+ for (const d of descendants(c)) {
329
+ const included = scope.isIncludedOnShare([SYS, c], d);
330
+ if (chainHas(d, isFloor) || chainHas(d, isOff)) expect(included, `${c} → ${d}`).toBe(false);
331
+ else expect(included, `${c} → ${d}`).toBe(true);
332
+ }
333
+ }
334
+ });
335
+
336
+ it("every off-by-default row in the chain must be enabled (the reference runner's rule)", () => {
337
+ const sel = [SYS, "immigration_legal_status"];
338
+ expect(scope.shareVerdict(sel, "immigration_status")).toEqual({
339
+ included: false,
340
+ reason: "off_by_default",
341
+ notEnabled: ["immigration_status", "immigration_legal_status"],
342
+ });
343
+ const parentOnly = { enabledOffByDefault: ["immigration_legal_status"] };
344
+ expect(scope.isIncludedOnShare(sel, "immigration_status", parentOnly)).toBe(false);
345
+ const both = { enabledOffByDefault: ["immigration_legal_status", "immigration_status"] };
346
+ expect(scope.isIncludedOnShare(sel, "immigration_status", both)).toBe(true);
347
+ const fullOnly = { enabledOffByDefault: new Set(["instrument_full"]) };
348
+ expect(scope.isIncludedOnShare([SYS, "instruments"], "full_lap", fullOnly)).toBe(false);
349
+ const fullAndLap = { enabledOffByDefault: new Set(["instrument_full", "full_lap"]) };
350
+ expect(scope.isIncludedOnShare([SYS, "instruments"], "full_lap", fullAndLap)).toBe(true);
351
+ });
352
+ });
353
+
354
+ describe("rule 5 — the floor never leaves", () => {
355
+ const floors = codes.filter(isFloor);
356
+ it("there are four floor rows (the client's and each kind's safe locations)", () => {
357
+ same(floors, [
358
+ "safe_locations",
359
+ "offenders.safe_locations",
360
+ "family.safe_locations",
361
+ "others.safe_locations",
362
+ ]);
363
+ });
364
+
365
+ it.each(floors)("%s is never included, even named outright with everything enabled", (code) => {
366
+ const v = scope.shareVerdict([SYS, code], code, { enabledOffByDefault: codes });
367
+ expect(v).toEqual({ included: false, reason: "platform_floor" });
368
+ });
369
+ });
370
+
371
+ // ─── Rule 6: select-all / de-select ─────────────────────────────────────────
372
+
373
+ describe("rule 6 — select-all at any level; de-select any child; the store stays flat", () => {
374
+ it.each([
375
+ ["primary_client", "health_status"],
376
+ ["primary_client", "contact"],
377
+ ["primary_client", "demographics"],
378
+ ["other_named_persons", "family"],
379
+ ["offenders", "offenders.contact"],
380
+ ["family", "family.immigration_legal_status"],
381
+ ["instruments", "instrument_full"],
382
+ ["risk", "system_involvement"],
383
+ ["immigration_legal_status", "immigration_applications"],
384
+ ["primary_client", "names"],
385
+ ])("de-select %s › %s keeps the siblings and drops the child", (parent, child) => {
386
+ const sel = scope.deselectChild([SYS, parent], child);
387
+ expect(sel).toContain(SYS);
388
+ expect(new Set(sel).size).toBe(sel.length);
389
+ const childTree = new Set([child, ...descendants(child)]);
390
+ for (const d of descendants(parent)) {
391
+ if (childTree.has(d)) {
392
+ expect(scope.isCovered(sel, d), `${d} should be gone`).toBe(false);
393
+ continue;
394
+ }
395
+ // A container with no rest row holds no facts of its own once expanded.
396
+ const emptyContainer =
397
+ scope.childrenOf(d).length > 0 &&
398
+ !scope.childrenOf(d).some((c) => isScopeRestRow(scope.row(c)));
399
+ if (!emptyContainer) expect(scope.isCovered(sel, d), `${d} should stay`).toBe(true);
400
+ }
401
+ });
402
+
403
+ it("re-selecting the parent brings the child back (no exclusions in the store)", () => {
404
+ const sel = scope.deselectChild([SYS, "primary_client"], "demographics");
405
+ expect(scope.isCovered(sel, "demographics")).toBe(false);
406
+ const again = scope.selectAll(sel, "primary_client");
407
+ same(again, [SYS, "primary_client"]);
408
+ expect(scope.isCovered(again, "demographics")).toBe(true);
409
+ });
410
+
411
+ it("system_info is always present and System metadata cannot be de-selected", () => {
412
+ expect(scope.selectAll([], "names")).toContain(SYS);
413
+ expect(scope.deselectChild(["names"], "names")).toEqual([SYS]);
414
+ expect(() => scope.deselectChild([SYS], SYS)).toThrow(RangeError);
415
+ expect(() => scope.deselectChild([SYS, "system"], "system")).toThrow(RangeError);
416
+ });
417
+
418
+ it("a picker never writes or de-selects a non-selectable or unknown row", () => {
419
+ expect(() => scope.selectAll([SYS], "full_lap")).toThrow(RangeError);
420
+ expect(() => scope.selectAll([SYS], "identifying.other")).toThrow(RangeError);
421
+ expect(() => scope.deselectChild([SYS, "instruments"], "summary_lap")).toThrow(RangeError);
422
+ expect(() => scope.deselectChild([SYS], "nope")).toThrow(RangeError);
423
+ });
424
+
425
+ it("does not mutate its input and keeps unknown stored codes", () => {
426
+ const input = Object.freeze([SYS, "primary_client", "legacy_code"]);
427
+ const out = scope.deselectChild(input, "contact");
428
+ expect(input).toEqual([SYS, "primary_client", "legacy_code"]);
429
+ expect(out[out.length - 1]).toBe("legacy_code");
430
+ });
431
+
432
+ it("returns copies: callers cannot reach the resolver's internal arrays", () => {
433
+ scope.childrenOf("identifying").push("x");
434
+ scope.ancestorsOf("names").push("x");
435
+ expect(scope.childrenOf("identifying")).not.toContain("x");
436
+ expect(scope.ancestorsOf("names")).not.toContain("x");
437
+ });
438
+ });
439
+
440
+ describe("instrument rows — non-selectable, covered by their parents", () => {
441
+ const instrumentRows = rows.filter(isScopeInstrumentRow);
442
+ it.each(instrumentRows.map((r) => [r.scopeCode, r.parentScopeCode as string]))(
443
+ "%s is covered by %s and not selectable",
444
+ (code, parent) => {
445
+ expect(isSelectableScopeRow(scope.row(code))).toBe(false);
446
+ expect(scope.isCovered([parent], code)).toBe(true);
447
+ expect(scope.isCovered(["instruments"], code)).toBe(true);
448
+ },
449
+ );
450
+ it("the guards answer false for an unknown code", () => {
451
+ expect(isSelectableScopeRow(scope.row("nope"))).toBe(false);
452
+ expect(isScopeRestRow(undefined)).toBe(false);
453
+ expect(isScopeInstrumentRow(undefined)).toBe(false);
454
+ });
455
+ });
456
+
457
+ // ─── Rule 7: level_floor (the viewing side) ─────────────────────────────────
458
+
459
+ describe("rule 7 — level_floor is the viewing side; sharing ignores it", () => {
460
+ it.each([
461
+ [1, "names", true],
462
+ [1, "dob", true],
463
+ [1, SYS, true],
464
+ [1, "addresses", false],
465
+ [1, "offenders.identifying", false],
466
+ [1, "family.identifying", false],
467
+ [2, "names", true],
468
+ [2, "additional_ids", false],
469
+ [3, "addresses", true],
470
+ [3, "family.identifying", true],
471
+ [3, "not_a_code", false],
472
+ ] as const)("level %i sees %s → %s", (level, code, expected) => {
473
+ expect(scope.isVisibleAtLevel(level, code)).toBe(expected);
474
+ });
475
+
476
+ it("the level-1 stub never carries another person's name", () => {
477
+ const stub = codes.filter((c) => scope.isVisibleAtLevel(1, c));
478
+ same(stub, ["system", SYS, "primary_client", "names", "dob"]);
479
+ expect(stub.includes(scope.rowForSubject("names", "offenders"))).toBe(false);
480
+ });
481
+
482
+ it("a floor-3 row is still an ordinary pick for sharing", () => {
483
+ expect(scope.isIncludedOnShare([SYS, "addresses"], "addresses")).toBe(true);
484
+ });
485
+ });
486
+
487
+ // ─── Rule 1: the branch is decided per record ──────────────────────────────
488
+
489
+ describe("rule 1 — rowForSubject: the deepest row the kind defines", () => {
490
+ it.each([
491
+ ["names", "client", "names"],
492
+ ["names", "family", "family.identifying"],
493
+ ["identifying.other", "others", "others.identifying"],
494
+ ["risk", "offenders", "offenders.risk"],
495
+ ["victimization", "offenders", "offenders.risk"],
496
+ ["health_status", "family", "family.health_accommodation"],
497
+ ["immigration_status", "offenders", "offenders.immigration_legal_status"],
498
+ ["safe_locations", "family", "family.safe_locations"],
499
+ ["full_lap", "offenders", "offenders.instrument_full"],
500
+ ["instrument_full", "others", "others.instrument_full"],
501
+ ["summary_tra", "offenders", "offenders.instrument_summary"],
502
+ ["relationships_household", "family", "family.relationships_household"],
503
+ ["primary_client", "family", "family"],
504
+ ["offenders.risk", "offenders", "offenders.risk"],
505
+ ["offenders.risk", "family", "family"],
506
+ ["family.identifying", "family", "family.identifying"],
507
+ ["family.identifying", "client", "family.identifying"],
508
+ ["case_notes", "offenders", "case_notes"],
509
+ ["session_summary", "family", "session_summary"],
510
+ [SYS, "others", SYS],
511
+ ["derived_risk_signals", "offenders", "derived_risk_signals"],
512
+ ["network_membership", "others", "network_membership"],
513
+ ["case_attachments", "family", "case_attachments"],
514
+ ] as const)("%s about %s → %s", (home, kind, expected) => {
515
+ expect(scope.rowForSubject(home, kind)).toBe(expected);
516
+ });
517
+
518
+ it("every client-branch home resolves under each kind (the CI row stays home)", () => {
519
+ const client = codes.filter((c) => chainHas(c, (a) => a === "primary_client"));
520
+ for (const kind of KINDS) {
521
+ for (const home of client) {
522
+ const got = scope.rowForSubject(home, kind);
523
+ if (home === "derived_risk_signals") expect(got).toBe(home);
524
+ else expect(scope.ancestorsOf(got), `${home} → ${got}`).toContain(kind);
525
+ }
526
+ }
527
+ });
528
+
529
+ it("the LEADS carve-out does not read `apps`: missing or lowercased apps change nothing", () => {
530
+ const variants: unknown[] = [undefined, ["leads"], ["LEADS"], {}];
531
+ for (const apps of variants) {
532
+ const bound = createInformationScopeResolver({
533
+ rows: rows.map((r) => ({ ...r, apps }) as unknown as ScopeRow),
534
+ migrations,
535
+ });
536
+ for (const kind of KINDS) {
537
+ expect(bound.rowForSubject("derived_risk_signals", kind)).toBe("derived_risk_signals");
538
+ expect(bound.rowForSubject("risk", kind)).toBe(`${kind}.risk`);
539
+ }
540
+ }
541
+ });
542
+
543
+ it("a row with no specialDataType fails closed: the tree refuses to bind", () => {
544
+ const noSdt = rows.map((r) =>
545
+ r.scopeCode === "derived_risk_signals" ? { ...r, specialDataType: undefined } : r,
546
+ ) as unknown as ScopeRow[];
547
+ expect(() => createInformationScopeResolver({ rows: noSdt })).toThrow(/specialDataType/);
548
+ });
549
+
550
+ it("an unknown home throws", () => {
551
+ expect(() => scope.rowForSubject("nope", "family")).toThrow(RangeError);
552
+ });
553
+ });
554
+
555
+ describe("kindForPerson (D5) — caused harm wins; EFM is asserted; neither → others", () => {
556
+ it.each([
557
+ [true, false, "offenders"],
558
+ [true, true, "offenders"],
559
+ [false, true, "family"],
560
+ [false, false, "others"],
561
+ ] as const)("causedHarm=%s efmAsserted=%s → %s", (causedHarm, efmAsserted, expected) => {
562
+ expect(kindForPerson({ causedHarm, efmAsserted })).toBe(expected);
563
+ });
564
+ });
565
+
566
+ // ─── § 3: migrations, scopeVersion ─────────────────────────────────────────
567
+
568
+ describe("§ 3 — readSelection / readRestriction", () => {
569
+ it("identity: an unchanged code reads the same", () => {
570
+ const r = scope.readSelection([SYS, "names", "contact_info"], 3, RELEASE);
571
+ same(r.informationScope, [SYS, "names", "contact_info"]);
572
+ expect(r.codes.map((c) => c.rule)).toEqual(["identity", "identity", "identity"]);
573
+ expect(r.unsupportedVersion).toBe(false);
574
+ });
575
+
576
+ it("row: retired v3 rows read as their successors (a policy's reading)", () => {
577
+ const r = scope.readSelection(["hiv_status", "uscis_alien_number", "tvap_enrollment"], 3, POLICY);
578
+ same(r.informationScope, [
579
+ SYS,
580
+ "health_status",
581
+ "immigration_status",
582
+ "immigration_applications",
583
+ ]);
584
+ expect(r.retired).toEqual(["hiv_status", "uscis_alien_number", "tvap_enrollment"]);
585
+ });
586
+
587
+ it("row: offender_facilitator reads as offenders.identifying + offenders.risk, never the whole kind", () => {
588
+ const r = scope.readSelection([SYS, "offender_facilitator"], 3, RELEASE);
589
+ same(r.informationScope, [SYS, "offenders.identifying", "offenders.risk"]);
590
+ expect(scope.isCovered(r.informationScope, "offenders.contact")).toBe(false);
591
+ expect(scope.isCovered(r.informationScope, "offenders.health_accommodation")).toBe(false);
592
+ });
593
+
594
+ it("D11 category: risk → risk only; identifying → identifying only (never widened)", () => {
595
+ const risk = scope.readSelection([SYS, "risk"], 3, POLICY);
596
+ same(risk.informationScope, [SYS, "risk"]);
597
+ expect(risk.codes[1].rule).toBe("category");
598
+ for (const kind of KINDS) {
599
+ expect(scope.isCovered(risk.informationScope, `${kind}.risk`)).toBe(false);
600
+ }
601
+ const ident = scope.readSelection([SYS, "identifying"], 3, POLICY);
602
+ same(ident.informationScope, [SYS, "identifying"]);
603
+ for (const kind of KINDS) {
604
+ expect(scope.isCovered(ident.informationScope, `${kind}.identifying`)).toBe(false);
605
+ }
606
+ });
607
+
608
+ it("subtract: an offender_facilitator RESTRICTION restricts the whole offenders kind", () => {
609
+ const r = scope.readRestriction(["offender_facilitator"], 3);
610
+ expect(r.informationScope).toEqual(["offenders"]);
611
+ expect(r.codes[0].rule).toBe("subtract");
612
+ expect(r.retired).toEqual(["offender_facilitator"]);
613
+ for (const c of descendants("offenders")) {
614
+ expect(scope.isCovered(r.informationScope, c)).toBe(true);
615
+ }
616
+ // A restriction reading never names system_info unless it was stored.
617
+ expect(scope.readRestriction(["hiv_status"], 3).informationScope).toEqual(["health_status"]);
618
+ });
619
+
620
+ it("retired before v4: the pre-v3 instrument codes have a stated reading, some read as nothing", () => {
621
+ const r = scope.readSelection(
622
+ ["ida_full", "screen_notes", "background", "assessment_records"],
623
+ 3,
624
+ RELEASE,
625
+ );
626
+ same(r.informationScope, [SYS, "summary_ida", "full_ida"]);
627
+ expect(r.codes.map((c) => c.rule)).toEqual(Array(4).fill("retired before v4"));
628
+ });
629
+
630
+ it("a v4 list: live codes read as written; retired codes still read through the table (§ 3 (c))", () => {
631
+ const r = scope.readSelection(
632
+ [SYS, "offenders", "hiv_status", "offender_facilitator", "assessment_records", "nope"],
633
+ 4,
634
+ POLICY,
635
+ );
636
+ expect(r.codes.map((c) => [c.from, c.rule])).toEqual([
637
+ [SYS, "identity"],
638
+ ["offenders", "identity"],
639
+ ["hiv_status", "row"],
640
+ ["offender_facilitator", "row"],
641
+ ["assessment_records", "retired before v4"],
642
+ ["nope", "unknown"],
643
+ ]);
644
+ same(r.informationScope, [
645
+ SYS,
646
+ "offenders",
647
+ "health_status",
648
+ "offenders.identifying",
649
+ "offenders.risk",
650
+ ]);
651
+ expect(r.retired).toEqual(["hiv_status", "offender_facilitator", "assessment_records"]);
652
+ expect(r.unknown).toEqual(["nope"]);
653
+ const restriction = scope.readRestriction(["offender_facilitator"], 4);
654
+ expect(restriction.codes[0].rule).toBe("subtract");
655
+ expect(restriction.informationScope).toEqual(["offenders"]);
656
+ });
657
+
658
+ it("widening lines are surfaced, never hidden (SOT `widens: true`)", () => {
659
+ const r = scope.readSelection(["names", "hiv_status", "immigration_status"], 3, POLICY);
660
+ expect(r.widened).toEqual(["hiv_status", "immigration_status"]);
661
+ expect(r.codes.map((c) => c.widens)).toEqual([false, true, true]);
662
+ expect(scope.readSelection(["immigration_status"], 4, POLICY).widened).toEqual([]);
663
+ expect(migrations.filter((m) => m.widens).map((m) => m.from)).toHaveLength(10);
664
+ });
665
+
666
+ it("a v2-era or unstamped list fails closed: this package ships no v2 → v3 table", () => {
667
+ for (const version of [2, undefined]) {
668
+ for (const options of SUBJECTS) {
669
+ const r = scope.readSelection(["ida_consid", "names", "hiv_status"], version, options);
670
+ expect(r.unsupportedVersion).toBe(true);
671
+ expect(r.informationScope).toEqual([SYS]);
672
+ expect(r.retained).toEqual([]);
673
+ expect(r.widened).toEqual([]);
674
+ expect(r.versionRowRequired).toBe(false);
675
+ }
676
+ }
677
+ });
678
+
679
+ it("each tombstone's restrictionSuccessors equals its table reading as a restriction", () => {
680
+ const withRestriction = sot.entries.filter((e) => e.restrictionSuccessors !== undefined);
681
+ expect(withRestriction.map((e) => e.key)).toEqual(["offender_facilitator"]);
682
+ for (const e of withRestriction) {
683
+ same(
684
+ scope.readRestriction([e.key], 3).informationScope,
685
+ (e.restrictionSuccessors ?? []).map((k) => k.replace(/__/g, ".")),
686
+ );
687
+ }
688
+ });
689
+
690
+ it("a signed list is kept as signed — never mutated, never rewritten", () => {
691
+ const signed = Object.freeze(["names", "hiv_status", "names"]);
692
+ const r = scope.readSelection(signed, 3, RELEASE);
693
+ expect(signed).toEqual(["names", "hiv_status", "names"]);
694
+ expect(r.stored).toEqual(["names", "hiv_status", "names"]);
695
+ expect(r.storedVersion).toBe(3);
696
+ expect(r.version).toBe(4);
697
+ expect(r.codes).toHaveLength(2);
698
+ });
699
+
700
+ it.each([undefined, null, 0, 1, 2, 5, 3.5, Number.NaN, "3"])(
701
+ "reads are total: scopeVersion %j is unsupported, so every code includes nothing",
702
+ (version) => {
703
+ const r = scope.readSelection(["names", "hiv_status"], version as number, POLICY);
704
+ expect(r.unsupportedVersion).toBe(true);
705
+ expect(r.codes.map((c) => c.rule)).toEqual(["unknown", "unknown"]);
706
+ expect(r.informationScope).toEqual([SYS]);
707
+ expect(r.unknown).toEqual(["names", "hiv_status"]);
708
+ expect(scope.readRestriction(["offender_facilitator"], version as number).informationScope).toEqual([]);
709
+ },
710
+ );
711
+
712
+ it("reads are total: a null or missing list reads as empty", () => {
713
+ for (const list of [null, undefined]) {
714
+ const r = scope.readSelection(list, 3, SHARE);
715
+ expect(r.stored).toEqual([]);
716
+ expect(r.informationScope).toEqual([SYS]);
717
+ expect(scope.readRestriction(list, 4).informationScope).toEqual([]);
718
+ expect(scope.isCovered(list, "names")).toBe(false);
719
+ expect(scope.shareVerdict(list, "names")).toEqual({ included: false, reason: "not_covered" });
720
+ expect(scope.clampToCeiling(list, ["identifying"])).toEqual([SYS]);
721
+ expect(scope.expandBranchPickToGrain([SYS, "primary_client"], list)).toEqual(
722
+ expect.arrayContaining([SYS, "primary_client"]),
723
+ );
724
+ }
725
+ });
726
+
727
+ it("every v3-era key (the 73 keys of `_supersedes.keyMap`) reads to a live code or a retired reading", () => {
728
+ // The CVC missingness group has no row in the tree and no line in the table.
729
+ const missingness = new Set(["missingness_root", "unknown", "anonymous", "data_not_collected"]);
730
+ const keys = Object.keys(sot._supersedes.keyMap);
731
+ expect(keys).toHaveLength(73);
732
+ for (const key of keys) {
733
+ expect(scope.readSelection([key], 2, RELEASE).unsupportedVersion).toBe(true);
734
+ for (const options of SUBJECTS) {
735
+ const [reading] = scope.readSelection([key], 3, options).codes;
736
+ if (missingness.has(key)) {
737
+ expect(reading.rule, key).toBe("unknown");
738
+ expect(reading.reads).toEqual([]);
739
+ continue;
740
+ }
741
+ expect(reading.rule, key).not.toBe("unknown");
742
+ for (const to of reading.reads) expect(scope.row(to)?.status, `${key} → ${to}`).not.toBe("retired");
743
+ }
744
+ }
745
+ });
746
+ });
747
+
748
+ // ─── Release grain (Crysta, 2026-10-09; SOT `migrations.ruling`) ──────────
749
+
750
+ describe("release grain — a signed release keeps the grain it was signed at (ruling 2026-10-09)", () => {
751
+ const WIDENING = [
752
+ "chronic_health_status",
753
+ "disability_subtypes",
754
+ "federal_protection_applications",
755
+ "hiv_status",
756
+ "immigration_status",
757
+ "le_report_status",
758
+ "mental_health_status",
759
+ "substance_use_status",
760
+ "tvap_enrollment",
761
+ "uscis_alien_number",
762
+ ];
763
+ /** Canon's nine merge folds (`signed_release_grain: keep`): the identity line is not one. */
764
+ const RETAINED = WIDENING.filter((c) => c !== "immigration_status");
765
+ const entry = (key: string) => sot.entries.find((e) => e.key === key);
766
+
767
+ it("canon's nine merge folds are retained for a release; every widening line is a policy's successor", () => {
768
+ const retain = migrations.filter((m) => m.releaseReading === "retain");
769
+ expect(retain.map((m) => m.from).sort()).toEqual(RETAINED);
770
+ expect(migrations.filter((m) => m.widens).map((m) => m.from).sort()).toEqual(WIDENING);
771
+ expect(
772
+ migrations.filter((m) => m.releaseReading === "successor").map((m) => [m.from, m.rule]),
773
+ ).toEqual([["immigration_status", "identity"]]);
774
+ for (const m of retain) {
775
+ expect(m.policyReading, m.from).toBe("successor");
776
+ expect(m.to, m.from).toHaveLength(1);
777
+ expect(m.v3Fields, m.from).toEqual(entry(m.from)?.v3Fields);
778
+ expect(m.v3Domains, m.from).toEqual(entry(m.from)?.v3Domains);
779
+ }
780
+ const policy = migrations.filter((m) => m.policyReading !== undefined).map((m) => m.from);
781
+ expect(policy.sort()).toEqual(WIDENING);
782
+ });
783
+
784
+ it.each([RELEASE, SHARE])(
785
+ "a v3 %j naming only mental_health_status keeps its v3 fields and never reads health_status",
786
+ (options) => {
787
+ const r = scope.readSelection([SYS, "mental_health_status"], 3, options);
788
+ expect(r.subject).toBe(options.subject);
789
+ expect(r.retained).toEqual([
790
+ {
791
+ code: "mental_health_status",
792
+ v3Fields: ["capture.mental_health_status"],
793
+ v3Domains: ["access_accommodations"],
794
+ successor: "health_status",
795
+ },
796
+ ]);
797
+ expect(r.informationScope).toEqual([SYS]);
798
+ expect(scope.isCovered(r.informationScope, "health_status")).toBe(false);
799
+ expect(r.widened).toEqual([]);
800
+ expect(r.codes[1]).toEqual({
801
+ from: "mental_health_status",
802
+ rule: "row",
803
+ reads: [],
804
+ widens: false,
805
+ retained: true,
806
+ });
807
+ // Still a retired code, still recognisable (§ 3 (c)).
808
+ expect(r.retired).toEqual(["mental_health_status"]);
809
+ expect(r.versionRowRequired).toBe(false);
810
+ expect(r.note).toBeNull();
811
+ },
812
+ );
813
+
814
+ it("the same list as a policy reads health_status, flagged widened, with a dated version row due", () => {
815
+ const r = scope.readSelection([SYS, "mental_health_status"], 3, POLICY);
816
+ same(r.informationScope, [SYS, "health_status"]);
817
+ expect(r.widened).toEqual(["mental_health_status"]);
818
+ expect(r.retained).toEqual([]);
819
+ expect(r.codes[1].retained).toBe(false);
820
+ expect(r.versionRowRequired).toBe(true);
821
+ expect(r.note).toMatch(/new version row on the record, dated/);
822
+ });
823
+
824
+ it.each([RELEASE, SHARE])(
825
+ "immigration_status alone as a %j reads as itself (canon leaves the identity line unmarked)",
826
+ (options) => {
827
+ const r = scope.readSelection([SYS, "immigration_status"], 3, options);
828
+ same(r.informationScope, [SYS, "immigration_status"]);
829
+ expect(r.codes[1]).toMatchObject({ rule: "identity", widens: true, retained: false });
830
+ expect(r.widened).toEqual(["immigration_status"]);
831
+ expect(r.retained).toEqual([]);
832
+ // Both facts stated: the line is mechanically wider (`replacesV3`), and the
833
+ // A-number input was already a v3 control of capture.immigration_status.
834
+ const line = migrations.find((m) => m.from === "immigration_status");
835
+ expect(line?.releaseReadingNote).toMatch(/followed canon/);
836
+ expect(line?.releaseReadingNote).toContain("`uscis_alien_number`");
837
+ expect(line?.releaseReadingNote).toContain("v3 control of `capture.immigration_status`");
838
+ expect(entry("immigration_status")?.v3Fields).toBeUndefined();
839
+ },
840
+ );
841
+
842
+ it("immigration_status alone as a policy reads as itself (identity), flagged widened", () => {
843
+ const r = scope.readSelection([SYS, "immigration_status"], 3, POLICY);
844
+ same(r.informationScope, [SYS, "immigration_status"]);
845
+ expect(r.codes[1]).toMatchObject({ rule: "identity", widens: true, retained: false });
846
+ expect(r.widened).toEqual(["immigration_status"]);
847
+ expect(r.retained).toEqual([]);
848
+ });
849
+
850
+ it.each(["uscis_alien_number", "tvap_enrollment"])(
851
+ "%s homed no v3 field: a release retaining it retains nothing, and says so",
852
+ (code) => {
853
+ const [kept] = scope.readSelection([code], 3, RELEASE).retained;
854
+ expect(kept.v3Fields).toEqual([]);
855
+ expect(kept.v3Domains).toEqual([]);
856
+ expect(kept.note).toMatch(/RETAINS NOTHING/);
857
+ expect(kept.successor).toBe(code === "tvap_enrollment" ? "immigration_applications" : "immigration_status");
858
+ },
859
+ );
860
+
861
+ it("the v3 placements fixture is the pinned projection of canon's file", () => {
862
+ const text = fixtureText(INFOSCOPE_V3_PLACEMENTS.file);
863
+ const head = text.split("\n")[0];
864
+ expect(head).toContain(INFOSCOPE_V3_PLACEMENTS.canonSha);
865
+ expect(head).toContain(INFOSCOPE_V3_PLACEMENTS.canonBlob);
866
+ const { file, projectionBlob } = INFOSCOPE_V3_PLACEMENTS;
867
+ expect(fixtureBodyBlobSha(file)).toBe(projectionBlob);
868
+ expect(Object.keys(loadV3Placements()[0])).toEqual([...INFOSCOPE_V3_PLACEMENTS.columns]);
869
+ same([...INFOSCOPE_V3_PLACEMENTS.units], WIDENING);
870
+ });
871
+
872
+ it("every retained unit's v3Fields / v3Domains equal canon's placements (not a hand-typed copy)", () => {
873
+ const placements = loadV3Placements();
874
+ for (const code of RETAINED) {
875
+ const homed = placements.filter((r) => r.home_unit_today === code);
876
+ const [kept] = scope.readSelection([code], 3, SHARE).retained;
877
+ expect(kept.code, code).toBe(code);
878
+ expect(kept.v3Fields, code).toEqual(homed.map((r) => r.field).sort());
879
+ const domains = [...new Set(homed.map((r) => r.assertion_domain))].sort();
880
+ expect(kept.v3Domains, code).toEqual(domains);
881
+ for (const r of homed) expect(r.home_grain_today, `${code} ${r.field}`).toBe("unit");
882
+ if (homed.length === 0) expect(kept.note, code).toMatch(/RETAINS NOTHING/);
883
+ }
884
+ // The fact the immigration_status note rests on: the A-number input is a v3
885
+ // control of a field homed on immigration_status.
886
+ const aNumber = placements.filter((r) => /\buscis_alien_number\b/.test(r.controls));
887
+ expect(aNumber.map((r) => [r.field, r.home_unit_today])).toEqual([
888
+ ["capture.immigration_status", "immigration_status"],
889
+ ]);
890
+ });
891
+
892
+ it.each([RELEASE, SHARE])(
893
+ "a stamp-3 %j naming any one retained code never covers its successor and widens nothing",
894
+ (options) => {
895
+ for (const code of RETAINED) {
896
+ const successor = migrations.find((m) => m.from === code && m.rule === "row")?.to[0] as string;
897
+ const r = scope.readSelection([SYS, code], 3, options);
898
+ expect(r.retained.map((k) => [k.code, k.successor]), code).toEqual([[code, successor]]);
899
+ expect(scope.isCovered(r.informationScope, successor), code).toBe(false);
900
+ expect(r.widened, code).toEqual([]);
901
+ expect(r.informationScope, code).toEqual([SYS]);
902
+ }
903
+ },
904
+ );
905
+
906
+ it("a category a v3 release named still covers its successor rows (the category was signed)", () => {
907
+ const r = scope.readSelection([SYS, "hiv_status", "health_accommodation"], 3, RELEASE);
908
+ expect(r.retained.map((k) => k.code)).toEqual(["hiv_status"]);
909
+ same(r.informationScope, [SYS, "health_accommodation"]);
910
+ expect(scope.isCovered(r.informationScope, "health_status")).toBe(true);
911
+ });
912
+
913
+ it("a v4-stamped list of live codes reads the same for every subject", () => {
914
+ const list = [SYS, "immigration_status", "health_status", "offender_facilitator"];
915
+ const policy = scope.readSelection(list, 4, POLICY);
916
+ for (const options of [RELEASE, SHARE]) {
917
+ const r = scope.readSelection(list, 4, options);
918
+ expect(r.codes, options.subject).toEqual(policy.codes);
919
+ expect(r.informationScope).toEqual(policy.informationScope);
920
+ expect(r.widened).toEqual(policy.widened);
921
+ expect(r.retained).toEqual([]);
922
+ }
923
+ expect(policy.versionRowRequired).toBe(false);
924
+ expect(policy.note).toBeNull();
925
+ });
926
+
927
+ it("a share carries its release's stamp: frozen under a v3 release it is stamp 3 and retains", () => {
928
+ const share = scope.readSelection([SYS, "hiv_status"], 3, SHARE);
929
+ expect(share.retained.map((k) => k.code)).toEqual(["hiv_status"]);
930
+ expect(scope.isCovered(share.informationScope, "health_status")).toBe(false);
931
+ });
932
+
933
+ it.each([RELEASE, SHARE])(
934
+ "a v4-stamped %j naming a retained tombstone includes nothing — never the successor",
935
+ (options) => {
936
+ for (const code of RETAINED) {
937
+ const r = scope.readSelection([SYS, code], 4, options);
938
+ const successor = migrations.find((m) => m.from === code && m.rule === "row")?.to[0] as string;
939
+ expect(r.codes[1], code).toEqual({
940
+ from: code,
941
+ rule: "row",
942
+ reads: [],
943
+ widens: false,
944
+ retained: false,
945
+ });
946
+ expect(r.informationScope, code).toEqual([SYS]);
947
+ expect(scope.isCovered(r.informationScope, successor), code).toBe(false);
948
+ expect(r.retained, code).toEqual([]);
949
+ expect(r.widened, code).toEqual([]);
950
+ expect(r.retired, code).toEqual([code]);
951
+ // A policy at stamp 4 still reads the table (§ 3 (c)).
952
+ same(scope.readSelection([SYS, code], 4, POLICY).informationScope, [SYS, successor]);
953
+ }
954
+ },
955
+ );
956
+
957
+ it("readRestriction keeps the subtract rule; a stamp-3 restriction is a policy's: version row due", () => {
958
+ const r = scope.readRestriction(["hiv_status", "immigration_status"], 3);
959
+ same(r.informationScope, ["health_status", "immigration_status"]);
960
+ expect(r.subject).toBeNull();
961
+ expect(r.retained).toEqual([]);
962
+ expect(r.versionRowRequired).toBe(true);
963
+ expect(r.note).toMatch(/new version row on the record, dated/);
964
+ const v4 = scope.readRestriction(["health_status"], 4);
965
+ expect([v4.versionRowRequired, v4.note]).toEqual([false, null]);
966
+ expect(scope.readRestriction(["health_status"], 2).versionRowRequired).toBe(false);
967
+ });
968
+
969
+ it("the subject is required: no silent default", () => {
970
+ const read = scope.readSelection as (
971
+ list: readonly string[],
972
+ v: number,
973
+ o?: unknown,
974
+ ) => unknown;
975
+ expect(() => read(["names"], 3)).toThrow(/options.subject/);
976
+ expect(() => read(["names"], 3, {})).toThrow(/options.subject/);
977
+ expect(() => read(["names"], 3, { subject: "preset" })).toThrow(/options.subject/);
978
+ });
979
+
980
+ it("the 17 retired-before-v4 lines are informational; their reading is unchanged (ruling 2)", () => {
981
+ const info = migrations.filter((m) => m.informational === true);
982
+ expect(info).toHaveLength(17);
983
+ expect(info.every((m) => m.rule === "retired before v4")).toBe(true);
984
+ expect(migrations.filter((m) => m.rule === "retired before v4")).toEqual(info);
985
+ for (const options of SUBJECTS) {
986
+ same(scope.readSelection(["lap"], 3, options).informationScope, [SYS, "summary_lap"]);
987
+ }
988
+ });
989
+
990
+ it("binding fails closed on a retained line without its v3 membership", () => {
991
+ const base = rows.filter((r) => r.scopeCode === "system" || r.scopeCode === SYS);
992
+ expect(() =>
993
+ createInformationScopeResolver({
994
+ rows: base,
995
+ migrations: [{ from: "old", to: [SYS], rule: "row", releaseReading: "retain" }],
996
+ }),
997
+ ).toThrow(/needs one successor and its v3Fields/);
998
+ expect(() =>
999
+ createInformationScopeResolver({
1000
+ rows: base,
1001
+ migrations: [
1002
+ {
1003
+ from: "old",
1004
+ to: [SYS, "system"],
1005
+ rule: "row",
1006
+ releaseReading: "retain",
1007
+ v3Fields: [],
1008
+ v3Domains: [],
1009
+ },
1010
+ ],
1011
+ }),
1012
+ ).toThrow(/needs one successor/);
1013
+ expect(() =>
1014
+ createInformationScopeResolver({
1015
+ rows: base,
1016
+ migrations: [{ from: "old", to: [SYS], rule: "row", releaseReading: "keep" as "retain" }],
1017
+ }),
1018
+ ).toThrow(/releaseReading "keep"/);
1019
+ const stripped = {
1020
+ ...sot,
1021
+ entries: sot.entries.map((e) => {
1022
+ if (e.key !== "hiv_status") return e;
1023
+ const { v3Fields: _f, ...rest } = e;
1024
+ return rest;
1025
+ }),
1026
+ };
1027
+ expect(() => scopeMigrationsFromSot(stripped)).toThrow(/"hiv_status" has v3Fields/);
1028
+ });
1029
+ });
1030
+
1031
+ // ─── § 7 row 6: branch-grain pick vs category-grain ceiling ────────────────
1032
+
1033
+ describe("§ 7 row 6 — expand a branch pick to the ceiling's grain before clamping", () => {
1034
+ const ceiling = ["identifying", "contact", "risk", "services", "instrument_summary", "notes"];
1035
+ const pick = [SYS, "primary_client", "notes", "offenders"];
1036
+
1037
+ it("expands primary_client down to the ceiling's grain", () => {
1038
+ same(scope.expandBranchPickToGrain(pick, ceiling), [
1039
+ SYS,
1040
+ "notes",
1041
+ "identifying",
1042
+ "contact",
1043
+ "health_accommodation",
1044
+ "immigration_legal_status",
1045
+ "risk",
1046
+ "services",
1047
+ "instrument_summary",
1048
+ "instrument_full",
1049
+ "relationships_household",
1050
+ "offenders",
1051
+ ]);
1052
+ });
1053
+
1054
+ it("clamps to the ceiling; a sender can never widen", () => {
1055
+ const clamped = scope.clampToCeiling(pick, ceiling);
1056
+ same(clamped, [SYS, "notes", "identifying", "contact", "risk", "services", "instrument_summary"]);
1057
+ for (const c of codes) {
1058
+ if (c === SYS || c === "system" || !scope.isCovered(clamped, c)) continue;
1059
+ expect(scope.isCovered(pick, c), `${c} picked`).toBe(true);
1060
+ expect(scope.isCovered(ceiling, c), `${c} within the ceiling`).toBe(true);
1061
+ }
1062
+ // A literal compare would have let the branch code past the ceiling.
1063
+ expect(ceiling.includes("primary_client")).toBe(false);
1064
+ expect(scope.isCovered(clamped, "health_status")).toBe(false);
1065
+ expect(scope.isCovered(clamped, "offenders.identifying")).toBe(false);
1066
+ });
1067
+
1068
+ it("a pick already inside the ceiling is kept as picked", () => {
1069
+ same(scope.clampToCeiling([SYS, "names"], ["identifying"]), [SYS, "names"]);
1070
+ same(scope.clampToCeiling([SYS, "identifying"], ["names", "dob"]), [SYS, "names", "dob"]);
1071
+ });
1072
+ });
1073
+
1074
+ // ─── Phase 4 § 1 — the seven scenarios ─────────────────────────────────────
1075
+
1076
+ describe("Phase 4 scenarios", () => {
1077
+ it("S1 a minimal release (names + service referrals) delivers the name and the services only", () => {
1078
+ same([...deliver([SYS, "names", "service_history"])], ["jane.names", "jane.services"]);
1079
+ });
1080
+
1081
+ it("S2 the mandated-report packet: the client, the offender whole, the order; not the child", () => {
1082
+ const MANDATED = [
1083
+ ...["names", "dob", "addresses", "screen_indicators", "victimization", "contact_info"],
1084
+ ...["priorities_safety", "encounter_location", "summary_initial_screen", "summary_ae_intake"],
1085
+ ...["summary_ida", "summary_lap", "summary_danger_assessment", "summary_stalking_assessment"],
1086
+ ...["summary_injury_and_strangulation", "offenders", "system_involvement"],
1087
+ ...["session_summary", "case_notes", SYS],
1088
+ ];
1089
+ const got = deliver(MANDATED);
1090
+ for (const id of ["jane.names", "jane.protection_order", "jane.da_summary", "dale.truck"]) {
1091
+ expect(got.has(id), id).toBe(true);
1092
+ }
1093
+ expect(got.has("dale.immigration_status")).toBe(false);
1094
+ expect(
1095
+ scope.shareVerdict(MANDATED, scope.rowForSubject("immigration_status", "offenders")).reason,
1096
+ ).toBe("off_by_default");
1097
+ expect(ids((r) => r.subject === "family").some((id) => got.has(id))).toBe(false);
1098
+ expect(got.has("jane.hiv")).toBe(false);
1099
+ expect(got.has("jane.household_roster")).toBe(false);
1100
+ expect(got.has("jane.da_full")).toBe(false);
1101
+ });
1102
+
1103
+ it("S3 case collaboration (the runner's FULL_COLLAB, enabled = {full_ida})", () => {
1104
+ // tools/infoscope/phase4_stress_test.py main(): FULL_COLLAB, enabled=frozenset({"full_ida"}).
1105
+ const FULL_COLLAB = [
1106
+ ...["names", "dob", "addresses", "demographics", "screen_indicators", "victimization"],
1107
+ ...["summary_initial_screen", "summary_ae_intake", "summary_ida", "summary_lap"],
1108
+ ...["summary_danger_assessment", "summary_stalking_assessment"],
1109
+ ...["summary_injury_and_strangulation", "summary_tra", "summary_hope_scale"],
1110
+ ...["summary_needs_assessment", "full_ida", "contact_info", "priorities_safety"],
1111
+ ...["encounter_location", "contact_history", "service_history", "plans_goals"],
1112
+ ...["session_summary", "case_notes", "relationships_household", "family", SYS],
1113
+ ];
1114
+ const enabled = ["full_ida"];
1115
+ const got = deliver(FULL_COLLAB, enabled);
1116
+ for (const id of ids((r) => r.subject === "family")) expect(got.has(id), id).toBe(true);
1117
+ for (const id of ids((r) => r.subject === "offenders")) expect(got.has(id), id).toBe(false);
1118
+ expect(got.has("jane.household_roster")).toBe(true);
1119
+ expect(got.has("jane.immigration_status")).toBe(false);
1120
+ // The reference verdict: enabling full_ida alone does not enable its off-by-default parent.
1121
+ expect(scope.shareVerdict(FULL_COLLAB, "full_ida", { enabledOffByDefault: enabled })).toEqual({
1122
+ included: false,
1123
+ reason: "off_by_default",
1124
+ notEnabled: ["instrument_full"],
1125
+ });
1126
+ });
1127
+
1128
+ it("S4 offender information to law enforcement: Dale's record, nothing of Jane's", () => {
1129
+ const got = deliver([SYS, "offenders"]);
1130
+ expect(ids((r) => r.subject === "client").filter((id) => got.has(id))).toEqual([]);
1131
+ for (const id of ["dale.names", "dale.offender_status", "dale.tra_run", "dale.record_note"]) {
1132
+ expect(got.has(id), id).toBe(true);
1133
+ }
1134
+ expect(got.has("dale.immigration_status")).toBe(false);
1135
+ // The cohabiting address is Dale's fact under the tree; holding it back is
1136
+ // build rule B-new-1, outside this resolver (handoff § 7 row 4).
1137
+ expect(got.has("dale.address")).toBe(true);
1138
+ });
1139
+
1140
+ it("S5 (the level-1 stub part only): the client's name is in the stub, another person's never", () => {
1141
+ // Canon S5 is a level-3 viewer whitelisted on two categories; the whitelist is
1142
+ // viewing policy outside this resolver. What the tree decides there is the
1143
+ // level-1 stub (rule 7) — asserted here per record.
1144
+ for (const r of CASE.filter((x) => x.home === "names")) {
1145
+ const row = scope.rowForSubject(r.home, r.subject);
1146
+ expect(scope.isVisibleAtLevel(1, row), r.id).toBe(r.subject === "client");
1147
+ }
1148
+ });
1149
+
1150
+ const EVERYTHING = [SYS, "primary_client", "notes", "other_named_persons"];
1151
+
1152
+ it("S6a everything except one note: the tree can only drop Session & case notes whole", () => {
1153
+ const got = deliver(scope.deselectChild(EVERYTHING, "case_notes"), ENABLED_ALL);
1154
+ expect(got.has("jane.case_note_pregnancy")).toBe(false);
1155
+ expect(got.has("jane.session_summary")).toBe(true);
1156
+ expect(got.has("jane.safe_location")).toBe(false);
1157
+ });
1158
+
1159
+ it("S6b everything except one health fact: Health status leaves whole; Accommodation stays", () => {
1160
+ const got = deliver(scope.deselectChild(EVERYTHING, "health_status"), ENABLED_ALL);
1161
+ for (const id of ["jane.hiv", "jane.pregnancy", "jane.mental_health"]) {
1162
+ expect(got.has(id), id).toBe(false);
1163
+ }
1164
+ expect(got.has("jane.accommodations")).toBe(true);
1165
+ expect(got.has("jane.living_situation")).toBe(true);
1166
+ expect(got.has("mika.health")).toBe(true);
1167
+ });
1168
+
1169
+ it("S6c everything except one relative's name: only kinds can be dropped, never a person", () => {
1170
+ const sel = scope.deselectChild(
1171
+ scope.deselectChild(EVERYTHING, "relationships_household"),
1172
+ "others",
1173
+ );
1174
+ const got = deliver(sel, ENABLED_ALL);
1175
+ for (const id of ["maria.names", "tom.names", "jane.household_roster"]) {
1176
+ expect(got.has(id), id).toBe(false);
1177
+ }
1178
+ expect(got.has("jane.ec_designation_maria")).toBe(true);
1179
+ expect(got.has("mika.names")).toBe(true);
1180
+ });
1181
+
1182
+ it("S7 to a partner: 'everything' is clamped at the door to the account's ceiling", () => {
1183
+ const ceiling = ["identifying", "contact", "risk", "services", "instrument_summary", "notes"];
1184
+ const got = deliver(scope.clampToCeiling(EVERYTHING, ceiling), ENABLED_ALL);
1185
+ expect(got.has("jane.names")).toBe(true);
1186
+ expect(got.has("jane.hiv")).toBe(false);
1187
+ expect(got.has("jane.household_roster")).toBe(false);
1188
+ expect(got.has("dale.names")).toBe(false);
1189
+ expect(got.has("jane.da_full")).toBe(false);
1190
+ });
1191
+ });
1192
+
1193
+ // ─── Phase 3 D1 ─────────────────────────────────────────────────────────────
1194
+
1195
+ describe("D1 — the relationship record is the client's; the person's own record rides their kind", () => {
1196
+ it("case 1: Relationships & household alone delivers the roster and no other person's record", () => {
1197
+ same([...deliver([SYS, "relationships_household"])], [
1198
+ "jane.household_roster",
1199
+ "jane.pet",
1200
+ "jane.relationship_dale",
1201
+ ]);
1202
+ });
1203
+
1204
+ it("case 2: Eligible family members alone delivers the child's record, not the roster", () => {
1205
+ same([...deliver([SYS, "family"])], ids((r) => r.subject === "family"));
1206
+ });
1207
+
1208
+ it("Risk-related alone sends nobody's name; People who caused harm alone sends nothing of the client's", () => {
1209
+ const risk = deliver([SYS, "risk"]);
1210
+ expect([...risk].every((id) => id.startsWith("jane."))).toBe(true);
1211
+ expect(risk.has("jane.names")).toBe(false);
1212
+ const harm = deliver([SYS, "offenders"]);
1213
+ expect([...harm].every((id) => id.startsWith("dale."))).toBe(true);
1214
+ });
1215
+ });
1216
+
1217
+ // ─── Tree validation and retired rows ──────────────────────────────────────
1218
+
1219
+ describe("construction", () => {
1220
+ const base = rows.filter((r) => r.scopeCode === "system" || r.scopeCode === SYS);
1221
+
1222
+ it("throws on a malformed tree or table", () => {
1223
+ expect(() => createInformationScopeResolver({ rows: [...base, base[1]] })).toThrow(/duplicate/);
1224
+ expect(() =>
1225
+ createInformationScopeResolver({
1226
+ rows: [...base, { ...base[1], scopeCode: "x", parentScopeCode: "y" }],
1227
+ }),
1228
+ ).toThrow(/unknown parent/);
1229
+ expect(() =>
1230
+ createInformationScopeResolver({ rows: base.filter((r) => r.scopeCode !== SYS) }),
1231
+ ).toThrow(/system_info/);
1232
+ expect(() =>
1233
+ createInformationScopeResolver({
1234
+ rows: base,
1235
+ migrations: [{ from: "old", to: ["missing"], rule: "row" }],
1236
+ }),
1237
+ ).toThrow(/not a live row/);
1238
+ expect(() =>
1239
+ createInformationScopeResolver({
1240
+ rows: base,
1241
+ migrations: [
1242
+ { from: "old", to: ["system"], rule: "row" },
1243
+ { from: "old", to: [SYS], rule: "row" },
1244
+ ],
1245
+ }),
1246
+ ).toThrow(/two "row" readings/);
1247
+ const noKindRow = rows.map((r) => {
1248
+ if (r.scopeCode !== "family.risk") return r;
1249
+ const { kindRow: _drop, ...rest } = r;
1250
+ return rest;
1251
+ });
1252
+ expect(() => createInformationScopeResolver({ rows: noKindRow })).toThrow(/kindRow/);
1253
+ });
1254
+
1255
+ it("a retired tombstone row is never covered, offered, expanded or written", () => {
1256
+ const withTombstone = createInformationScopeResolver({
1257
+ rows: [
1258
+ ...rows,
1259
+ {
1260
+ ...(scope.row("health_status") as ScopeRow),
1261
+ scopeCode: "hiv_status",
1262
+ status: "retired",
1263
+ selectable: false,
1264
+ },
1265
+ ],
1266
+ migrations,
1267
+ });
1268
+ same(withTombstone.childrenOf("health_accommodation"), ["health_status", "accommodation_needs"]);
1269
+ expect(withTombstone.isCovered([SYS, "primary_client"], "hiv_status")).toBe(false);
1270
+ expect(withTombstone.isIncludedOnShare([SYS, "hiv_status"], "hiv_status")).toBe(false);
1271
+ expect(withTombstone.isVisibleAtLevel(3, "hiv_status")).toBe(false);
1272
+ same(withTombstone.deselectChild([SYS, "health_accommodation"], "accommodation_needs"), [
1273
+ SYS,
1274
+ "health_status",
1275
+ ]);
1276
+ expect(withTombstone.readSelection(["hiv_status"], 4, RELEASE).codes[0].rule).toBe("row");
1277
+ });
1278
+ });