@htilabs/platform-common-models 0.23.0 → 0.25.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 (82) hide show
  1. package/README.md +104 -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-Asg7mxjB.d.cts} +12 -9
  15. package/dist/{cvcEntry-0BIB9sen.d.ts → cvcEntry-Asg7mxjB.d.ts} +12 -9
  16. package/dist/{index-CDoqrfc1.d.ts → index-ClTjjJ_S.d.ts} +1 -1
  17. package/dist/{index-Zu_mOJRn.d.cts → index-Pt82NxQg.d.cts} +1 -1
  18. package/dist/index.cjs +604 -15
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +7 -5
  21. package/dist/index.d.ts +7 -5
  22. package/dist/index.js +577 -15
  23. package/dist/index.js.map +1 -1
  24. package/dist/information-scope/index.d.cts +3 -350
  25. package/dist/information-scope/index.d.ts +3 -350
  26. package/dist/informationScopeResolver-BzYu97DE.d.cts +351 -0
  27. package/dist/informationScopeResolver-BzYu97DE.d.ts +351 -0
  28. package/dist/models/index.cjs +26 -1
  29. package/dist/models/index.cjs.map +1 -1
  30. package/dist/models/index.d.cts +2 -2
  31. package/dist/models/index.d.ts +2 -2
  32. package/dist/models/index.js +26 -1
  33. package/dist/models/index.js.map +1 -1
  34. package/dist/{platform-auth-B49Ly57B.d.cts → platform-auth-DJO-r9Pf.d.cts} +48 -1
  35. package/dist/{platform-auth-B49Ly57B.d.ts → platform-auth-DJO-r9Pf.d.ts} +48 -1
  36. package/dist/schemas/index.cjs +26 -1
  37. package/dist/schemas/index.cjs.map +1 -1
  38. package/dist/schemas/index.d.cts +25 -25
  39. package/dist/schemas/index.d.ts +25 -25
  40. package/dist/schemas/index.js +26 -1
  41. package/dist/schemas/index.js.map +1 -1
  42. package/dist/services/index.cjs +26 -1
  43. package/dist/services/index.cjs.map +1 -1
  44. package/dist/services/index.d.cts +2 -1
  45. package/dist/services/index.d.ts +2 -1
  46. package/dist/services/index.js +26 -1
  47. package/dist/services/index.js.map +1 -1
  48. package/dist/sharing-ceiling/index.cjs +497 -0
  49. package/dist/sharing-ceiling/index.cjs.map +1 -0
  50. package/dist/sharing-ceiling/index.d.cts +318 -0
  51. package/dist/sharing-ceiling/index.d.ts +318 -0
  52. package/dist/sharing-ceiling/index.js +451 -0
  53. package/dist/sharing-ceiling/index.js.map +1 -0
  54. package/dist/types/index.d.cts +11 -3
  55. package/dist/types/index.d.ts +11 -3
  56. package/dist/validation/index.cjs +22 -0
  57. package/dist/validation/index.cjs.map +1 -1
  58. package/dist/validation/index.js +22 -0
  59. package/dist/validation/index.js.map +1 -1
  60. package/package.json +7 -1
  61. package/src/__sot__/README.md +2 -1
  62. package/src/__sot__/coreFunctionFields.ts +88 -4
  63. package/src/__sot__/coreFunctions.pin.json +1040 -113
  64. package/src/__sot__/sharingStarter.pin.json +229 -0
  65. package/src/__tests__/authz-resolve.test.ts +115 -31
  66. package/src/__tests__/core-function-default-bounds.test.ts +374 -0
  67. package/src/__tests__/core-functions-case-close.test.ts +82 -0
  68. package/src/__tests__/sharing-starter-canon.test.ts +178 -0
  69. package/src/authz/defaultBounds.ts +69 -0
  70. package/src/authz/index.ts +12 -3
  71. package/src/authz/resolveEffectiveFunctions.ts +69 -29
  72. package/src/constants/platform-auth.ts +60 -0
  73. package/src/generated/coreFunctionDefaultBounds.ts +109 -0
  74. package/src/generated/sharingPlatformStarter.ts +165 -0
  75. package/src/index.ts +5 -0
  76. package/src/schemas/platform-role.ts +4 -1
  77. package/src/sharingCeiling/__tests__/sharingCeiling.test.ts +678 -0
  78. package/src/sharingCeiling/chain.ts +269 -0
  79. package/src/sharingCeiling/coverage.ts +346 -0
  80. package/src/sharingCeiling/index.ts +14 -0
  81. package/src/sharingCeiling/starter.ts +89 -0
  82. package/src/types/platform-auth.ts +9 -2
