@htilabs/platform-common-models 0.23.0 → 0.24.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 (61) hide show
  1. package/README.md +39 -0
  2. package/dist/authz/index.cjs +143 -12
  3. package/dist/authz/index.cjs.map +1 -1
  4. package/dist/authz/index.d.cts +121 -12
  5. package/dist/authz/index.d.ts +121 -12
  6. package/dist/authz/index.js +136 -12
  7. package/dist/authz/index.js.map +1 -1
  8. package/dist/constants/index.cjs +30 -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 +26 -0
  13. package/dist/constants/index.js.map +1 -1
  14. package/dist/{cvcEntry-0BIB9sen.d.cts → cvcEntry-BqAGctqK.d.cts} +4 -1
  15. package/dist/{cvcEntry-0BIB9sen.d.ts → cvcEntry-BqAGctqK.d.ts} +4 -1
  16. package/dist/{index-Zu_mOJRn.d.cts → index-BTqHP4DM.d.cts} +1 -1
  17. package/dist/{index-CDoqrfc1.d.ts → index-Dr6GBCoY.d.ts} +1 -1
  18. package/dist/index.cjs +147 -13
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +4 -4
  21. package/dist/index.d.ts +4 -4
  22. package/dist/index.js +140 -13
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.cjs +26 -1
  25. package/dist/models/index.cjs.map +1 -1
  26. package/dist/models/index.d.cts +2 -2
  27. package/dist/models/index.d.ts +2 -2
  28. package/dist/models/index.js +26 -1
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{platform-auth-B49Ly57B.d.cts → platform-auth-DJO-r9Pf.d.cts} +48 -1
  31. package/dist/{platform-auth-B49Ly57B.d.ts → platform-auth-DJO-r9Pf.d.ts} +48 -1
  32. package/dist/schemas/index.cjs +26 -1
  33. package/dist/schemas/index.cjs.map +1 -1
  34. package/dist/schemas/index.d.cts +1 -1
  35. package/dist/schemas/index.d.ts +1 -1
  36. package/dist/schemas/index.js +26 -1
  37. package/dist/schemas/index.js.map +1 -1
  38. package/dist/services/index.cjs +26 -1
  39. package/dist/services/index.cjs.map +1 -1
  40. package/dist/services/index.js +26 -1
  41. package/dist/services/index.js.map +1 -1
  42. package/dist/types/index.d.cts +11 -3
  43. package/dist/types/index.d.ts +11 -3
  44. package/dist/validation/index.cjs +22 -0
  45. package/dist/validation/index.cjs.map +1 -1
  46. package/dist/validation/index.js +22 -0
  47. package/dist/validation/index.js.map +1 -1
  48. package/package.json +1 -1
  49. package/src/__sot__/README.md +1 -1
  50. package/src/__sot__/coreFunctionFields.ts +88 -4
  51. package/src/__sot__/coreFunctions.pin.json +1040 -113
  52. package/src/__tests__/authz-resolve.test.ts +115 -31
  53. package/src/__tests__/core-function-default-bounds.test.ts +374 -0
  54. package/src/__tests__/core-functions-case-close.test.ts +82 -0
  55. package/src/authz/defaultBounds.ts +69 -0
  56. package/src/authz/index.ts +12 -3
  57. package/src/authz/resolveEffectiveFunctions.ts +69 -29
  58. package/src/constants/platform-auth.ts +60 -0
  59. package/src/generated/coreFunctionDefaultBounds.ts +109 -0
  60. package/src/schemas/platform-role.ts +4 -1
  61. package/src/types/platform-auth.ts +9 -2
