@htilabs/platform-common-models 0.22.0 → 0.23.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/dist/authz/index.cjs +539 -0
  2. package/dist/authz/index.cjs.map +1 -0
  3. package/dist/authz/index.d.cts +210 -0
  4. package/dist/authz/index.d.ts +210 -0
  5. package/dist/authz/index.js +507 -0
  6. package/dist/authz/index.js.map +1 -0
  7. package/dist/constants/index.d.cts +2 -1
  8. package/dist/constants/index.d.ts +2 -1
  9. package/dist/cvcs/index.cjs +647 -353
  10. package/dist/cvcs/index.cjs.map +1 -1
  11. package/dist/cvcs/index.d.cts +658 -362
  12. package/dist/cvcs/index.d.ts +658 -362
  13. package/dist/cvcs/index.js +647 -353
  14. package/dist/cvcs/index.js.map +1 -1
  15. package/dist/enums/index.cjs +1 -9
  16. package/dist/enums/index.cjs.map +1 -1
  17. package/dist/enums/index.d.cts +7 -15
  18. package/dist/enums/index.d.ts +7 -15
  19. package/dist/enums/index.js +1 -9
  20. package/dist/enums/index.js.map +1 -1
  21. package/dist/{platform-auth-CvAYFVhK.d.cts → ic-DpKrdgQP.d.cts} +1 -78
  22. package/dist/{platform-auth-CvAYFVhK.d.ts → ic-DpKrdgQP.d.ts} +1 -78
  23. package/dist/index.cjs +899 -362
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +3 -1
  26. package/dist/index.d.ts +3 -1
  27. package/dist/index.js +893 -362
  28. package/dist/index.js.map +1 -1
  29. package/dist/platform-auth-B49Ly57B.d.cts +78 -0
  30. package/dist/platform-auth-B49Ly57B.d.ts +78 -0
  31. package/dist/types/index.d.cts +2 -2
  32. package/dist/types/index.d.ts +2 -2
  33. package/package.json +6 -1
  34. package/src/__sot__/README.md +3 -1
  35. package/src/__sot__/adminRoles.pin.json +122 -0
  36. package/src/__sot__/adminRoles.published.json +77 -0
  37. package/src/__sot__/coreFunctionFields.ts +16 -0
  38. package/src/__sot__/coreFunctions.pin.json +114 -1
  39. package/src/__sot__/roleFields.ts +137 -0
  40. package/src/__sot__/userRoles.pin.json +174 -0
  41. package/src/__sot__/userRoles.published.json +103 -0
  42. package/src/__tests__/__snapshots__/cvc-sot.snap +5 -5
  43. package/src/__tests__/admin-roles-canon.test.ts +80 -0
  44. package/src/__tests__/authz-resolve.test.ts +712 -0
  45. package/src/__tests__/core-functions-canon.test.ts +62 -12
  46. package/src/__tests__/cvc-sot-snapshot.test.ts +12 -4
  47. package/src/__tests__/cvc-status-parser.test.ts +1 -1
  48. package/src/__tests__/cvc-structural.test.ts +3 -3
  49. package/src/__tests__/role-vocab-gate.ts +279 -0
  50. package/src/__tests__/user-roles-canon.test.ts +104 -0
  51. package/src/authz/index.ts +9 -0
  52. package/src/authz/resolveEffectiveFunctions.ts +454 -0
  53. package/src/cvcs/adminRoles.v2.0.0.json +197 -0
  54. package/src/cvcs/{coreFunctions.v1.2.0.json → coreFunctions.v1.3.0.json} +357 -200
  55. package/src/cvcs/index.ts +3 -3
  56. package/src/cvcs/userRoles.v2.0.0.json +296 -0
  57. package/src/generated/coreFunctionsEvaluable.ts +101 -0
  58. package/src/generated/cvc-enums.ts +7 -15
  59. package/src/index.ts +4 -0
  60. package/src/cvcs/adminRoles.v1.0.0.json +0 -153
  61. package/src/cvcs/userRoles.v1.0.0.json +0 -203