@@ -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
+ });
@@ -0,0 +1,82 @@
1
+ /**
2
+ * CORE FUNCTIONS (CVC-133) — `case_close` is ONE function carrying both legs
3
+ * ===========================================================================
4
+ *
5
+ * Crysta's 2026-10-09 ruling (case close is holder-only and is a REQUEST that
6
+ * an Account Admin or the holder's team Supervisor approves or does not
7
+ * approve) is already minted in canon as a single CVC-133 row, `case_close`
8
+ * (prototype `data/cvcs/core_functions.yaml` @ f4356aa4, L2383-L2394, "Minted
9
+ * 2026-10-10"), and the generated SOT v1.3.0 carries it at
10
+ * 133-098-000-000-000-000-000. The approval leg is not a second function: canon
11
+ * gives it to "the supervisor-confirm leg of case_status_manage brought to
12
+ * PAVE" — the approver must hold `case_close` AND be an Account Admin of the
13
+ * case's account or a supervisor of the holder, and is never the requester
14
+ * (L2392). Bounds ride canon only (Always MEM-ADM · SUP · case_nav; Default On
15
+ * TEAM-ADM, L2398-L2414); this entry schema does not carry bounds.
16
+ *
17
+ * What this pins, against the regression it exists for: a hand-minted
18
+ * `case_close_request` / `case_close_approve` pair next to the canon row (an
19
+ * engineer-direct "mint" of something canon already has — GATE I would also
20
+ * refuse it as invented, this names the reason), and a regenerated row that
21
+ * silently loses the request/approval semantics PAVE's close flow enforces
22
+ * (bead pv-p6share-case-close-request-approval). The notification kinds the
23
+ * flow emits (`caseCloseRequested` / `caseCloseRuled`, CVC-284 v19) are NOT
24
+ * carried by this package — CVC-284 has no domain here — so nothing pins them.
25
+ *
26
+ * The expectations are transcribed from canon, not derived from the JSON.
27
+ */
28
+ import { readFileSync } from "node:fs";
29
+ import path from "node:path";
30
+ import { fileURLToPath } from "node:url";
31
+ import { describe, it, expect } from "vitest";
32
+
33
+ import { CoreFunctionsKeys } from "../generated/cvc-enums.js";
34
+
35
+ const here = path.dirname(fileURLToPath(import.meta.url));
36
+ const SOT = path.join(here, "..", "cvcs", "coreFunctions.v1.3.0.json");
37
+
38
+ interface Entry {
39
+ code: string;
40
+ key: string;
41
+ title: string;
42
+ selectable: boolean;
43
+ parentCode: string | null;
44
+ childCodes: string[];
45
+ definition: string;
46
+ }
47
+
48
+ const entries = (JSON.parse(readFileSync(SOT, "utf8")) as { entries: Entry[] }).entries;
49
+
50
+ describe("CVC-133 case_close — the holder's close request and its approval are one function", () => {
51
+ it("is published at 133-098 and exported by key", () => {
52
+ expect(CoreFunctionsKeys.case_close).toBe("133-098-000-000-000-000-000");
53
+ });
54
+
55
+ it("is a selectable leaf titled as canon titles it", () => {
56
+ const row = entries.find((e) => e.key === "case_close");
57
+ expect(row).toBeDefined();
58
+ expect(row).toMatchObject({
59
+ code: "133-098-000-000-000-000-000",
60
+ title: "Close case",
61
+ selectable: true,
62
+ parentCode: null,
63
+ childCodes: [],
64
+ });
65
+ });
66
+
67
+ it("defines the close as a REQUEST that waits on an Account Admin or the holder's team Supervisor", () => {
68
+ const def = entries.find((e) => e.key === "case_close")?.definition ?? "";
69
+ expect(def).toContain("submit it as a CLOSE REQUEST");
70
+ expect(def).toContain(
71
+ "until an Account Admin or the holder's team Supervisor approves or does not approve it",
72
+ );
73
+ expect(def).toContain("Nothing closes until the approval.");
74
+ expect(def).toContain("Platform: PAVE.");
75
+ expect(def).toContain("Category: Core case/lead workflow, Approval-gated actions.");
76
+ });
77
+
78
+ it("has no split request/approve sibling — the approval leg rides case_close", () => {
79
+ const siblings = entries.map((e) => e.key).filter((k) => /^case_close./.test(k));
80
+ expect(siblings).toEqual([]);
81
+ });
82
+ });
@@ -0,0 +1,178 @@
1
+ /**
2
+ * SHARING STARTER — GATE M: the platform sharing starter restates canon (co-2sx)
3
+ * =============================================================================
4
+ *
5
+ * `src/generated/sharingPlatformStarter.ts` is GENERATED from canon by
6
+ * `scripts/gen-sharing-starter.py` (monolith `HTI_SHARE_PLATFORM_STARTER` +
7
+ * platform-prototype `data.sharing.*`, refused unless the two copies agree).
8
+ * `src/__sot__/sharingStarter.pin.json` is derived INDEPENDENTLY from the same
9
+ * canon by `scripts/sot-pins.ts` (a separate TypeScript reader). This test is
10
+ * the hermetic enforcer: the shipped starter equals the pin, key order
11
+ * included, and every code it names is a live, non-floor CVC-236 v4 row; the
12
+ * field homes (`fieldHomeRows`) equal the pin and are live rows. Like
13
+ * `gen-sharing-starter.py --check`, it compares DATA only: a newer canon SHA
14
+ * with identical data passes, with the provenance printed as a note.
15
+ * `gen-sharing-starter.py --check` and `sot:pins:check` are the detectors for
16
+ * canon moving.
17
+ */
18
+ import { readFileSync } from "node:fs";
19
+ import path from "node:path";
20
+ import { fileURLToPath } from "node:url";
21
+ import { describe, expect, it } from "vitest";
22
+
23
+ import { coreInformationScopeSot, sharePurposeSot } from "../cvcs/index.js";
24
+ import {
25
+ createInformationScopeResolver,
26
+ scopeMigrationsFromSot,
27
+ scopeRowsFromSot,
28
+ type CoreInformationScopeSot,
29
+ } from "../services/informationScope.js";
30
+ import {
31
+ HTI_SHARE_PLATFORM_PURPOSE_ENABLED,
32
+ HTI_SHARE_PLATFORM_STARTER,
33
+ HTI_SHARE_PLATFORM_STARTER_SOURCE,
34
+ INFORMATION_SCOPE_FIELD_HOME_ROWS,
35
+ } from "../sharingCeiling/index.js";
36
+ import * as root from "../index.js";
37
+
38
+ const here = path.dirname(fileURLToPath(import.meta.url));
39
+ const pin = JSON.parse(
40
+ readFileSync(path.join(here, "..", "__sot__", "sharingStarter.pin.json"), "utf8"),
41
+ ) as {
42
+ sourceSha: string;
43
+ mirror: { sourceSha: string };
44
+ scopeVersion: number;
45
+ scopeByPurpose: Record<string, string[]>;
46
+ counterpartyOverrides: Record<string, Record<string, string[]>>;
47
+ purposeEnabled: Record<string, boolean>;
48
+ fieldHomeRows: string[];
49
+ };
50
+
51
+ const sot = coreInformationScopeSot as CoreInformationScopeSot;
52
+ const scope = createInformationScopeResolver({
53
+ rows: scopeRowsFromSot(sot),
54
+ migrations: scopeMigrationsFromSot(sot),
55
+ });
56
+
57
+ /** Every (where, code) the starter names. */
58
+ const namedCodes = (): [string, string][] => {
59
+ const out: [string, string][] = [];
60
+ for (const [p, codes] of Object.entries(HTI_SHARE_PLATFORM_STARTER.scopeByPurpose)) {
61
+ for (const c of codes) out.push([`scopeByPurpose.${p}`, c]);
62
+ }
63
+ for (const [cp, lists] of Object.entries(HTI_SHARE_PLATFORM_STARTER.counterpartyOverrides)) {
64
+ for (const [p, codes] of Object.entries(lists)) {
65
+ for (const c of codes) out.push([`counterpartyOverrides.${cp}.${p}`, c]);
66
+ }
67
+ }
68
+ return out;
69
+ };
70
+
71
+ type PurposeEntry = { key: string; wing?: string };
72
+ const purposes = (sharePurposeSot as unknown as { entries: PurposeEntry[] }).entries;
73
+ const corePurposes = purposes.filter((e) => e.wing === "core").map((e) => e.key);
74
+ const allPurposes = new Set(purposes.map((e) => e.key));
75
+
76
+ describe("sharing starter — GATE M: the shipped starter restates canon (@ the pin)", () => {
77
+ it("equals the independently derived pin, key order included", () => {
78
+ expect(pin.scopeVersion).toBe(4);
79
+ expect(HTI_SHARE_PLATFORM_STARTER.scopeVersion).toBe(4);
80
+ expect(JSON.stringify(HTI_SHARE_PLATFORM_STARTER.scopeByPurpose)).toBe(
81
+ JSON.stringify(pin.scopeByPurpose),
82
+ );
83
+ expect(JSON.stringify(HTI_SHARE_PLATFORM_STARTER.counterpartyOverrides)).toBe(
84
+ JSON.stringify(pin.counterpartyOverrides),
85
+ );
86
+ expect(JSON.stringify(HTI_SHARE_PLATFORM_PURPOSE_ENABLED)).toBe(
87
+ JSON.stringify(pin.purposeEnabled),
88
+ );
89
+ });
90
+
91
+ it("checks DATA only — a different canon SHA with identical data is a NOTE, not a failure", () => {
92
+ // Matches `gen-sharing-starter.py --check`: the monolith moves on nearly
93
+ // every canon commit, so provenance alone never fails the gate.
94
+ const src = HTI_SHARE_PLATFORM_STARTER_SOURCE;
95
+ const stale = [
96
+ src.monolith.sha.startsWith(pin.sourceSha) ? null : `prototype ${src.monolith.sha} vs pin ${pin.sourceSha}`,
97
+ src.mirror.sha.startsWith(pin.mirror.sourceSha)
98
+ ? null
99
+ : `platform-prototype ${src.mirror.sha} vs pin ${pin.mirror.sourceSha}`,
100
+ ].filter((n): n is string => n !== null);
101
+ if (stale.length > 0) {
102
+ console.info(`NOTE (GATE M): data in sync; provenance differs — ${stale.join("; ")}`);
103
+ }
104
+ expect(typeof src.monolith.sha).toBe("string");
105
+ });
106
+
107
+ it("ships canon's field homes (row_v4), each a live v4 row", () => {
108
+ expect([...INFORMATION_SCOPE_FIELD_HOME_ROWS]).toEqual(pin.fieldHomeRows);
109
+ const notLive = pin.fieldHomeRows.filter((c) => {
110
+ const row = scope.row(c);
111
+ return row === undefined || row.status === "retired";
112
+ });
113
+ expect(notLive).toEqual([]);
114
+ expect(pin.fieldHomeRows).toContain("instruments");
115
+ expect(pin.fieldHomeRows).toContain("commercial_activity");
116
+ });
117
+
118
+ it("names only live, non-floor CVC-236 v4 rows, each once per list", () => {
119
+ const bad: string[] = [];
120
+ for (const [where, code] of namedCodes()) {
121
+ const row = scope.row(code);
122
+ if (row === undefined || row.status === "retired") bad.push(`${where}: ${code} is not a live v4 row`);
123
+ else if (scope.ancestorsOf(code).some((a) => scope.row(a)?.platformFloor === true)) {
124
+ bad.push(`${where}: ${code} is (under) the platform safety floor`);
125
+ }
126
+ }
127
+ expect(bad).toEqual([]);
128
+ for (const lists of [
129
+ HTI_SHARE_PLATFORM_STARTER.scopeByPurpose,
130
+ ...Object.values(HTI_SHARE_PLATFORM_STARTER.counterpartyOverrides),
131
+ ]) {
132
+ for (const codes of Object.values(lists)) expect(new Set(codes).size).toBe(codes.length);
133
+ }
134
+ });
135
+
136
+ it("covers exactly the eight core-wing CVC-84 purposes; LEADS-wing purposes have no platform ceiling", () => {
137
+ const core = [...corePurposes].sort();
138
+ expect(core).toHaveLength(8);
139
+ expect(Object.keys(HTI_SHARE_PLATFORM_STARTER.scopeByPurpose).sort()).toEqual(core);
140
+ expect(Object.keys(HTI_SHARE_PLATFORM_PURPOSE_ENABLED).sort()).toEqual(core);
141
+ for (const lists of Object.values(HTI_SHARE_PLATFORM_STARTER.counterpartyOverrides)) {
142
+ for (const p of Object.keys(lists)) expect(allPurposes.has(p), p).toBe(true);
143
+ }
144
+ });
145
+
146
+ it("ships records_request disabled and every other core purpose enabled (data.js L32527)", () => {
147
+ expect(
148
+ Object.entries(HTI_SHARE_PLATFORM_PURPOSE_ENABLED)
149
+ .filter(([, e]) => !e)
150
+ .map(([p]) => p),
151
+ ).toEqual(["records_request"]);
152
+ });
153
+
154
+ it("CANON GAP — the seeded partner rules are keyed by canon's demonstration ids, shipped as canon has them", () => {
155
+ // No registry agency carries these ids, so the seeded-partner rung binds on
156
+ // no real data until the platform maps them. A change here is a canon change.
157
+ expect(Object.keys(HTI_SHARE_PLATFORM_STARTER.counterpartyOverrides)).toEqual([
158
+ "palomar",
159
+ "okcpd",
160
+ "legal_aid_ok",
161
+ ]);
162
+ });
163
+
164
+ it("is deep-frozen", () => {
165
+ expect(Object.isFrozen(HTI_SHARE_PLATFORM_STARTER)).toBe(true);
166
+ expect(Object.isFrozen(HTI_SHARE_PLATFORM_STARTER.scopeByPurpose)).toBe(true);
167
+ expect(Object.isFrozen(HTI_SHARE_PLATFORM_STARTER.scopeByPurpose["referral"])).toBe(true);
168
+ expect(Object.isFrozen(HTI_SHARE_PLATFORM_STARTER.counterpartyOverrides["okcpd"])).toBe(true);
169
+ expect(Object.isFrozen(HTI_SHARE_PLATFORM_PURPOSE_ENABLED)).toBe(true);
170
+ });
171
+
172
+ it("is re-exported from the package root", () => {
173
+ expect(root.HTI_SHARE_PLATFORM_STARTER).toBe(HTI_SHARE_PLATFORM_STARTER);
174
+ expect(root.HTI_SHARE_PLATFORM_PURPOSE_ENABLED).toBe(HTI_SHARE_PLATFORM_PURPOSE_ENABLED);
175
+ expect(typeof root.effectiveCeiling).toBe("function");
176
+ expect(typeof root.scopeRowWithinCeiling).toBe("function");
177
+ });
178
+ });