@@ -32,14 +32,14 @@ import {
32
32
  // SUP and NEVER for CIRO; `usr_manage` is MEM-ADM only; `session_create` is
33
33
  // PREF_NO for SUP and PREF_YES for CIRO.
34
34
  const functions = [
35
- { code: "case_edit", tools: ["THREAD"] },
36
- { code: "usr_manage", tools: ["THREAD"] },
37
- { code: "session_create", tools: ["THREAD"] },
35
+ { code: "case_edit" },
36
+ { code: "usr_manage" },
37
+ { code: "session_create" },
38
38
  ];
39
39
  const roles = [
40
- { code: "SUP", tools: ["THREAD"], functions: { case_edit: "ALWAYS", session_create: "PREF_NO" } },
41
- { code: "CIRO", tools: ["THREAD"], functions: { case_edit: "NEVER", session_create: "PREF_YES" } },
42
- { code: "MEM-ADM", tools: ["THREAD"], functions: { usr_manage: "ALWAYS" } },
40
+ { code: "SUP", functions: { case_edit: "ALWAYS", session_create: "PREF_NO" } },
41
+ { code: "CIRO", functions: { case_edit: "NEVER", session_create: "PREF_YES" } },
42
+ { code: "MEM-ADM", functions: { usr_manage: "ALWAYS" } },
43
43
  ] as const;
44
44
 
45
45
  const input = (
@@ -259,8 +259,8 @@ describe("§ 4.1 extras", () => {
259
259
  it("rule 8: a canon-unknown code is denied even when the caller's catalog lists it with a v1-looking row", () => {
260
260
  // ida_conduct is in the platform seed (cvcRoles.js) but not in CVC-133.
261
261
  const fns = resolve({
262
- functions: [...functions, { code: "ida_conduct", tools: ["THREAD"] }],
263
- roles: [{ code: "SUP", tools: ["THREAD"], functions: { ida_conduct: "ALWAYS", case_edit: "ALWAYS" } }],
262
+ functions: [...functions, { code: "ida_conduct" }],
263
+ roles: [{ code: "SUP", functions: { ida_conduct: "ALWAYS", case_edit: "ALWAYS" } }],
264
264
  assignedRoleCodes: ["SUP"],
265
265
  });
266
266
  expect(isCanonEvaluableFunction("ida_conduct")).toBe(false);
@@ -270,11 +270,10 @@ describe("§ 4.1 extras", () => {
270
270
  it("rule 8: canon not-v1 codes are denied even with no status on the caller's row (break_glass, thread_share_send, share_approve)", () => {
271
271
  const notV1 = ["break_glass", "thread_share_send", "share_approve"];
272
272
  const fns = resolve({
273
- functions: notV1.map((code) => ({ code, tools: ["PLATFORM"] })),
273
+ functions: notV1.map((code) => ({ code })),
274
274
  roles: [
275
275
  {
276
276
  code: "PLT-ADM",
277
- tools: ["PLATFORM"],
278
277
  functions: { break_glass: "ALWAYS", thread_share_send: "ALWAYS", share_approve: "ALWAYS" },
279
278
  },
280
279
  ],
@@ -289,12 +288,11 @@ describe("§ 4.1 extras", () => {
289
288
  // canon says v1. The caller's status is not read.
290
289
  const staleRow = {
291
290
  code: "platform_perm_modify",
292
- tools: ["PLATFORM"],
293
291
  status: "Future function (not v1)",
294
292
  };
295
293
  const fns = resolve({
296
294
  functions: [staleRow],
297
- roles: [{ code: "PLT-ADM", tools: ["PLATFORM"], functions: { platform_perm_modify: "ALWAYS" } }],
295
+ roles: [{ code: "PLT-ADM", functions: { platform_perm_modify: "ALWAYS" } }],
298
296
  assignedRoleCodes: ["PLT-ADM"],
299
297
  });
300
298
  expect(fns).toEqual(["platform_perm_modify"]);
@@ -305,8 +303,8 @@ describe("§ 4.1 extras", () => {
305
303
  // the SOT itself (every entry with retired: true is never evaluable).
306
304
  const fns = resolve({
307
305
  functions: [
308
- { code: "case_edit", tools: ["THREAD"], retired: true },
309
- { code: "session_create", tools: ["THREAD"], retired: false },
306
+ { code: "case_edit", retired: true },
307
+ { code: "session_create", retired: false },
310
308
  ],
311
309
  assignedRoleCodes: ["SUP", "CIRO"],
312
310
  });
@@ -320,8 +318,8 @@ describe("§ 4.1 extras", () => {
320
318
  expect(isCanonEvaluableFunction(k), k).toBe(false);
321
319
  expect(
322
320
  resolve({
323
- functions: [{ code: "unknown", tools: ["THREAD"] }],
324
- roles: [{ code: "SUP", tools: ["THREAD"], functions: { unknown: "ALWAYS" } }],
321
+ functions: [{ code: "unknown" }],
322
+ roles: [{ code: "SUP", functions: { unknown: "ALWAYS" } }],
325
323
  assignedRoleCodes: ["SUP"],
326
324
  }),
327
325
  ).toEqual([]);
@@ -336,19 +334,106 @@ describe("§ 4.1 extras", () => {
336
334
  }
337
335
  });
338
336
 
339
- it("tier 1: an unlisted function defaults to PREF_NO when it shares a tool, NEVER when it does not", () => {
337
+ it("tier 1: an UNLISTED function is unbound — the role is ineligible, shared tool or not (co-p1x, canon role_ineligible)", () => {
338
+ // Before co-p1x a shared tool made an unlisted function PREF_NO, which this
339
+ // agency override lifted to a grant of session_create. Canon
340
+ // (`agencyhub.jsx:578-584`) stops an unbound role before the agency layer.
340
341
  const fns = resolve({
341
342
  functions: [...functions, { code: "lead_create", tools: ["LEADS"] }],
342
343
  roles: [{ code: "SUP", tools: ["THREAD"], functions: {} }],
343
344
  assignedRoleCodes: ["SUP"],
344
345
  agencyOverrides: { SUP: { session_create: "PREF_YES", lead_create: "PREF_YES" } },
345
346
  });
346
- expect(fns).toEqual(["session_create"]); // lead_create is N/A for SUP: NEVER, locked
347
+ expect(fns).toEqual([]);
348
+ });
349
+
350
+ it("unbound + an agency PREF_YES or ALWAYS override is still denied (tools are not read)", () => {
351
+ for (const override of ["PREF_YES", "ALWAYS"] as const) {
352
+ for (const tools of [["THREAD"], ["LEADS"], [], undefined]) {
353
+ expect(
354
+ resolve({
355
+ roles: [{ code: "SUP", tools, functions: { case_edit: "ALWAYS" } }],
356
+ assignedRoleCodes: ["SUP"],
357
+ agencyOverrides: { SUP: { session_create: override, usr_manage: override } },
358
+ }),
359
+ `${override} / tools ${JSON.stringify(tools)}`,
360
+ ).toEqual(["case_edit"]);
361
+ }
362
+ }
363
+ // A role row with no functions map at all is unbound for everything.
364
+ expect(
365
+ resolve({
366
+ roles: [{ code: "SUP", tools: ["THREAD"] }],
367
+ assignedRoleCodes: ["SUP"],
368
+ agencyOverrides: { SUP: { session_create: "ALWAYS" } },
369
+ }),
370
+ ).toEqual([]);
371
+ });
372
+
373
+ it("unbound + a team policy (flat or role-grain PREF_YES / ALWAYS) is still denied", () => {
374
+ const team: AuthzTeamPolicy = {
375
+ functions: { session_create: "ALWAYS", usr_manage: "PREF_YES" },
376
+ roles: [{ roleCode: "SUP", overrides: { session_create: "PREF_YES", usr_manage: "ALWAYS" } }],
377
+ };
378
+ expect(
379
+ resolve({
380
+ roles: [{ code: "SUP", functions: { case_edit: "ALWAYS" } }],
381
+ assignedRoleCodes: ["SUP"],
382
+ agencyOverrides: { SUP: { session_create: "PREF_YES" } },
383
+ teamPolicy: team,
384
+ }),
385
+ ).toEqual(["case_edit"]);
386
+ });
387
+
388
+ it("unbound is local to its role: another held role's grant stands (rule 2)", () => {
389
+ // MEM-ADM lists only usr_manage; CIRO's PREF_YES session_create and SUP's
390
+ // ALWAYS case_edit are still granted to the seat holding all three.
391
+ expect(resolve({ assignedRoleCodes: ["MEM-ADM"] })).toEqual(["usr_manage"]);
392
+ expect(resolve()).toEqual(["case_edit", "session_create", "usr_manage"]);
393
+ });
394
+
395
+ it("Required (ALWAYS) still grants: an agency cannot lower it, a team cannot restrict it", () => {
396
+ expect(
397
+ resolve({
398
+ assignedRoleCodes: ["SUP"],
399
+ agencyOverrides: { SUP: { case_edit: "NEVER" } },
400
+ teamPolicy: { functions: { case_edit: "NEVER" }, roles: [{ roleCode: "SUP", overrides: { case_edit: "PREF_NO" } }] },
401
+ }),
402
+ ).toEqual(["case_edit"]);
403
+ });
404
+
405
+ it("a stored NA (codebook 'Not relevant') reads NEVER at every tier", () => {
406
+ const NA = "NA" as const;
407
+ // Tier 1 NA: locked — the agency cannot lift it.
408
+ expect(
409
+ resolve({
410
+ roles: [{ code: "CIRO", functions: { session_create: NA } }],
411
+ assignedRoleCodes: ["CIRO"],
412
+ agencyOverrides: { CIRO: { session_create: "ALWAYS" } },
413
+ }),
414
+ ).toEqual([]);
415
+ // Tier 2 / Tier 3 types have no NA (canon has no NA chip there); stored
416
+ // data can still carry one, and it must deny, never grant.
417
+ // Tier 2 NA over a platform PREF_YES: denied for that role.
418
+ expect(
419
+ resolve({ assignedRoleCodes: ["CIRO"], agencyOverrides: { CIRO: { session_create: NA as never } } }),
420
+ ).toEqual([]);
421
+ // Tier 3 NA restricts a team-gated grant, but not Required.
422
+ expect(
423
+ resolve({ assignedRoleCodes: ["CIRO", "SUP"], teamPolicy: { functions: { session_create: NA as never, case_edit: NA as never } } }),
424
+ ).toEqual(["case_edit"]);
425
+ // NA is local to its role (rule 2): SUP's ALWAYS case_edit survives CIRO's NA.
426
+ expect(
427
+ resolve({
428
+ roles: [roles[0], { code: "CIRO", functions: { case_edit: NA } }],
429
+ assignedRoleCodes: ["CIRO", "SUP"],
430
+ }),
431
+ ).toEqual(["case_edit"]);
347
432
  });
348
433
 
349
434
  it("malformed Tier-1 state fails closed: a bad stored value is NEVER for that role", () => {
350
435
  const fns = resolve({
351
- roles: [{ code: "SUP", tools: ["THREAD"], functions: { case_edit: "yes" as never } }],
436
+ roles: [{ code: "SUP", functions: { case_edit: "yes" as never } }],
352
437
  assignedRoleCodes: ["SUP"],
353
438
  });
354
439
  expect(fns).toEqual([]);
@@ -411,6 +496,8 @@ describe("§ 4.1 extras", () => {
411
496
  "../constants/platform-auth.js",
412
497
  "../generated/cvc-enums.js",
413
498
  "../generated/coreFunctionsEvaluable.js",
499
+ "./defaultBounds.js",
500
+ "../generated/coreFunctionDefaultBounds.js",
414
501
  ]),
415
502
  );
416
503
  });
@@ -497,17 +584,17 @@ describe("§ 4.1 extras", () => {
497
584
  for (const retired of ["true", "false", 1, 0, null, {}]) {
498
585
  expect(
499
586
  resolve({
500
- functions: [{ code: "session_create", tools: ["THREAD"], retired: retired as never }],
587
+ functions: [{ code: "session_create", retired: retired as never }],
501
588
  assignedRoleCodes: ["CIRO"],
502
589
  }),
503
590
  `retired = ${JSON.stringify(retired)}`,
504
591
  ).toEqual([]);
505
592
  }
506
593
  expect(
507
- resolve({ functions: [{ code: "session_create", tools: ["THREAD"], retired: false }], assignedRoleCodes: ["CIRO"] }),
594
+ resolve({ functions: [{ code: "session_create", retired: false }], assignedRoleCodes: ["CIRO"] }),
508
595
  ).toEqual(["session_create"]);
509
596
  expect(
510
- resolve({ functions: [{ code: "session_create", tools: ["THREAD"] }], assignedRoleCodes: ["CIRO"] }),
597
+ resolve({ functions: [{ code: "session_create" }], assignedRoleCodes: ["CIRO"] }),
511
598
  ).toEqual(["session_create"]);
512
599
  });
513
600
 
@@ -522,7 +609,7 @@ describe("§ 4.1 extras", () => {
522
609
  // a role whose stored functions container is malformed grants nothing
523
610
  expect(
524
611
  resolve({
525
- roles: [{ code: "CIRO", tools: ["THREAD"], functions: ["session_create"] as never }],
612
+ roles: [{ code: "CIRO", functions: ["session_create"] as never }],
526
613
  assignedRoleCodes: ["CIRO"],
527
614
  }),
528
615
  ).toEqual([]);
@@ -550,8 +637,8 @@ describe("§ 4.1 extras", () => {
550
637
  expect(
551
638
  resolve({
552
639
  roles: [
553
- { code: "C", tools: ["THREAD"], functions: { session_create: "ALWAYS" } },
554
- { code: "I", tools: ["THREAD"], functions: { session_create: "ALWAYS" } },
640
+ { code: "C", functions: { session_create: "ALWAYS" } },
641
+ { code: "I", functions: { session_create: "ALWAYS" } },
555
642
  ],
556
643
  assignedRoleCodes: "CIRO" as never,
557
644
  }),
@@ -609,9 +696,9 @@ describe("§ 4.1 extras", () => {
609
696
 
610
697
  describe("effective viewing level (CVC-133 viewing_level_1/2/3 logic_notes)", () => {
611
698
  const vFunctions = [
612
- { code: "viewing_level_1_search", tools: ["PAVE"] },
613
- { code: "viewing_level_2_autocomplete", tools: ["PAVE"] },
614
- { code: "viewing_level_3_components", tools: ["PAVE"] },
699
+ { code: "viewing_level_1_search" },
700
+ { code: "viewing_level_2_autocomplete" },
701
+ { code: "viewing_level_3_components" },
615
702
  ];
616
703
  // Bounds excerpt from canon (records data/cvcs/core_functions.yaml @ f4356aa4):
617
704
  // case_nav L1/L2 Always, L3 Default-On; legal_advocate L1 Default-On, L2/L3
@@ -619,7 +706,6 @@ describe("effective viewing level (CVC-133 viewing_level_1/2/3 logic_notes)", ()
619
706
  const vRoles = [
620
707
  {
621
708
  code: "case_nav",
622
- tools: ["PAVE"],
623
709
  functions: {
624
710
  viewing_level_1_search: "ALWAYS",
625
711
  viewing_level_2_autocomplete: "ALWAYS",
@@ -628,7 +714,6 @@ describe("effective viewing level (CVC-133 viewing_level_1/2/3 logic_notes)", ()
628
714
  },
629
715
  {
630
716
  code: "legal_advocate",
631
- tools: ["PAVE"],
632
717
  functions: {
633
718
  viewing_level_1_search: "PREF_YES",
634
719
  viewing_level_2_autocomplete: "PREF_NO",
@@ -637,7 +722,6 @@ describe("effective viewing level (CVC-133 viewing_level_1/2/3 logic_notes)", ()
637
722
  },
638
723
  {
639
724
  code: "volunteer",
640
- tools: ["PAVE"],
641
725
  functions: {
642
726
  viewing_level_1_search: "PREF_NO",
643
727
  viewing_level_2_autocomplete: "NEVER",
@@ -0,0 +1,374 @@
1
+ /**
2
+ * CORE FUNCTIONS (CVC-133) — GATE L: the codebook default bounds restate canon
3
+ * ============================================================================
4
+ *
5
+ * `src/generated/coreFunctionDefaultBounds.ts` is GENERATED from canon's
6
+ * `bounds:` blocks (`htilabstech/prototype` `data/cvcs/core_functions.yaml`) by
7
+ * `scripts/gen-core-functions.py` (co-p1x). This test is the hermetic enforcer:
8
+ * the map equals the bounds projection in `src/__sot__/coreFunctions.pin.json`
9
+ * (taken by `scripts/sot-pins.ts` through `projectBounds`), for exactly the
10
+ * evaluable functions, and every role code it names is a CVC-134 / CVC-135
11
+ * `canonicalCode` the package ships. `gen-core-functions.py --check` and
12
+ * `sot:pins:check` are the detectors for canon moving.
13
+ *
14
+ * These are CODEBOOK DEFAULTS (what platform seeds, what "clear" reverts to),
15
+ * not live policy: the live role × function bounds are platform policy state
16
+ * (KICKOFF_SHARED_AUTHZ_RESOLVER_2026-10-12 § 3 rule 7).
17
+ */
18
+ import { readFileSync, readdirSync } from "node:fs";
19
+ import path from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { describe, it, expect } from "vitest";
22
+
23
+ import {
24
+ CORE_FUNCTION_DEFAULT_BOUNDS,
25
+ CORE_FUNCTION_DEFAULT_BOUNDS_SOT_VERSION,
26
+ DEFAULT_BOUND_STATE,
27
+ DEFAULT_BOUND_STATE_VALUES,
28
+ codebookDefaultBound,
29
+ resolveEffectiveFunctions,
30
+ } from "../authz/index.js";
31
+ import * as root from "../index.js";
32
+ import { PERMISSION_STATE_VALUES } from "../constants/platform-auth.js";
33
+ import type { DefaultBoundStateValue, PermissionStateValue } from "../constants/platform-auth.js";
34
+ import { CORE_FUNCTIONS_EVALUABLE_KEYS } from "../generated/coreFunctionsEvaluable.js";
35
+ import { projectBounds } from "../__sot__/coreFunctionFields.js";
36
+ import type { ProjectedFunctionFields } from "../__sot__/coreFunctionFields.js";
37
+
38
+ const here = path.dirname(fileURLToPath(import.meta.url));
39
+ const read = <T>(...p: string[]): T =>
40
+ JSON.parse(readFileSync(path.join(here, "..", ...p), "utf8")) as T;
41
+
42
+ const SOT_VERSION = "1.3.0";
43
+ const pin = read<{ keys: string[]; fields: Record<string, ProjectedFunctionFields> }>(
44
+ "__sot__",
45
+ "coreFunctions.pin.json",
46
+ );
47
+ type RoleSot = { entries: { key: string; canonicalCode: string; selectable: boolean }[] };
48
+ const semver = (f: string): number[] =>
49
+ (/\.v(\d+)\.(\d+)\.(\d+)\.json$/.exec(f)?.slice(1) ?? ["0", "0", "0"]).map(Number);
50
+ /**
51
+ * The highest committed `<stem>.v*.json`, chosen exactly as the generator's
52
+ * `role_codes` does (glob, numeric semver sort, last) — never a hard-coded
53
+ * version, so a role SOT bump cannot leave GATE L reading a stale file.
54
+ */
55
+ const highestSot = (stem: string): string => {
56
+ const files = readdirSync(path.join(here, "..", "cvcs"))
57
+ .filter((f) => f.startsWith(`${stem}.v`) && f.endsWith(".json"))
58
+ .sort((a, b) => {
59
+ const [x, y] = [semver(a), semver(b)];
60
+ return x[0]! - y[0]! || x[1]! - y[1]! || x[2]! - y[2]!;
61
+ });
62
+ if (files.length === 0) throw new Error(`no committed ${stem}.v*.json`);
63
+ return files.at(-1)!;
64
+ };
65
+ /** A role SOT's live canonical codes (the generator ignores a withdrawn row too). */
66
+ const liveCodes = (file: string): Set<string> =>
67
+ new Set(
68
+ read<RoleSot>("cvcs", file)
69
+ .entries.filter((e) => e.selectable)
70
+ .map((e) => e.canonicalCode),
71
+ );
72
+ const adminCodes = liveCodes(highestSot("adminRoles"));
73
+ const userCodes = liveCodes(highestSot("userRoles"));
74
+
75
+ const evaluableFromPin = pin.keys.filter((k) => pin.fields[k]!.v1 && !pin.fields[k]!.retired);
76
+
77
+ describe("core_functions — GATE L: codebook default bounds restate canon (CVC-133 @ the pin)", () => {
78
+ it("is stamped with the SOT version and covers exactly the evaluable functions", () => {
79
+ expect(CORE_FUNCTION_DEFAULT_BOUNDS_SOT_VERSION).toBe(SOT_VERSION);
80
+ expect(Object.keys(CORE_FUNCTION_DEFAULT_BOUNDS)).toEqual([...CORE_FUNCTIONS_EVALUABLE_KEYS]);
81
+ expect(Object.keys(CORE_FUNCTION_DEFAULT_BOUNDS)).toEqual(evaluableFromPin);
82
+ });
83
+
84
+ it("equals the pinned canon bounds, function by function", () => {
85
+ const bad: string[] = [];
86
+ for (const k of evaluableFromPin) {
87
+ const want = pin.fields[k]!.bounds;
88
+ const got = CORE_FUNCTION_DEFAULT_BOUNDS[k];
89
+ if (JSON.stringify(got) !== JSON.stringify(want))
90
+ bad.push(`${k}: ${JSON.stringify(got)} != canon ${JSON.stringify(want)}`);
91
+ }
92
+ expect(bad).toEqual([]);
93
+ });
94
+
95
+ it("names only role codes the package ships (CVC-134 ∪ CVC-135 canonicalCode), in every canon row", () => {
96
+ expect([...adminCodes].filter((c) => userCodes.has(c)), "the two axes are disjoint").toEqual([]);
97
+ const unknown: string[] = [];
98
+ for (const k of pin.keys)
99
+ for (const role of Object.keys(pin.fields[k]!.bounds))
100
+ if (!adminCodes.has(role) && !userCodes.has(role)) unknown.push(`${k}: ${role}`);
101
+ for (const [k, roles] of Object.entries(CORE_FUNCTION_DEFAULT_BOUNDS))
102
+ for (const role of Object.keys(roles))
103
+ if (!adminCodes.has(role) && !userCodes.has(role)) unknown.push(`generated ${k}: ${role}`);
104
+ expect(unknown).toEqual([]);
105
+ });
106
+
107
+ it("uses only the five codebook states (the four PERMISSION_STATE values + NA)", () => {
108
+ expect([...DEFAULT_BOUND_STATE_VALUES]).toEqual([...PERMISSION_STATE_VALUES, "NA"]);
109
+ const states = new Set(DEFAULT_BOUND_STATE_VALUES as readonly string[]);
110
+ const bad = Object.entries(CORE_FUNCTION_DEFAULT_BOUNDS).flatMap(([k, roles]) =>
111
+ Object.entries(roles)
112
+ .filter(([, s]) => !states.has(s))
113
+ .map(([r, s]) => `${k}.${r}: ${s}`),
114
+ );
115
+ expect(bad).toEqual([]);
116
+ });
117
+
118
+ it("spot checks against canon (records data/cvcs/core_functions.yaml @ f4356aa4)", () => {
119
+ // :38 agency_info_manage — always MEM-ADM, PLT-ADM; default_on TEAM-ADM.
120
+ expect(CORE_FUNCTION_DEFAULT_BOUNDS["agency_info_manage"]).toEqual({
121
+ "MEM-ADM": "ALWAYS",
122
+ "PLT-ADM": "ALWAYS",
123
+ "TEAM-ADM": "PREF_YES",
124
+ });
125
+ // :68 note_open_departed_author — Default Off for Account Admin, no other role.
126
+ expect(CORE_FUNCTION_DEFAULT_BOUNDS["note_open_departed_author"]).toEqual({
127
+ "MEM-ADM": "PREF_NO",
128
+ });
129
+ // :3809 auth_model_manage_platform — PLT-ADM always, every other admin never,
130
+ // research_analytics not applicable; no other user role is named (unbound).
131
+ expect(codebookDefaultBound("auth_model_manage_platform", "PLT-ADM")).toBe("ALWAYS");
132
+ expect(codebookDefaultBound("auth_model_manage_platform", "MEM-ADM")).toBe("NEVER");
133
+ expect(codebookDefaultBound("auth_model_manage_platform", "research_analytics")).toBe(
134
+ DEFAULT_BOUND_STATE.NA,
135
+ );
136
+ expect(codebookDefaultBound("auth_model_manage_platform", "case_nav")).toBeNull();
137
+ // :3018 audit_log_view_team — not v1 and has no bounds: not in the map.
138
+ expect(pin.fields["audit_log_view_team"]!.v1).toBe(false);
139
+ expect(codebookDefaultBound("audit_log_view_team", "PLT-ADM")).toBeNull();
140
+ });
141
+
142
+ it("codebookDefaultBound: unbound, unknown and inherited names are null", () => {
143
+ expect(codebookDefaultBound("agency_info_manage", "case_nav")).toBeNull();
144
+ expect(codebookDefaultBound("not_a_function", "MEM-ADM")).toBeNull();
145
+ expect(codebookDefaultBound("constructor", "MEM-ADM")).toBeNull();
146
+ expect(codebookDefaultBound("agency_info_manage", "toString")).toBeNull();
147
+ expect(codebookDefaultBound("__proto__", "__proto__")).toBeNull();
148
+ });
149
+
150
+ it("ships from the package root and the browser-safe ./authz entry", () => {
151
+ expect(root.CORE_FUNCTION_DEFAULT_BOUNDS).toBe(CORE_FUNCTION_DEFAULT_BOUNDS);
152
+ expect(root.codebookDefaultBound).toBe(codebookDefaultBound);
153
+ expect(root.DEFAULT_BOUND_STATE).toBe(DEFAULT_BOUND_STATE);
154
+ });
155
+
156
+ it("UNBOUND means ineligible, even with an agency override or a team policy (canon role_ineligible)", () => {
157
+ // auth_model_manage_platform leaves case_nav unbound. Seed Tier 1 from the
158
+ // codebook (bound states only): no agency or team value, and no shared
159
+ // tool, makes case_nav eligible (platform-prototype agencyhub.jsx:578-584).
160
+ const fn = "auth_model_manage_platform";
161
+ expect(codebookDefaultBound(fn, "case_nav")).toBeNull();
162
+ for (const override of [undefined, "PREF_YES", "ALWAYS"] as const) {
163
+ for (const teamPolicy of [undefined, { functions: { [fn]: "ALWAYS" as const } }]) {
164
+ const got = resolveEffectiveFunctions({
165
+ roles: [{ code: "case_nav", tools: ["PLATFORM"], functions: {} }],
166
+ functions: [{ code: fn, tools: ["PLATFORM"] }],
167
+ assignedRoleCodes: ["case_nav"],
168
+ agencyOverrides: override ? { case_nav: { [fn]: override } } : undefined,
169
+ teamPolicy,
170
+ unknownFunctionPolicy: "deny",
171
+ });
172
+ expect(got, `agency ${override} / team ${JSON.stringify(teamPolicy)}`).toEqual([]);
173
+ }
174
+ }
175
+ // ...while the codebook's ALWAYS role, seeded, resolves it.
176
+ expect(
177
+ resolveEffectiveFunctions({
178
+ roles: [{ code: "PLT-ADM", tools: ["PLATFORM"], functions: { [fn]: "ALWAYS" } }],
179
+ functions: [{ code: fn, tools: ["PLATFORM"] }],
180
+ assignedRoleCodes: ["PLT-ADM"],
181
+ unknownFunctionPolicy: "deny",
182
+ }),
183
+ ).toEqual([fn]);
184
+ });
185
+ });
186
+
187
+ // ─── Property: the resolver against a canon oracle ──────────────────────────
188
+
189
+ type Seed = DefaultBoundStateValue | null; // null = unbound (no stored state)
190
+ type Gate = PermissionStateValue | "NA" | undefined; // a stored agency / team value
191
+
192
+ /**
193
+ * The oracle: canon `authzResolve` (platform-prototype @ a6f1f3a
194
+ * `src/agencyhub.jsx:551-628`), read per held role and unioned.
195
+ * - `:578` / `:580-584`: a role that is unbound, Never-bound or N/A is not
196
+ * eligible and contributes nothing (`role_ineligible` / `unavailable`) —
197
+ * locally: another held role may still grant (`:566-577`, multi-role rule).
198
+ * - `:586-589`: any held role Always-bound → `required`; the agency layer is
199
+ * skipped (`:625` "agency cannot disable").
200
+ * - `:597-622`: per Default-On / Default-Off role the account state decides
201
+ * (required / on grant, blocked / off deny), else the default; the union
202
+ * of roles grants. Package mapping: agency ALWAYS = account "required",
203
+ * PREF_YES = "on", PREF_NO = "off", NEVER (and a stored NA) = "blocked".
204
+ * - `:626-628`: the team only restricts. Canon's team is function-grain (the
205
+ * package's flat `functions` map); the role-grain `roles[]` restriction is
206
+ * the platform's Tier-3 shape (kickoff § 2.1), applied to its own role.
207
+ * - Required immunity is the RULING (kickoff § 3 rule 3): Tier-1 ALWAYS and
208
+ * agency-escalated ALWAYS skip the team gate. Today's prototype still runs
209
+ * the team check for `required` (`:626-628`; the queued prototype ship), so
210
+ * the oracle follows the ruling, as the resolver does.
211
+ */
212
+ function oracle(
213
+ held: readonly { code: string; seed: Seed; agency: Gate }[],
214
+ team: { flat?: Gate; byRole?: Readonly<Record<string, Gate>> },
215
+ ): boolean {
216
+ const off = (g: Gate): boolean => g !== undefined && g !== "PREF_YES" && g !== "ALWAYS";
217
+ let granted = false;
218
+ for (const r of held) {
219
+ if (r.seed === null || r.seed === "NEVER" || r.seed === "NA") continue;
220
+ if (r.seed === "ALWAYS") return true;
221
+ const eff = r.agency ?? r.seed;
222
+ if (eff === "ALWAYS") return true;
223
+ if (eff === "PREF_YES" && !off(team.flat) && !off(team.byRole?.[r.code])) granted = true;
224
+ }
225
+ return granted;
226
+ }
227
+
228
+ const resolveOne = (
229
+ fn: string,
230
+ held: readonly { code: string; seed: Seed; agency: Gate }[],
231
+ team: { flat?: Gate; byRole?: Readonly<Record<string, Gate>> },
232
+ ): boolean => {
233
+ const byRole = Object.entries(team.byRole ?? {}).filter(([, g]) => g !== undefined);
234
+ return resolveEffectiveFunctions({
235
+ roles: held.map((r) => ({ code: r.code, functions: r.seed === null ? {} : { [fn]: r.seed } })),
236
+ functions: [{ code: fn }],
237
+ assignedRoleCodes: held.map((r) => r.code),
238
+ // Agency / team types carry no NA (canon has no NA chip there); the sweep
239
+ // still stores one, as malformed-but-possible data that must deny.
240
+ agencyOverrides: Object.fromEntries(
241
+ held.filter((r) => r.agency !== undefined).map((r) => [r.code, { [fn]: r.agency as never }]),
242
+ ),
243
+ teamPolicy:
244
+ team.flat === undefined && byRole.length === 0
245
+ ? undefined
246
+ : {
247
+ ...(team.flat === undefined ? {} : { functions: { [fn]: team.flat as never } }),
248
+ ...(byRole.length === 0
249
+ ? {}
250
+ : {
251
+ roles: byRole.map(([roleCode, g]) => ({
252
+ roleCode,
253
+ overrides: { [fn]: g as never },
254
+ })),
255
+ }),
256
+ },
257
+ unknownFunctionPolicy: "deny",
258
+ }).includes(fn);
259
+ };
260
+
261
+ describe("GATE L property: the codebook-seeded resolver against canon authzResolve", () => {
262
+ it("every evaluable function × every role, seeded from the codebook, × 6 agency × 5 team values: never escalates, and matches the oracle", () => {
263
+ // Independent of the oracle: a pair the codebook leaves unbound, NEVER or
264
+ // NA is never granted, whatever the agency or team says.
265
+ const roleCodes = [...adminCodes, ...userCodes].sort();
266
+ const agencyValues: Gate[] = [undefined, "ALWAYS", "PREF_YES", "PREF_NO", "NEVER", "NA"];
267
+ const teamValues: Gate[] = [undefined, "PREF_YES", "ALWAYS", "PREF_NO", "NA"];
268
+ const escalations: string[] = [];
269
+ const mismatches: string[] = [];
270
+ let checked = 0;
271
+ for (const fn of Object.keys(CORE_FUNCTION_DEFAULT_BOUNDS)) {
272
+ for (const role of roleCodes) {
273
+ const seed = codebookDefaultBound(fn, role);
274
+ for (const agency of agencyValues) {
275
+ for (const flat of teamValues) {
276
+ const held = [{ code: role, seed, agency }];
277
+ const got = resolveOne(fn, held, { flat });
278
+ checked++;
279
+ const tag = `${fn} × ${role} (codebook ${seed ?? "unbound"}, agency ${agency}, team ${flat})`;
280
+ if (got && (seed === null || seed === "NEVER" || seed === "NA")) escalations.push(tag);
281
+ if (got !== oracle(held, { flat })) mismatches.push(`${tag}: got ${got}`);
282
+ }
283
+ }
284
+ }
285
+ }
286
+ expect(checked).toBe(86 * roleCodes.length * agencyValues.length * teamValues.length);
287
+ expect(escalations, "grants canon never makes grantable").toEqual([]);
288
+ expect(mismatches.slice(0, 20)).toEqual([]);
289
+ });
290
+
291
+ it("role pairs: two held roles × seed (unbound, ALWAYS, PREF_YES, PREF_NO, NEVER, NA) × agency per role × flat / role-grain / NEVER team gates — the union matches the oracle", () => {
292
+ // One role's cascade has about 150 distinct behaviours (6 seeds × 5 agency
293
+ // values × 5 team outcomes); crossing two held roles exercises the union
294
+ // (rule 2: grants union, NEVER / NA / unbound are local to their role) and
295
+ // a role-grain team gate that narrows one role but not the other.
296
+ const fn = "case_edit";
297
+ const seeds: Seed[] = [null, "ALWAYS", "PREF_YES", "PREF_NO", "NEVER", "NA"];
298
+ const agencyValues: Gate[] = [undefined, "ALWAYS", "PREF_YES", "PREF_NO", "NEVER"];
299
+ const teams: { flat?: Gate; byRole?: Record<string, Gate> }[] = [
300
+ {},
301
+ { flat: "PREF_YES" },
302
+ { flat: "ALWAYS" },
303
+ { flat: "PREF_NO" },
304
+ { flat: "NEVER" },
305
+ { byRole: { SUP: "PREF_NO" } },
306
+ { byRole: { SUP: "PREF_YES" } },
307
+ { byRole: { case_nav: "NEVER" } },
308
+ { flat: "PREF_YES", byRole: { SUP: "PREF_NO" } },
309
+ ];
310
+ const mismatches: string[] = [];
311
+ let checked = 0;
312
+ let grants = 0;
313
+ for (const s1 of seeds)
314
+ for (const s2 of seeds)
315
+ for (const a1 of agencyValues)
316
+ for (const a2 of agencyValues)
317
+ for (const team of teams) {
318
+ const held = [
319
+ { code: "SUP", seed: s1, agency: a1 },
320
+ { code: "case_nav", seed: s2, agency: a2 },
321
+ ];
322
+ const got = resolveOne(fn, held, team);
323
+ const want = oracle(held, team);
324
+ checked++;
325
+ if (got) grants++;
326
+ if (got !== want)
327
+ mismatches.push(`SUP ${s1}/${a1} + case_nav ${s2}/${a2}, team ${JSON.stringify(team)}: got ${got}`);
328
+ }
329
+ expect(checked).toBe(6 * 6 * 5 * 5 * teams.length);
330
+ expect(grants, "the sweep reaches grants as well as denials").toBeGreaterThan(0);
331
+ expect(grants).toBeLessThan(checked);
332
+ expect(mismatches.slice(0, 20)).toEqual([]);
333
+ });
334
+ });
335
+
336
+ describe("projectBounds — the shared normalization (pin + GATE L)", () => {
337
+ const row = (bounds: unknown): Record<string, unknown> => ({ code: "x", bounds });
338
+
339
+ it("maps the four groups and not_applicable_roles, keys sorted; no bounds → {}", () => {
340
+ expect(
341
+ projectBounds(
342
+ row({
343
+ never: { admin_roles: [{ code: "SUP" }] },
344
+ always: { admin_roles: [{ code: "PLT-ADM" }], user_roles: [{ code: "case_nav" }] },
345
+ default_on: { user_roles: [{ code: "screener" }] },
346
+ default_off: { admin_roles: [{ code: "MEM-ADM" }] },
347
+ not_applicable_roles: [{ code: "research_analytics" }],
348
+ }),
349
+ ),
350
+ ).toEqual({
351
+ "MEM-ADM": "PREF_NO",
352
+ "PLT-ADM": "ALWAYS",
353
+ SUP: "NEVER",
354
+ case_nav: "ALWAYS",
355
+ research_analytics: "NA",
356
+ screener: "PREF_YES",
357
+ });
358
+ expect(projectBounds(row(undefined))).toEqual({});
359
+ });
360
+
361
+ it("throws on a role named twice, an unknown group or axis, or an entry without a code", () => {
362
+ expect(() =>
363
+ projectBounds(
364
+ row({ always: { admin_roles: [{ code: "SUP" }] }, not_applicable_roles: [{ code: "SUP" }] }),
365
+ ),
366
+ ).toThrow(/named twice/);
367
+ expect(() => projectBounds(row({ sometimes: {} }))).toThrow(/unknown group/);
368
+ expect(() => projectBounds(row({ always: { team_roles: [] } }))).toThrow(/unknown axis/);
369
+ expect(() => projectBounds(row({ never: { user_roles: [{ name: "x" }] } }))).toThrow(
370
+ /no string code/,
371
+ );
372
+ expect(() => projectBounds(row([]))).toThrow(/not a mapping/);
373
+ });
374
+ });