@@ -0,0 +1,454 @@
1
+ /**
2
+ * @htilabs/platform-common-models — the shared CVC-133 authorization resolver
3
+ *
4
+ * ONE pure function that every app (Thread · PAVE 2.0 · platform) calls to turn
5
+ * a seat's roles and the stored platform / agency / team policies into the set
6
+ * of CVC-133 function codes the seat may perform. No I/O and no mongoose: each
7
+ * app keeps only a loader that reads the platform-written collections and hands
8
+ * the rows in. Browser-safe entry: `@htilabs/platform-common-models/authz`.
9
+ *
10
+ * Spec: records repo (`htilabstech/prototype`) `KICKOFF_SHARED_AUTHZ_RESOLVER_2026-10-12.md`
11
+ * § 3 (the ruled model) and § 4.1 (this file). Line cites below are to the
12
+ * platform prototype (`htilabstech/platform-prototype` @ af10119)
13
+ * `src/agencyhub.jsx` `authzResolve` unless they name another file;
14
+ * `policyResolver.js` / `proxy/route.ts` cites are to `htilabstech/platform`
15
+ * develop @ ccf8da3.
16
+ *
17
+ * THE RULES (kickoff § 3 numbering)
18
+ *
19
+ * 1. Layers intersect and clamp downward: effective = platform ∩ agency ∩
20
+ * team (CAM, Notion 27f1ef14abcd8016accaca50780b2906; the devs' "3-Tier HTI
21
+ * Platform Permission Model", Notion 32c1ef14abcd80f0933ec66638bcc300:
22
+ * "The most restrictive applicable setting wins. Access is always clamped
23
+ * downward, never expanded upward"). Per role: the platform state (Tier 1)
24
+ * is the base; the agency may move an unlocked state (Tier 2,
25
+ * `agencyhub.jsx:601-624` — an account may switch a Default-Off function on
26
+ * or require it, or switch a Default-On one off); the team may only take a
27
+ * grant away (rule 4). The user-restriction, training, clearance, legal-basis
28
+ * and purpose layers (`:629-693`) are not inputs here (CAM layers the dev
29
+ * model has no data for yet, inventory resolvers.md D6).
30
+ * 2. Roles union at the user level; NEVER is local to its role. A function is
31
+ * granted when ANY assigned role's own cascade grants it; a role whose
32
+ * cascade ends at NEVER / Default-Off simply contributes nothing — it never
33
+ * vetoes another role's grant (`:566-589`, Crysta 2026-08-09 "grants are
34
+ * computed first"; restated 2026-10-12 "roles stack").
35
+ * 3. Required is immune to the team gate: a state that is ALWAYS after
36
+ * Tier 1 + Tier 2 (platform ALWAYS, or an agency that escalated the role to
37
+ * ALWAYS) is not team-gated (dev model: "locked" states skip Tier 3,
38
+ * `platform/lib/utils/policyResolver.js:58-72`; prototype `:625` "agency
39
+ * cannot disable"). NEVER at Tier 1 / Tier 2 is immune to a team lift —
40
+ * a Tier-1 ALWAYS / NEVER also ignores the agency layer
41
+ * (`policyResolver.js:46-48`). NOTE (kickoff § 5 trap): today's prototype
42
+ * still runs the team check for `required` (`:626-628`); "Required immune
43
+ * to the team gate" is the queued prototype ship. This resolver encodes the
44
+ * ruling, not the current prototype behaviour.
45
+ * 4. The team layer is RESTRICT-ONLY (`:626-628` "teams are workflow
46
+ * containers, never authority"; editor log lines `:1236` / `:4490` "it never
47
+ * grants"; UDD Team object, Notion 3ec1ef14abcd814385e4c4e84e071178: "If a
48
+ * team enables a function, but a user's role does not permit that function,
49
+ * the user does not gain access to it through team membership"). A team
50
+ * PREF_NO (or a NEVER, which the platform's own write path refuses from a
51
+ * team, `app/api/admin/proxy/route.ts:900`, but which is honoured
52
+ * fail-closed) takes the grant away; a team PREF_YES or ALWAYS is
53
+ * ignored — it never lifts a Default-Off or an agency switch-off. The
54
+ * policy's role-grain `roles[]` and flat `functions` maps are both team
55
+ * restrictions: either one switching a function off is enough.
56
+ * 5. One acting team per resolution: the seat's primary team (`team_id` =
57
+ * `team_ids[0]`, `setUserTeams` `:3228`; `authzForCurrentUser` passes the
58
+ * single `u.team_id`, `:734`), or a verified acting team the request
59
+ * carries (pave-2.0 team-scope precedence ADR, Notion
60
+ * 3921ef14abcd814ca839c1e7c3a57485). The caller resolves that ONE team's
61
+ * policy and passes it as `teamPolicy` — see `selectActingTeamId`. No team,
62
+ * or a team with no policy, is an explicit pass-through (ruling 3c, `:626`).
63
+ * 8. Unknown / retired / not-v1 functions are denied (`:556` "unknown function
64
+ * — deny by default", `:557` retired, `:558` not-v1) — decided by the canon
65
+ * this package ships, not by the caller's rows. The prototype checks its
66
+ * injected canon registry (`HTI_CORE_FUNCTIONS`, `:552-558`); here that is
67
+ * the CVC-133 SOT (`coreFunctions.v1.3.0.json`, whose `v1` / `retired`
68
+ * booleans are canon's own row flags), read through the slim generated key
69
+ * set `CORE_FUNCTIONS_EVALUABLE_KEYS` (v1 && !retired; GATE I asserts it
70
+ * equals the SOT) and intersected with `CoreFunctionsKeys`. No assigned
71
+ * roles, or none that resolve to a role row, yields the empty set.
72
+ *
73
+ * FAIL-CLOSED ON MALFORMED STORED DATA (ruled 2026-10-13, co-zo3 review and
74
+ * verification rounds). Every input is read defensively, so malformed data
75
+ * makes `resolveEffectiveFunctions` deny, never throw:
76
+ * - an `input` that is not an object, or a `roles` / `functions` /
77
+ * `assignedRoleCodes` that is not an array (null, a number, a string —
78
+ * never split into characters), resolves to `[]`;
79
+ * - a present state that is not one of the four PERMISSION_STATE values is
80
+ * NEVER at Tier 1, NEVER at Tier 2 (for that role), and a restriction at
81
+ * Tier 3; `undefined` and `null` mean "not set";
82
+ * - a state CONTAINER that is present but not a plain object (an array, a
83
+ * string, a Map, …) fails closed for everything it could govern: a role's
84
+ * `functions` → the role grants nothing; the agency's map, or one role's
85
+ * entry in it → NEVER for every unlocked state it covers; the team policy,
86
+ * its `functions`, or its `roles` list → every team-gated grant restricted;
87
+ * one role's `overrides` → that role's team-gated grants restricted;
88
+ * - a `teamPolicy.roles` entry that is not an object with a string `roleCode`
89
+ * cannot be attributed to a role, so it restricts every role's team-gated
90
+ * grants; duplicate entries for one role are unioned (any off wins);
91
+ * - a catalog row's `retired` keeps the function only when it is absent or
92
+ * exactly `false`;
93
+ * - Required (rule 3) stays immune to every team-side restriction.
94
+ *
95
+ * Rules 6 (app access is not a function) and 7 (vocabulary vs policy state)
96
+ * are about what the inputs are, not about this computation.
97
+ */
98
+
99
+ import {
100
+ PERMISSION_STATE,
101
+ type PermissionStateValue,
102
+ } from "../constants/platform-auth.js";
103
+ import { CoreFunctionsKeys } from "../generated/cvc-enums.js";
104
+ import { CORE_FUNCTIONS_EVALUABLE_KEYS } from "../generated/coreFunctionsEvaluable.js";
105
+
106
+ // ─── Canon (rule 8) ─────────────────────────────────────────────────────────
107
+
108
+ const CANON_EVALUABLE: ReadonlySet<string> = new Set(
109
+ CORE_FUNCTIONS_EVALUABLE_KEYS.filter((k) => Object.hasOwn(CoreFunctionsKeys, k)),
110
+ );
111
+
112
+ /** True when canon lets the resolver evaluate `code` at all (rule 8). */
113
+ export function isCanonEvaluableFunction(code: string): boolean {
114
+ return CANON_EVALUABLE.has(code);
115
+ }
116
+
117
+ // ─── Input contract (kickoff § 4.1) ─────────────────────────────────────────
118
+
119
+ /** A map of function code → permission state, as the platform stores it. */
120
+ export type AuthzStateMap = Readonly<Record<string, PermissionStateValue>>;
121
+
122
+ /**
123
+ * One `platformRoles` row (Tier 1): the role's platform state per function.
124
+ * A function the role does not list resolves to PREF_NO when it shares one of
125
+ * the role's tools, else NEVER (not applicable) — the rule all three dev
126
+ * resolvers use (`policyResolver.js:33-40`).
127
+ */
128
+ export interface AuthzRoleRow {
129
+ readonly code: string;
130
+ readonly tools?: readonly string[];
131
+ readonly functions?: AuthzStateMap;
132
+ }
133
+
134
+ /**
135
+ * One `platformFunctions` row: the deployment's function catalog, which
136
+ * supplies each function's `tools` (the Tier-1 default above). It can only
137
+ * narrow canon, never widen it:
138
+ * - a code canon does not carry, or carries as not-v1 / retired, is denied
139
+ * even when it is listed here;
140
+ * - `retired` other than absent / exactly `false` denies a function canon
141
+ * still has (a deployment may stop offering one early);
142
+ * - a canon function missing from this list is denied (it has no catalog row).
143
+ * Any other stored field (e.g. `platformFunctions.status`) is not read: a stale
144
+ * "Future function (not v1)" status never denies a function canon says is v1.
145
+ */
146
+ export interface AuthzFunctionRow {
147
+ readonly code: string;
148
+ readonly tools?: readonly string[];
149
+ readonly retired?: boolean;
150
+ }
151
+
152
+ /** One role-grain override entry, as stored in `teamAccessPolicies.roles[]`. */
153
+ export interface AuthzRoleOverrides {
154
+ readonly roleCode: string;
155
+ readonly overrides?: AuthzStateMap;
156
+ }
157
+
158
+ /**
159
+ * The ONE acting team's `teamAccessPolicies` document (rule 5). `roles[]`
160
+ * narrows one role; `functions` narrows every role. Both only restrict, so a
161
+ * function is off for a role when any of them says so.
162
+ */
163
+ export interface AuthzTeamPolicy {
164
+ readonly roles?: readonly AuthzRoleOverrides[];
165
+ readonly functions?: AuthzStateMap;
166
+ }
167
+
168
+ export interface ResolveEffectiveFunctionsInput {
169
+ /** Every `platformRoles` row the seat might hold (extra rows are ignored). */
170
+ readonly roles: readonly AuthzRoleRow[];
171
+ /** The deployment's function catalog (`platformFunctions`), narrowed by canon. */
172
+ readonly functions: readonly AuthzFunctionRow[];
173
+ /** The seat's assigned role codes. */
174
+ readonly assignedRoleCodes: readonly string[];
175
+ /** Tier 2 — the agency's overrides, `{ roleCode → { functionCode → state } }`. */
176
+ readonly agencyOverrides?: Readonly<Record<string, AuthzStateMap>>;
177
+ /** Tier 3 — the acting team's policy; absent / null = pass-through. */
178
+ readonly teamPolicy?: AuthzTeamPolicy | null;
179
+ /** Declared, not configurable: an unknown function is always denied (rule 8). */
180
+ readonly unknownFunctionPolicy: "deny";
181
+ }
182
+
183
+ // ─── Defensive reads ────────────────────────────────────────────────────────
184
+
185
+ type StoredMap = Readonly<Record<string, unknown>>;
186
+
187
+ /** A container read: not set, a usable plain object, or malformed. */
188
+ type Container = { readonly kind: "absent" } | { readonly kind: "malformed" } | {
189
+ readonly kind: "map";
190
+ readonly map: StoredMap;
191
+ };
192
+
193
+ const ABSENT: Container = { kind: "absent" };
194
+ const MALFORMED: Container = { kind: "malformed" };
195
+
196
+ function isPlainObject(v: unknown): v is StoredMap {
197
+ if (v === null || typeof v !== "object") return false;
198
+ const proto: unknown = Object.getPrototypeOf(v);
199
+ return proto === Object.prototype || proto === null;
200
+ }
201
+
202
+ function readContainer(v: unknown): Container {
203
+ if (v === undefined || v === null) return ABSENT;
204
+ return isPlainObject(v) ? { kind: "map", map: v } : MALFORMED;
205
+ }
206
+
207
+ /** An own property of a plain-object map (never an inherited key). */
208
+ function own(map: StoredMap, key: string): unknown {
209
+ return Object.hasOwn(map, key) ? map[key] : undefined;
210
+ }
211
+
212
+ const STATES: ReadonlySet<string> = new Set<string>(Object.values(PERMISSION_STATE));
213
+
214
+ /** One stored state: not set, a recognised state, or `"malformed"`. */
215
+ function readState(map: StoredMap, code: string): PermissionStateValue | "malformed" | undefined {
216
+ const v = own(map, code);
217
+ if (v === undefined || v === null) return undefined;
218
+ return typeof v === "string" && STATES.has(v) ? (v as PermissionStateValue) : "malformed";
219
+ }
220
+
221
+ function stringList(v: unknown): readonly string[] {
222
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
223
+ }
224
+
225
+ /** Rule 4: anything but "not set", PREF_YES or ALWAYS restricts. */
226
+ function teamValueRestricts(map: StoredMap, code: string): boolean {
227
+ const gate = readState(map, code);
228
+ return (
229
+ gate !== undefined &&
230
+ gate !== PERMISSION_STATE.PREF_YES &&
231
+ gate !== PERMISSION_STATE.ALWAYS
232
+ );
233
+ }
234
+
235
+ /** The acting team's policy, compiled once into restrict-only predicates. */
236
+ interface TeamGate {
237
+ /** Every team-gated grant is restricted (malformed or unattributable data). */
238
+ readonly restrictsAll: boolean;
239
+ readonly flat: StoredMap | undefined;
240
+ /** Every overrides map stored for a role (duplicates kept, then unioned). */
241
+ readonly byRole: ReadonlyMap<string, readonly StoredMap[]>;
242
+ /** Roles whose stored overrides container is malformed. */
243
+ readonly malformedRoles: ReadonlySet<string>;
244
+ }
245
+
246
+ function compileTeamGate(teamPolicy: unknown): TeamGate {
247
+ const byRole = new Map<string, StoredMap[]>();
248
+ const malformedRoles = new Set<string>();
249
+ const policy = readContainer(teamPolicy);
250
+ if (policy.kind === "absent") {
251
+ return { restrictsAll: false, flat: undefined, byRole, malformedRoles };
252
+ }
253
+ if (policy.kind === "malformed") {
254
+ return { restrictsAll: true, flat: undefined, byRole, malformedRoles };
255
+ }
256
+ let restrictsAll = false;
257
+ const functions = readContainer(own(policy.map, "functions"));
258
+ if (functions.kind === "malformed") restrictsAll = true;
259
+ const roles = own(policy.map, "roles");
260
+ if (roles !== undefined && roles !== null) {
261
+ if (!Array.isArray(roles)) restrictsAll = true;
262
+ else {
263
+ for (const entry of roles as unknown[]) {
264
+ const roleCode = isPlainObject(entry) ? own(entry, "roleCode") : undefined;
265
+ if (!isPlainObject(entry) || typeof roleCode !== "string") {
266
+ restrictsAll = true; // cannot tell which role it narrows
267
+ continue;
268
+ }
269
+ const overrides = readContainer(own(entry, "overrides"));
270
+ if (overrides.kind === "malformed") malformedRoles.add(roleCode);
271
+ else if (overrides.kind === "map") {
272
+ const list = byRole.get(roleCode) ?? [];
273
+ list.push(overrides.map);
274
+ byRole.set(roleCode, list);
275
+ }
276
+ }
277
+ }
278
+ }
279
+ return {
280
+ restrictsAll,
281
+ flat: functions.kind === "map" ? functions.map : undefined,
282
+ byRole,
283
+ malformedRoles,
284
+ };
285
+ }
286
+
287
+ function teamRestricts(gate: TeamGate, roleCode: string, code: string): boolean {
288
+ if (gate.restrictsAll || gate.malformedRoles.has(roleCode)) return true;
289
+ if (gate.flat !== undefined && teamValueRestricts(gate.flat, code)) return true;
290
+ return (gate.byRole.get(roleCode) ?? []).some((m) => teamValueRestricts(m, code));
291
+ }
292
+
293
+ // ─── Resolver ───────────────────────────────────────────────────────────────
294
+
295
+ /**
296
+ * Resolve the CVC-133 function codes a seat may perform.
297
+ *
298
+ * @returns sorted, de-duplicated function codes; `[]` when nothing resolves,
299
+ * including when `input` is not an object or `roles`, `functions` or
300
+ * `assignedRoleCodes` is not an array (never a throw; a string is
301
+ * never iterated as characters).
302
+ */
303
+ export function resolveEffectiveFunctions(
304
+ input: ResolveEffectiveFunctionsInput,
305
+ ): string[] {
306
+ const raw: unknown = input;
307
+ if (!isPlainObject(raw)) return [];
308
+ const roleRows = own(raw, "roles");
309
+ const catalog = own(raw, "functions");
310
+ const assigned = own(raw, "assignedRoleCodes");
311
+ if (!Array.isArray(roleRows) || !Array.isArray(catalog) || !Array.isArray(assigned)) return [];
312
+
313
+ const rolesByCode = new Map<string, StoredMap>();
314
+ for (const r of roleRows as readonly unknown[]) {
315
+ const code = isPlainObject(r) ? own(r, "code") : undefined;
316
+ if (isPlainObject(r) && typeof code === "string") rolesByCode.set(code, r);
317
+ }
318
+ const heldCodes = [...new Set(assigned as readonly unknown[])].filter(
319
+ (c): c is string => typeof c === "string" && rolesByCode.has(c),
320
+ );
321
+ if (heldCodes.length === 0) return [];
322
+
323
+ // Rule 8: the catalog narrowed by canon, and by its own `retired` (only an
324
+ // absent or exactly-false flag keeps a row).
325
+ const vocabulary: { readonly code: string; readonly tools: readonly string[] }[] = [];
326
+ for (const fn of catalog as readonly unknown[]) {
327
+ if (!isPlainObject(fn)) continue;
328
+ const code = own(fn, "code");
329
+ const retired = own(fn, "retired");
330
+ if (typeof code !== "string" || !isCanonEvaluableFunction(code)) continue;
331
+ if (retired !== undefined && retired !== false) continue;
332
+ vocabulary.push({ code, tools: stringList(own(fn, "tools")) });
333
+ }
334
+
335
+ const agencyAll = readContainer(input.agencyOverrides);
336
+ const team = compileTeamGate(input.teamPolicy);
337
+
338
+ const granted = new Set<string>();
339
+ for (const roleCode of heldCodes) {
340
+ const role = rolesByCode.get(roleCode)!;
341
+ const roleTools = new Set(stringList(own(role, "tools")));
342
+ const roleFunctions = readContainer(own(role, "functions"));
343
+ if (roleFunctions.kind === "malformed") continue; // Tier 1 unreadable: grants nothing
344
+ const agency =
345
+ agencyAll.kind === "map" ? readContainer(own(agencyAll.map, roleCode)) : agencyAll;
346
+
347
+ for (const fn of vocabulary) {
348
+ if (granted.has(fn.code)) continue; // rule 2: another role already grants it
349
+
350
+ // Tier 1 — platform. A malformed stored state is NEVER.
351
+ const listed = roleFunctions.kind === "map" ? readState(roleFunctions.map, fn.code) : undefined;
352
+ const applies = fn.tools.some((t) => roleTools.has(t));
353
+ const tier1: PermissionStateValue =
354
+ listed === "malformed"
355
+ ? PERMISSION_STATE.NEVER
356
+ : (listed ?? (applies ? PERMISSION_STATE.PREF_NO : PERMISSION_STATE.NEVER));
357
+
358
+ // Tier 2 — agency. Tier-1 ALWAYS / NEVER are locked (rule 3); a
359
+ // malformed override (or container) is NEVER for this role.
360
+ let state = tier1;
361
+ if (tier1 !== PERMISSION_STATE.ALWAYS && tier1 !== PERMISSION_STATE.NEVER) {
362
+ const override =
363
+ agency.kind === "malformed"
364
+ ? "malformed"
365
+ : agency.kind === "map"
366
+ ? readState(agency.map, fn.code)
367
+ : undefined;
368
+ if (override === "malformed") state = PERMISSION_STATE.NEVER;
369
+ else if (override !== undefined) state = override;
370
+ }
371
+
372
+ if (state !== PERMISSION_STATE.ALWAYS && state !== PERMISSION_STATE.PREF_YES) continue;
373
+
374
+ // Tier 3 — team, restrict-only (rule 4); Required is immune (rule 3).
375
+ if (state !== PERMISSION_STATE.ALWAYS && teamRestricts(team, roleCode, fn.code)) continue;
376
+
377
+ granted.add(fn.code);
378
+ }
379
+ }
380
+
381
+ return [...granted].sort();
382
+ }
383
+
384
+ // ─── Acting team (rule 5) ───────────────────────────────────────────────────
385
+
386
+ /**
387
+ * Pick the ONE team whose policy feeds `teamPolicy`.
388
+ *
389
+ * - `verifiedActingTeamId` given → that team, as is. VERIFYING it is the
390
+ * caller's job: each app has its own membership source (pave-2.0 checks
391
+ * `teams.members[]` through its membership checker; `users.teams` is not kept
392
+ * in step with it), so this helper does not second-guess the caller against
393
+ * `seatTeamIds`. Pass only a team the caller has confirmed the seat sits on.
394
+ * - otherwise → the primary team, `seatTeamIds[0]`;
395
+ * - no teams → `null` (pass-through).
396
+ */
397
+ export function selectActingTeamId(
398
+ seatTeamIds: readonly string[],
399
+ verifiedActingTeamId?: string | null,
400
+ ): string | null {
401
+ if (verifiedActingTeamId) return verifiedActingTeamId;
402
+ return seatTeamIds[0] ?? null;
403
+ }
404
+
405
+ // ─── Internal viewing level (CVC-133 viewing_level_1/2/3) ───────────────────
406
+
407
+ /** Level 0 is derived (no level function resolves), never a configurable rung. */
408
+ export type ViewingLevel = 0 | 1 | 2 | 3;
409
+
410
+ /** The three Type-A viewing functions, highest first. */
411
+ export const VIEWING_LEVEL_FUNCTIONS = [
412
+ ["viewing_level_3_components", 3],
413
+ ["viewing_level_2_autocomplete", 2],
414
+ ["viewing_level_1_search", 1],
415
+ ] as const satisfies ReadonlyArray<readonly [keyof typeof CoreFunctionsKeys, ViewingLevel]>;
416
+
417
+ /**
418
+ * The effective internal viewing level from an already-resolved function set.
419
+ *
420
+ * Canon (CVC-133 `viewing_level_3_components` logic_notes, records
421
+ * `data/cvcs/core_functions.yaml` @ f4356aa4): "Effective viewing level = the
422
+ * highest of the three level functions the user's roles resolve to … clamped by
423
+ * the team-set level — most restrictive wins; the team axis clamps down, never
424
+ * up. … Absence of all three functions = Level 0 (not a configurable setting)."
425
+ *
426
+ * `teamViewingLevel` is the level the account's viewing policy sets for the
427
+ * acting team — the team's own row, else the account-wide rule (prototype
428
+ * `src/screens.jsx:14671` `effLevel`, `:14819` "a member's own role can only
429
+ * narrow it further"). Absent / null = no team-set level, so no clamp.
430
+ *
431
+ * Own / claimed cases are always fully visible; that is the caller's
432
+ * record-level check, not this function's.
433
+ */
434
+ export function viewingLevelFromFunctions(
435
+ effectiveFunctions: Iterable<string>,
436
+ teamViewingLevel?: ViewingLevel | null,
437
+ ): ViewingLevel {
438
+ const held = new Set(effectiveFunctions);
439
+ const roleLevel = VIEWING_LEVEL_FUNCTIONS.find(([code]) => held.has(code))?.[1] ?? 0;
440
+ return teamViewingLevel == null
441
+ ? roleLevel
442
+ : (Math.min(roleLevel, teamViewingLevel) as ViewingLevel);
443
+ }
444
+
445
+ /**
446
+ * Resolve the seat's functions (same input, same rules as
447
+ * `resolveEffectiveFunctions`) and return its effective internal viewing level.
448
+ */
449
+ export function resolveEffectiveViewingLevel(
450
+ input: ResolveEffectiveFunctionsInput,
451
+ teamViewingLevel?: ViewingLevel | null,
452
+ ): ViewingLevel {
453
+ return viewingLevelFromFunctions(resolveEffectiveFunctions(input), teamViewingLevel);
454
+ }
@@ -0,0 +1,197 @@
1
+ {
2
+ "domain": "admin_roles",
3
+ "name": "Core Admin Roles (CVC-134)",
4
+ "version": "2.0.0",
5
+ "_status": "CANONICAL — Notion CVC-134 (core - admin roles), active (verification: expired; mirror revision 1.8); GENERATED from the prototype repo's data/cvcs/core_admin_role.yaml by scripts/gen-admin-roles.py — never hand-edit. Canonical numbering (134). ADMINISTRATIVE / control-plane role axis of the canonical authorization model (IC-66): authority to configure, govern and support — \"admin ≠ content visibility\" (holding one never widens what case content a person sees). DISTINCT from CVC-135 `user_roles` — a person may hold both. Keys are the underscore transliterations of canon's hyphenated codes (`PLT-ADM` -> `plt_adm`), carried verbatim in `canonicalCode`. 10 canon roles = 10 entries. NO missingness codes: canon declares none (a role is assigned, never observed); the 1.0.0 quadruplet is withdrawn (`_supersedes.retiredCodes`). Canon `legacy_codes` (old -> live, migrate on read) resolve through `_supersedes.keyMap`, which is key-space: transliterate canon's spelling first (`ACCT-ADM` -> `acct_adm`). Canon's per-role `display_label` (the 20-char topbar-chip short form; absent = use `title`), `reach` (platform · account · team · supervised_people), `scope`, `plain_language`, `required` and `required_when` ride on each entry in camelCase where canon carries them. TRAIN-ADM's definition is canon's DRAFT (\"⚑ Crysta to confirm\" — see its `definitionNote`). Canon's `functions` (BRK-GLS-FN, CI-EXPORT-FN: capabilities, not roles) are not carried.",
6
+ "_supersedes": {
7
+ "version": "1.0.0",
8
+ "keyMap": {
9
+ "missingness_root": null,
10
+ "unknown": null,
11
+ "anonymous": null,
12
+ "data_not_collected": null,
13
+ "plt_adm": "plt_adm",
14
+ "plt_sup": "plt_sup",
15
+ "mem_adm": "mem_adm",
16
+ "team_adm": "team_adm",
17
+ "aud": "aud",
18
+ "data_adm": "data_adm",
19
+ "gov_aud": "gov_aud",
20
+ "ciro": "ciro",
21
+ "sup": "sup",
22
+ "train_adm": "train_adm",
23
+ "acct_adm": "mem_adm"
24
+ },
25
+ "retiredCodes": [
26
+ {
27
+ "code": "134-000-000-000-000-000-000",
28
+ "key": "missingness_root",
29
+ "successor": null,
30
+ "reason": "missingness (canon declares none)"
31
+ },
32
+ {
33
+ "code": "134-000-000-000-000-000-001",
34
+ "key": "unknown",
35
+ "successor": null,
36
+ "reason": "missingness (canon declares none)"
37
+ },
38
+ {
39
+ "code": "134-000-000-000-000-000-002",
40
+ "key": "anonymous",
41
+ "successor": null,
42
+ "reason": "missingness (canon declares none)"
43
+ },
44
+ {
45
+ "code": "134-000-000-000-000-000-003",
46
+ "key": "data_not_collected",
47
+ "successor": null,
48
+ "reason": "missingness (canon declares none)"
49
+ }
50
+ ],
51
+ "notes": {
52
+ "acct_adm": "LEGACY ALIAS (since 2.0.0): canon data/cvcs/core_admin_role.yaml legacy_codes `ACCT-ADM: MEM-ADM`. `acct_adm` was never a key of this package; it is mapped here so a stored `acct_adm` resolves to `mem_adm` the same way a re-keyed key does. This keyMap is key-space (the package convention): a store holding canon's spelling `ACCT-ADM` transliterates it with this codeset's key rule first (`ACCT-ADM` -> `acct_adm`). Canon (recorded 2026-09-07, CVC134-135-AUDIT): ACCT-ADM was the HTI Platform demo fixture's spelling of the MEM-ADM hat, never a CVC-134 code; canon records it so any straggler stored value still resolves.",
53
+ "missingness": "WITHDRAWN: canon CVC-134 declares NO missingness rows (neither the yaml nor the Notion codebook the 1.0.0 file was imported from; 1.0.0 added the quadruplet package-side \"per SOT convention\"). A role is ASSIGNED, never observed — the CVC-135 ruling (canon core_user_role.yaml, gate G3) on the sibling role axis. The four 1.0.0 missingness codes 134-000-* are retired the victimAbuseTypes 1.1.0 way: no entry, keyMap -> null, listed in retiredCodes, recorded in the ledger so a code is never reused. A stored missingness key has no successor: read it as an empty admin-role list."
54
+ },
55
+ "appended": [],
56
+ "refreshed": [
57
+ "plt_adm",
58
+ "plt_sup",
59
+ "mem_adm",
60
+ "team_adm",
61
+ "aud",
62
+ "data_adm",
63
+ "gov_aud",
64
+ "ciro",
65
+ "sup",
66
+ "train_adm"
67
+ ],
68
+ "tombstoned": []
69
+ },
70
+ "_source": "htilabstech/prototype data/cvcs/core_admin_role.yaml @ e963ec97 (last commit touching canon on the canonical branch); Notion — core - admin roles (CVC-134) (https://app.notion.com/3211ef14abcd80179464c1ec7583e7b4, from the yaml's `cvc:` line comment). The June codebook CSV export the 1.0.0 file was built from (prototype a596eb9) is superseded by the yaml and not read.",
71
+ "levels": {
72
+ "1": "Admin role"
73
+ },
74
+ "entries": [
75
+ {
76
+ "code": "134-001-000-000-000-000-000",
77
+ "key": "plt_adm",
78
+ "title": "Platform Owner & Admin",
79
+ "selectable": true,
80
+ "parentCode": null,
81
+ "childCodes": [],
82
+ "definition": "HTI Labs platform control-plane governance.",
83
+ "canonicalCode": "PLT-ADM",
84
+ "displayLabel": "Platform Admin",
85
+ "reach": "platform"
86
+ },
87
+ {
88
+ "code": "134-002-000-000-000-000-000",
89
+ "key": "plt_sup",
90
+ "title": "Platform Support Admin",
91
+ "selectable": true,
92
+ "parentCode": null,
93
+ "childCodes": [],
94
+ "definition": "Routine HTI support / debugging (prefer over PLT-ADM for support).",
95
+ "canonicalCode": "PLT-SUP",
96
+ "displayLabel": "Support Admin",
97
+ "reach": "platform"
98
+ },
99
+ {
100
+ "code": "134-003-000-000-000-000-000",
101
+ "key": "mem_adm",
102
+ "title": "Account Admin (Member Administrator)",
103
+ "selectable": true,
104
+ "parentCode": null,
105
+ "childCodes": [],
106
+ "definition": "The member-account administrator (Account Admin / \"Member Administrator\"). Required role — at least one per member account.",
107
+ "canonicalCode": "MEM-ADM",
108
+ "displayLabel": "Account Admin",
109
+ "required": true,
110
+ "reach": "account"
111
+ },
112
+ {
113
+ "code": "134-004-000-000-000-000-000",
114
+ "key": "team_adm",
115
+ "title": "Team Admin",
116
+ "selectable": true,
117
+ "parentCode": null,
118
+ "childCodes": [],
119
+ "definition": "Delegated, team-scoped admin used to operate one-to-many teams as workflow containers. Always: manage team membership + team workflow configuration. Optional-on: assign/reassign cases, manage training gates. Optional-off (delegable by MEM-ADM): user management, role assignment, bulk transfer. NEVER: team structure & admin scoping — so TEAM-ADM cannot expand or redefine its own scope.",
120
+ "canonicalCode": "TEAM-ADM",
121
+ "reach": "team",
122
+ "scope": "team",
123
+ "plainLanguage": "Runs the team's SETUP."
124
+ },
125
+ {
126
+ "code": "134-005-000-000-000-000-000",
127
+ "key": "aud",
128
+ "title": "Compliance / Auditor",
129
+ "selectable": true,
130
+ "parentCode": null,
131
+ "childCodes": [],
132
+ "definition": "Read-only audit + de-identified compliance workflows.",
133
+ "canonicalCode": "AUD",
134
+ "reach": "account"
135
+ },
136
+ {
137
+ "code": "134-006-000-000-000-000-000",
138
+ "key": "data_adm",
139
+ "title": "Data & Reporting Admin",
140
+ "selectable": true,
141
+ "parentCode": null,
142
+ "childCodes": [],
143
+ "definition": "Echo / reporting admin — grant reporting, data exports, reporting configuration — WITHOUT broader account governance.",
144
+ "canonicalCode": "DATA-ADM",
145
+ "reach": "account"
146
+ },
147
+ {
148
+ "code": "134-007-000-000-000-000-000",
149
+ "key": "gov_aud",
150
+ "title": "Governance Auditor",
151
+ "selectable": true,
152
+ "parentCode": null,
153
+ "childCodes": [],
154
+ "definition": "Opt-in governance spot checks / QA review; redacted-by-default surfaces.",
155
+ "canonicalCode": "GOV-AUD",
156
+ "reach": "account"
157
+ },
158
+ {
159
+ "code": "134-008-000-000-000-000-000",
160
+ "key": "ciro",
161
+ "title": "Criminal Intelligence Review Officer",
162
+ "selectable": true,
163
+ "parentCode": null,
164
+ "childCodes": [],
165
+ "definition": "Control-plane governance designation establishing accountability for CI handling: validation rules, periodic review, purge/retention, oversight. Does NOT imply broad case-content visibility. The CI → evidence export approval FUNCTION is exercised by a CIRO (see cross_references.functions).",
166
+ "canonicalCode": "CIRO",
167
+ "displayLabel": "Intel Review Officer",
168
+ "requiredWhen": "leads_ci_enabled",
169
+ "reach": "account"
170
+ },
171
+ {
172
+ "code": "134-009-000-000-000-000-000",
173
+ "key": "sup",
174
+ "title": "Supervisor",
175
+ "selectable": true,
176
+ "parentCode": null,
177
+ "childCodes": [],
178
+ "definition": "A role a person holds over the specific people they supervise — the seats whose `supervised_by` names them (Crysta 2026-10-02: \"A supervisor is a role that a user takes on over those users that they supervise\"; it relates to people, not to a team, and it is still a role). Day-to-day case workflow oversight for those people: operational triage, case assignment, the needs-action flags on their work, and the notices about items that belong to one of them (a claimed mandatory-report flag that sits unsent goes to that person's supervisor). WITHOUT account governance powers or destructive enforcement; deliberately NARROWER than TEAM-ADM. Always: manage case escalation / needs-action flags, assign/reassign case ownership. Case-record access is NOT required of the role; an account's Member Admin may enable it (Crysta 2026-10-02). Not relevant to the role (SUPERVISOR-RULING 2026-10-07, off the role): team membership, role assignment, training gates — those are team and account setup (Team Admin · Member Admin), not supervision of people. NEVER: user management, sharing configuration, team structure & scoping, bulk transfer, purge, suspend, API keys, platform authorization model. Not a generalized admin or support role. The people supervised may sit on any team or none; supervision does not follow team or account lines.",
179
+ "canonicalCode": "SUP",
180
+ "reach": "supervised_people",
181
+ "scope": "people",
182
+ "plainLanguage": "Oversees the WORK of the people they supervise."
183
+ },
184
+ {
185
+ "code": "134-010-000-000-000-000-000",
186
+ "key": "train_adm",
187
+ "title": "Training Admin",
188
+ "selectable": true,
189
+ "parentCode": null,
190
+ "childCodes": [],
191
+ "definition": "Agency-set role that configures training/certification requirements and gates (which modules a role or team must complete), manages training content, and reports on completion. Case-content posture: NONE.",
192
+ "canonicalCode": "TRAIN-ADM",
193
+ "definitionNote": "NOTE: the canonical Notion row is an empty stub (owner Ava Monte, created by Lauren DeLuca 2026-04-21) — definition drafted here from the codebook's own role-table entry and the training_gate_manage function bounds. ⚑ Crysta to confirm.",
194
+ "reach": "account"
195
+ }
196
+ ]
197
+ }