@htilabs/platform-common-models 0.55.0 → 0.56.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.
@@ -11,6 +11,8 @@ export * from "./resolveEffectiveFunctions.js";
11
11
  export * from "./defaultBounds.js";
12
12
  export * from "./functionDoor.js";
13
13
  export * from "./roleCodes.js";
14
+ export * from "./viewingPolicy.js";
15
+ export * from "./viewingScope.js";
14
16
  export {
15
17
  DEFAULT_BOUND_STATE,
16
18
  DEFAULT_BOUND_STATE_DISPLAY,
@@ -0,0 +1,525 @@
1
+ /**
2
+ * @htilabs/platform-common-models/authz — the account's Internal Viewing Policy
3
+ * reader: which stored viewing rule governs one acting team.
4
+ *
5
+ * Contract of record: "Contract — the account's Internal Viewing Policy: stored
6
+ * shape and delivery to Thread and PAVE (Kickoff 13 § 5a)", §§ 1–4. Lifted from
7
+ * PAVE's `@pave/db` `readViewingPolicy` (pave-2.0 develop 41f5f916,
8
+ * `packages/db/src/lookups/viewingPolicy.ts`) so Thread and PAVE run ONE reader
9
+ * (GDR § 5.79, one resolver per runtime). The selection and validation rules are
10
+ * PAVE's, unchanged; only the I/O is left to the app.
11
+ *
12
+ * ## Pure: each app does its own query
13
+ *
14
+ * No database access. The app reads the candidate rows itself — the account's
15
+ * `registry_policies` documents (`species: "viewing"`, `account_id` = the acting
16
+ * agency's Account; passing every policy of the account is fine, other species are
17
+ * skipped here) — and hands them in with `{ accountId, teamId }`. A failed read is
18
+ * passed as `docs: null` (or answered with {@link unavailableViewingPolicy}); it is
19
+ * never an empty list, because an empty list means "nothing on file".
20
+ *
21
+ * ## Which row governs (Crysta 2026-10-06, ruling (a))
22
+ *
23
+ * The acting team's OWN active row governs that team IN PLACE OF the account-wide
24
+ * rule — higher or lower; the two are never combined. With no team row, the
25
+ * account-wide rule governs. With neither, nothing governs: `source: "none"`, and
26
+ * the role level alone decides (Level 3 shows the full record; Crysta 2026-11-03,
27
+ * "Match the prototype"). The role clamps afterwards:
28
+ * `viewingLevelFromFunctions(effectiveFunctions, teamViewingLevelFromPolicy(result))`.
29
+ * Prototype: `viewingPolicyFor`, platform-prototype `src/data.js` (aa2c63a).
30
+ *
31
+ * ## Fail closed, never throw (contract § 4)
32
+ *
33
+ * Anything that stops the policy being READ answers `source: "unavailable"`
34
+ * (level 0 for that request) with a coded reason — never `"none"`: the account
35
+ * cannot be resolved; the read failed; a live viewing row whose assignment is not
36
+ * exactly one account-or-team entry (it might be this team's narrowing); a row in
37
+ * this team's or the account's place whose `active` is neither `true` nor `false`;
38
+ * two live rows in one place without distinct versions of one family; and, on the
39
+ * governing row, a `level` that is not exactly 0–3, a `visibleGroups` that is
40
+ * present but not a list of strings or names a code that is not live at its stamp,
41
+ * a `scopeVocab` that is missing or not 3, 4 or 5. A malformed team row never falls
42
+ * back to the account rule (that fallback could widen).
43
+ *
44
+ * A governing row with no `visibleGroups` reads as an EMPTY list (contract § 4;
45
+ * PAVE `caseViewing.ts` `accessFromResolution`): only "no row at all" shows the
46
+ * full record. System information is always shown — that is the Level 3 filter's
47
+ * job ({@link caseViewingAccess}), not this reader's.
48
+ */
49
+
50
+ import type {
51
+ InformationScopeResolver,
52
+ ScopeReading,
53
+ } from "../services/informationScopeResolver.js";
54
+ import type { ViewingLevel } from "./resolveEffectiveFunctions.js";
55
+
56
+ /** The stored `species` of an internal-viewing policy (UDD Policy.v1). */
57
+ export const VIEWING_POLICY_SPECIES = "viewing" as const;
58
+
59
+ // ─── The vocabulary stamp (`scopeVocab`) ─────────────────────────────────────
60
+
61
+ /** What one of the prototype's viewing-policy vocabulary stamps means to a reader. */
62
+ export interface ViewingPolicyVocabulary {
63
+ /** The CVC-236 tree version the resolver reads the list at (3 through the v3 → v4 table, or 4). */
64
+ readonly scopeVersion: 3 | 4;
65
+ /** The prototype's ONE-HOME domain carry applies (`scopeVocab < 4`). */
66
+ readonly oneHomeCarry: boolean;
67
+ /** The prototype's v4 alias on `identifying` applies (`scopeVocab < 5`). */
68
+ readonly identifyingAlias: boolean;
69
+ }
70
+
71
+ /**
72
+ * The stamps a stored viewing policy's `scopeVocab` may carry and still be read.
73
+ *
74
+ * The stamp is the Internal Viewing tab's own counter, NOT the CVC-236 tree
75
+ * version: the hub stamps every save `5` for the four-level v4 tree
76
+ * (platform-prototype `src/screens.jsx` `setLevel` / `toggleGroup` /
77
+ * `setAcctLevel`). Earlier saves stamped 4 (ONE-HOME) and 3 (the Instruments
78
+ * catalog), both authored against the v3 tree. Stamps 1 and 2 and every future
79
+ * stamp (6 and up) are not read: they fail closed. Lifted from PAVE
80
+ * `@pave/domain` `VIEWING_POLICY_VOCABULARIES`.
81
+ */
82
+ export const VIEWING_POLICY_VOCABULARIES: Readonly<
83
+ Record<3 | 4 | 5, ViewingPolicyVocabulary>
84
+ > = Object.freeze({
85
+ 3: Object.freeze({ scopeVersion: 3, oneHomeCarry: true, identifyingAlias: true }),
86
+ 4: Object.freeze({ scopeVersion: 3, oneHomeCarry: false, identifyingAlias: true }),
87
+ 5: Object.freeze({ scopeVersion: 4, oneHomeCarry: false, identifyingAlias: false }),
88
+ });
89
+
90
+ /** A stamp this reader reads. */
91
+ export type ViewingPolicyScopeVocab = 3 | 4 | 5;
92
+
93
+ /** The reading of a stored `scopeVocab`, or `null` when it cannot be read (fail closed). */
94
+ export function viewingPolicyVocabulary(scopeVocab: unknown): ViewingPolicyVocabulary | null {
95
+ return scopeVocab === 3 || scopeVocab === 4 || scopeVocab === 5
96
+ ? VIEWING_POLICY_VOCABULARIES[scopeVocab]
97
+ : null;
98
+ }
99
+
100
+ // ─── Inputs and the result ───────────────────────────────────────────────────
101
+
102
+ /**
103
+ * The bound CVC-236 resolver the reader validates a whitelist with — the app's
104
+ * own binding of `createInformationScopeResolver` to `coreInformationScopeSot`
105
+ * (PAVE `INFORMATION_SCOPE_V4`, Thread `INFORMATION_SCOPE_RESOLVER`). Passed in
106
+ * so the browser-safe `./authz` entry never inlines the SOT JSON.
107
+ */
108
+ export type ViewingPolicyScopeResolver = Pick<InformationScopeResolver, "row" | "readSelection">;
109
+
110
+ /** Who is asking. */
111
+ export interface ViewingPolicyQuery {
112
+ /**
113
+ * The Account that owns the policy — the acting agency's Account, which the
114
+ * caller resolved. Empty / null = the account could not be resolved
115
+ * (`unavailable`, `account_unresolved`).
116
+ */
117
+ accountId: string | null | undefined;
118
+ /**
119
+ * The ONE acting team, already bound by the caller to the acting agency
120
+ * (Thread `resolveSeatActingTeamId`, PAVE `viewingTeamOfAgency`). `null` = no
121
+ * acting team, so only the account-wide rule can govern. A 24-hex id is
122
+ * compared case-insensitively.
123
+ */
124
+ teamId: string | null | undefined;
125
+ }
126
+
127
+ /** Why the policy could not be read. The first four are the app's I/O outcomes. */
128
+ export type ViewingPolicyUnavailableReason =
129
+ | "no_acting_agency"
130
+ | "account_unresolved"
131
+ | "policy_store_absent"
132
+ | "read_error"
133
+ | "unreadable_assignment"
134
+ | "malformed_active"
135
+ | "ambiguous_rows"
136
+ | "malformed_level"
137
+ | "malformed_visible_groups"
138
+ | "unknown_visible_group"
139
+ | "malformed_scope_vocab"
140
+ | "unsupported_scope_vocab";
141
+
142
+ /** The governing row's identity (prototype `viewingPolicyFor` `policy`). */
143
+ export interface ViewingPolicyRef {
144
+ /** The row's `entity_id`, else `id`, else `_id`. */
145
+ readonly id: string;
146
+ readonly familyId: string | null;
147
+ /** A positive integer, or `null` when the row carries none (or a malformed one). */
148
+ readonly version: number | null;
149
+ }
150
+
151
+ /** A team's own row, or the account-wide rule, governs. */
152
+ export interface ViewingPolicyGoverning {
153
+ readonly source: "team" | "account";
154
+ /** The level the policy grants (before the role clamp). */
155
+ readonly level: ViewingLevel;
156
+ /**
157
+ * The categories still shown at Level 3, as stored (a copy), minus any
158
+ * `category_rest` row. A row with no list reads `[]` (only the stub and system
159
+ * information show). Every code is live at the tree version `scopeVocab` reads.
160
+ */
161
+ readonly visibleGroups: readonly string[];
162
+ readonly scopeVocab: ViewingPolicyScopeVocab;
163
+ readonly policy: ViewingPolicyRef;
164
+ readonly accountId: string;
165
+ /** A short, value-free trace of the decision, for logs (ids and versions only). */
166
+ readonly rulePath: string;
167
+ }
168
+
169
+ /** No row governs: the account set nothing for this team. The role level alone decides. */
170
+ export interface ViewingPolicyNone {
171
+ readonly source: "none";
172
+ readonly level: null;
173
+ /** `null`: no row, so Level 3 shows the full record. */
174
+ readonly visibleGroups: null;
175
+ readonly scopeVocab: null;
176
+ readonly policy: null;
177
+ readonly accountId: string;
178
+ /** The account holds viewing rows and every one is retired (`active: false`): log it. */
179
+ readonly retiredRowsOnly: boolean;
180
+ readonly rulePath: string;
181
+ }
182
+
183
+ /** The policy could not be read: no view of other teams' cases for this request. */
184
+ export interface ViewingPolicyUnavailable {
185
+ readonly source: "unavailable";
186
+ readonly level: 0;
187
+ readonly visibleGroups: readonly string[];
188
+ readonly scopeVocab: null;
189
+ readonly policy: null;
190
+ readonly reason: ViewingPolicyUnavailableReason;
191
+ /** The offending row's id, when one row caused it. */
192
+ readonly policyId: string | null;
193
+ readonly rulePath: string;
194
+ }
195
+
196
+ export type GoverningViewingPolicy =
197
+ | ViewingPolicyGoverning
198
+ | ViewingPolicyNone
199
+ | ViewingPolicyUnavailable;
200
+
201
+ /** A stored viewing row, as raw as it is on disk (the platform owns the writer). */
202
+ interface RawViewingPolicyDoc {
203
+ _id?: unknown;
204
+ entity_id?: unknown;
205
+ id?: unknown;
206
+ familyId?: unknown;
207
+ version?: unknown;
208
+ active?: unknown;
209
+ level?: unknown;
210
+ visibleGroups?: unknown;
211
+ scopeVocab?: unknown;
212
+ assignments?: unknown;
213
+ species?: unknown;
214
+ account_id?: unknown;
215
+ }
216
+
217
+ /** Where one row applies: the whole account, one team, or unplaceable. */
218
+ type Placement =
219
+ | { kind: "account" }
220
+ | { kind: "team"; teamId: string }
221
+ | { kind: "unreadable" };
222
+
223
+ // ─── Helpers (PAVE's, verbatim in behaviour) ─────────────────────────────────
224
+
225
+ /**
226
+ * The policy could not be read — the shape every fail-closed answer takes. Apps
227
+ * use it for their own I/O outcomes (`read_error`, `policy_store_absent`, …).
228
+ */
229
+ export function unavailableViewingPolicy(
230
+ reason: ViewingPolicyUnavailableReason,
231
+ policyId?: string | null,
232
+ ): ViewingPolicyUnavailable {
233
+ return {
234
+ source: "unavailable",
235
+ level: 0,
236
+ visibleGroups: [],
237
+ scopeVocab: null,
238
+ policy: null,
239
+ reason,
240
+ policyId: policyId ?? null,
241
+ rulePath:
242
+ `viewing policy unavailable: ${reason}` +
243
+ (policyId ? ` (${policyId})` : "") +
244
+ " — no view of other teams' cases",
245
+ };
246
+ }
247
+
248
+ const HEX_OBJECT_ID = /^[0-9a-fA-F]{24}$/;
249
+
250
+ /** The hex of an ObjectId-like value (duck-typed), lower-case; `null` for anything else. */
251
+ function objectIdHex(v: unknown): string | null {
252
+ if (typeof v === "object" && v !== null && "toHexString" in v) {
253
+ const toHex: unknown = (v as { toHexString: unknown }).toHexString;
254
+ if (typeof toHex === "function") {
255
+ const hex: unknown = toHex.call(v);
256
+ if (typeof hex === "string") return hex.toLowerCase();
257
+ }
258
+ }
259
+ return null;
260
+ }
261
+
262
+ /** A stored id as text, or `null` when it is not an id. */
263
+ function idText(v: unknown): string | null {
264
+ if (typeof v === "string") return v === "" ? null : v;
265
+ return objectIdHex(v);
266
+ }
267
+
268
+ /**
269
+ * One spelling per id: a 24-hex ObjectId string is lower-cased (an ObjectId's own
270
+ * rendering is lower-case; a hand-typed team id may not be); any other id is
271
+ * compared exactly.
272
+ */
273
+ function normalizedId(id: string): string {
274
+ return HEX_OBJECT_ID.test(id) ? id.toLowerCase() : id;
275
+ }
276
+
277
+ function policyIdOf(d: RawViewingPolicyDoc): string {
278
+ return idText(d.entity_id) ?? idText(d.id) ?? idText(d._id) ?? "(no id)";
279
+ }
280
+
281
+ /**
282
+ * A row's ONE assignment: the whole account or one team. Anything else — no
283
+ * assignment, several, a mix, an unknown scope, a team entry with no team — is
284
+ * UNREADABLE: the row might be this team's narrowing, and skipping it could widen.
285
+ */
286
+ function placementOf(d: RawViewingPolicyDoc): Placement {
287
+ if (!Array.isArray(d.assignments) || d.assignments.length !== 1) {
288
+ return { kind: "unreadable" };
289
+ }
290
+ const [a] = d.assignments as unknown[];
291
+ if (typeof a !== "object" || a === null) return { kind: "unreadable" };
292
+ const { scope, teamId } = a as { scope?: unknown; teamId?: unknown };
293
+ if (scope === "account") return { kind: "account" };
294
+ const team = idText(teamId);
295
+ if (scope === "team" && team !== null) {
296
+ return { kind: "team", teamId: normalizedId(team) };
297
+ }
298
+ return { kind: "unreadable" };
299
+ }
300
+
301
+ /** A positive integer, or `null` when absent; `undefined` when malformed. */
302
+ function positiveIntOrNull(v: unknown): number | null | undefined {
303
+ if (v === undefined || v === null) return null;
304
+ return typeof v === "number" && Number.isInteger(v) && v >= 1 ? v : undefined;
305
+ }
306
+
307
+ /**
308
+ * The ONE live row of a place. Several live rows are read in version order only
309
+ * when they are one family with distinct versions (a prior version the writer has
310
+ * not yet deactivated); otherwise the place is ambiguous.
311
+ */
312
+ function governingRowOf(
313
+ rows: readonly RawViewingPolicyDoc[],
314
+ ): { row: RawViewingPolicyDoc } | ViewingPolicyUnavailable {
315
+ const [only] = rows;
316
+ if (rows.length === 1 && only !== undefined) return { row: only };
317
+ const family = idText(rows[0]?.familyId);
318
+ const versions = rows.map((r) => positiveIntOrNull(r.version));
319
+ const ordered =
320
+ family !== null &&
321
+ rows.every((r) => idText(r.familyId) === family) &&
322
+ versions.every((v): v is number => typeof v === "number") &&
323
+ new Set(versions).size === versions.length;
324
+ if (!ordered) {
325
+ return unavailableViewingPolicy("ambiguous_rows", policyIdOf(rows[0] ?? {}));
326
+ }
327
+ let best = rows[0] as RawViewingPolicyDoc;
328
+ for (const r of rows) {
329
+ if ((r.version as number) > (best.version as number)) best = r;
330
+ }
331
+ return { row: best };
332
+ }
333
+
334
+ /**
335
+ * Every code must be a live CVC-236 code at the tree version the stamp reads at:
336
+ * an unknown or retired code fails closed rather than being quietly dropped.
337
+ */
338
+ function whitelistProblem(
339
+ visibleGroups: readonly string[],
340
+ vocab: ViewingPolicyVocabulary,
341
+ scope: ViewingPolicyScopeResolver,
342
+ ): ViewingPolicyUnavailableReason | null {
343
+ const reading: ScopeReading = scope.readSelection(visibleGroups, vocab.scopeVersion, {
344
+ subject: "policy",
345
+ });
346
+ if (reading.unsupportedVersion) return "unsupported_scope_vocab";
347
+ if (reading.unknown.length > 0 || reading.retired.length > 0) {
348
+ return "unknown_visible_group";
349
+ }
350
+ return null;
351
+ }
352
+
353
+ /**
354
+ * The whitelist as viewing reads it: without a `category_rest` row
355
+ * (`identifying.other`). Naming that row covers its whole category on the share
356
+ * side; the prototype's viewing gate reads the category alone, so here it opens
357
+ * nothing. Dropped, not refused (PAVE `withoutRestRows`).
358
+ */
359
+ function withoutRestRows(
360
+ visibleGroups: readonly string[],
361
+ scope: ViewingPolicyScopeResolver,
362
+ ): string[] {
363
+ return visibleGroups.filter((code) => scope.row(code)?.rowType !== "category_rest");
364
+ }
365
+
366
+ function ruleText(source: "team" | "account", ref: ViewingPolicyRef): string {
367
+ const v = ref.version === null ? "" : ` v${ref.version}`;
368
+ return source === "team"
369
+ ? `${ref.id}${v} (the team's own row — it governs this team in place of the account-wide rule)`
370
+ : `${ref.id}${v} (the account-wide viewing rule — no row for this team)`;
371
+ }
372
+
373
+ /** Read the governing row's fields; any malformed field is unavailable. */
374
+ function readRow(
375
+ d: RawViewingPolicyDoc,
376
+ source: "team" | "account",
377
+ accountId: string,
378
+ scope: ViewingPolicyScopeResolver,
379
+ ): GoverningViewingPolicy {
380
+ const policyId = policyIdOf(d);
381
+ const level = d.level;
382
+ if (level !== 0 && level !== 1 && level !== 2 && level !== 3) {
383
+ return unavailableViewingPolicy("malformed_level", policyId);
384
+ }
385
+ let visibleGroups: string[] = [];
386
+ if (d.visibleGroups !== undefined && d.visibleGroups !== null) {
387
+ if (!Array.isArray(d.visibleGroups) || !d.visibleGroups.every((g) => typeof g === "string")) {
388
+ return unavailableViewingPolicy("malformed_visible_groups", policyId);
389
+ }
390
+ visibleGroups = [...(d.visibleGroups as string[])];
391
+ }
392
+ const scopeVocab = positiveIntOrNull(d.scopeVocab);
393
+ if (scopeVocab === undefined) {
394
+ return unavailableViewingPolicy("malformed_scope_vocab", policyId);
395
+ }
396
+ // EVERY governing row must carry a stamp the reader reads (3, 4 or 5), at every
397
+ // level and with or without a list: the hub stamps every save, so a row without
398
+ // one was not written by it, and a Level 3 row read at all shows the client's
399
+ // name and date of birth to other teams (PAVE `readRow`).
400
+ const vocab = viewingPolicyVocabulary(scopeVocab);
401
+ if (scopeVocab === null || vocab === null) {
402
+ return unavailableViewingPolicy("unsupported_scope_vocab", policyId);
403
+ }
404
+ const problem = whitelistProblem(visibleGroups, vocab, scope);
405
+ if (problem !== null) return unavailableViewingPolicy(problem, policyId);
406
+ const policy: ViewingPolicyRef = {
407
+ id: policyId,
408
+ familyId: idText(d.familyId),
409
+ version: positiveIntOrNull(d.version) ?? null,
410
+ };
411
+ return {
412
+ source,
413
+ level,
414
+ visibleGroups: withoutRestRows(visibleGroups, scope),
415
+ scopeVocab: scopeVocab as ViewingPolicyScopeVocab,
416
+ policy,
417
+ accountId,
418
+ rulePath: ruleText(source, policy),
419
+ };
420
+ }
421
+
422
+ // ─── The reader ──────────────────────────────────────────────────────────────
423
+
424
+ /**
425
+ * The internal-viewing policy that governs `query.teamId` on `query.accountId`,
426
+ * chosen from the candidate rows the app read. NEVER throws; see the module
427
+ * header for every outcome.
428
+ *
429
+ * `docs`: the account's policy documents (`registry_policies`), or `null` /
430
+ * `undefined` when the read failed (`read_error`). Rows of another species or
431
+ * another account are skipped, as the app's own query would have left them out.
432
+ * Mongo answers `[]` for a collection that does not exist, so on an empty answer
433
+ * the app must check that the policy store exists and pass
434
+ * `unavailableViewingPolicy("policy_store_absent")` when it does not (PAVE's
435
+ * reader checks with `listCollections`); an empty list from a store that exists
436
+ * means "none".
437
+ */
438
+ export function resolveViewingPolicy(
439
+ docs: readonly unknown[] | null | undefined,
440
+ query: ViewingPolicyQuery,
441
+ scope: ViewingPolicyScopeResolver,
442
+ ): GoverningViewingPolicy {
443
+ const accountRaw = typeof query.accountId === "string" ? query.accountId.trim() : "";
444
+ if (accountRaw === "") return unavailableViewingPolicy("account_unresolved");
445
+ if (!Array.isArray(docs)) return unavailableViewingPolicy("read_error");
446
+ const accountId = normalizedId(accountRaw);
447
+ const teamRaw = typeof query.teamId === "string" ? query.teamId.trim() : "";
448
+ const actingTeamId = teamRaw !== "" ? normalizedId(teamRaw) : null;
449
+
450
+ // The app's query: `species: "viewing"`, `account_id` = this Account (any stored
451
+ // id form, hex in either case).
452
+ const rows: RawViewingPolicyDoc[] = [];
453
+ for (const raw of docs) {
454
+ if (typeof raw !== "object" || raw === null) {
455
+ return unavailableViewingPolicy("read_error");
456
+ }
457
+ const d = raw as RawViewingPolicyDoc;
458
+ if (d.species !== VIEWING_POLICY_SPECIES) continue;
459
+ const owner = idText(d.account_id);
460
+ if (owner === null || normalizedId(owner) !== accountId) continue;
461
+ rows.push(d);
462
+ }
463
+
464
+ const teamRows: RawViewingPolicyDoc[] = [];
465
+ const accountRows: RawViewingPolicyDoc[] = [];
466
+ for (const d of rows) {
467
+ // A retired version never governs (the writer deactivates the prior one).
468
+ if (d.active === false) continue;
469
+ const placement = placementOf(d);
470
+ if (placement.kind === "unreadable") {
471
+ return unavailableViewingPolicy("unreadable_assignment", policyIdOf(d));
472
+ }
473
+ const governsHere =
474
+ placement.kind === "account" ||
475
+ (actingTeamId !== null && placement.teamId === actingTeamId);
476
+ if (!governsHere) continue; // another team's row
477
+ // Only `active: true` is live; an absent / null `active` is a row this reader
478
+ // cannot classify.
479
+ if (d.active !== true) {
480
+ return unavailableViewingPolicy("malformed_active", policyIdOf(d));
481
+ }
482
+ if (placement.kind === "account") accountRows.push(d);
483
+ else teamRows.push(d);
484
+ }
485
+
486
+ // Ruling (a): the team's own row REPLACES the account-wide rule.
487
+ const [source, candidates]: ["team" | "account", RawViewingPolicyDoc[]] =
488
+ teamRows.length > 0 ? ["team", teamRows] : ["account", accountRows];
489
+ if (candidates.length === 0) {
490
+ const retiredRowsOnly = rows.length > 0 && rows.every((d) => d.active === false);
491
+ return {
492
+ source: "none",
493
+ level: null,
494
+ visibleGroups: null,
495
+ scopeVocab: null,
496
+ policy: null,
497
+ accountId,
498
+ retiredRowsOnly,
499
+ rulePath: retiredRowsOnly
500
+ ? "no viewing policy on file (every viewing row is retired) — the role level alone decides"
501
+ : "no viewing policy on file — the role level alone decides",
502
+ };
503
+ }
504
+ const governing = governingRowOf(candidates);
505
+ if (!("row" in governing)) return governing;
506
+ return readRow(governing.row, source, accountId, scope);
507
+ }
508
+
509
+ /**
510
+ * The `teamViewingLevel` argument of `viewingLevelFromFunctions` /
511
+ * `resolveEffectiveViewingLevel` (contract § 3): the row's level when a row
512
+ * governs; `null` when none does (the role level alone decides); `0` when the
513
+ * policy could not be read (fail closed).
514
+ */
515
+ export function teamViewingLevelFromPolicy(policy: GoverningViewingPolicy): ViewingLevel | null {
516
+ switch (policy.source) {
517
+ case "team":
518
+ case "account":
519
+ return policy.level;
520
+ case "none":
521
+ return null;
522
+ default:
523
+ return 0;
524
+ }
525
+ }