@htilabs/platform-common-models 0.41.0 → 0.42.1

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.
@@ -0,0 +1,1293 @@
1
+ /**
2
+ * THE share resolver (Kickoff 13, GDR § 5.79 "ONE resolver per runtime"): the
3
+ * one pure read Thread and PAVE call to learn, for one sender (account +
4
+ * team) × one recipient × one purpose, which POLICY governs and at which
5
+ * level, the posture, whether the share is excluded as a whole, and which
6
+ * information-scope categories may leave — with the sending team's own policy
7
+ * as a CEILING, the Platform default read as the FOUR STATES, and reports
8
+ * never blocked at the policy or partner layer. Every answer names policy ·
9
+ * version · level (CAM invariant 17).
10
+ *
11
+ * Contract of record: platform-prototype `src/data.js` @ becfab4 (K13-18) —
12
+ * - `governingPolicyFor` L54533ff: the team row, `hit()` (one policy =
13
+ * one purpose; a policy that ANSWERS shares received never governs a
14
+ * send), the ladder (pair row → [inside: account default for inside →
15
+ * the platform's inside starter] → relationship → account default →
16
+ * Platform default), `done()` (the sending team's own policy rides as a
17
+ * ceiling on every rung's answer when it is not itself the governing one);
18
+ * - `effectiveCeiling` L54879ff: the posture composition (L54977-L54994;
19
+ * `POSTURE_RANK` L53645), the whole-share exclusion, which list binds
20
+ * (K13-12, L55121-L55130) and the per-category clamps 0 · 4 · 4a · 4b · 5 ·
21
+ * 5b · 5c · 5d · the group flip (L55140ff; 4 at L55165, 4b at L55185);
22
+ * - `platformStarterScope` / `starterDerivedState` L53708-L53760: the
23
+ * Platform default as the four CVC-133 states (`SHARE_STATE_KEYS` L53697,
24
+ * `SCOPE_LOCK_LABEL` L53698);
25
+ * - `scopeListCovers` L54696-L54706 (HANDOFF K13-14: a stored list may name
26
+ * a category, a kind above it or a row of it — never read it with a flat
27
+ * `indexOf`).
28
+ * Behavioural specs: `tools/smoke/flows/one-resolver-k13.js` (A–G) and
29
+ * `sharing-four-state-k13.js` (A–C); the test suite beside this file carries
30
+ * their vectors.
31
+ *
32
+ * Deliberately NOT here (prototype storage artefacts or relationship-row
33
+ * facts the caller holds): the `byPurpose` virtual fork, the legacy
34
+ * `sharingPolicies` narrowing rows (#451 moved them onto cards), the partner
35
+ * row's direction / team-scoped gates and item `restrictions`, deconfliction /
36
+ * viewing / release / routing species. The legacy cell chain (`sharingScopeEdits`
37
+ * → `effectiveCeiling` in chain.ts) arrives as `legacyCeiling` and is applied
38
+ * exactly where data.js applies it (clamp 5; review M6: seeded partner rules
39
+ * stay a ceiling even over an authored policy).
40
+ *
41
+ * Fail-closed conventions (this module's, stricter than canon where noted):
42
+ * - an unknown purpose (no Platform default supplied) governs nothing —
43
+ * `governing: null`, every category withheld, `excluded` says why (canon's
44
+ * `governingPolicyFor` returns null and the read leaks unrestricted; the
45
+ * prototype masks it upstream with `purposeIsLive`);
46
+ * - a document's `infoScope: null` OR an absent `infoScope` is "no category
47
+ * list" and is honoured, exactly as data.js reads it
48
+ * (`Array.isArray(gp.policy.infoScope) ? … : null`, L54979 / L55124 —
49
+ * the inside starter and a field-limits-only team ceiling are written
50
+ * that way, flow G); an explicit `[]` binds an empty list (canon too);
51
+ * a value that is present but is not a list of strings reads as `[]`
52
+ * (stricter than canon, which reads it as no list);
53
+ * - the account's Information Scope (clamps 4 / 4b) starts from the codebook:
54
+ * a CVC-236 heightened category or row (`shareableDefault: false` —
55
+ * immigration & legal status, the full instrument narratives) stays OFF
56
+ * until the account turns it on (`accountScope.categoriesOn` / `rowsOn`),
57
+ * exactly as data.js reads `cg ? cg.shareable : seedG.shareable` and
58
+ * `saved4b ? saved4b.shareable : it.shareable` — a caller that passes no
59
+ * `accountScope` gets the codebook's defaults, never everything;
60
+ * - an assignment whose `scope` is not one of the five kinds is skipped; two live
61
+ * documents on one cell — a store's key forbids it — resolve to the LATER one in
62
+ * `policies` (deterministic), and a duplicated id to the later document;
63
+ * - a tree with no System-metadata category has nothing Required by itself, and an
64
+ * excluded share then lets nothing through at all.
65
+ *
66
+ * Pure: no I/O, no SOT import, copies never live references.
67
+ */
68
+
69
+ import type { EffectiveSharingCeiling } from "./chain.js";
70
+ import type { SharingCeilingScope } from "./coverage.js";
71
+ import {
72
+ HTI_SHARE_PLATFORM_STARTER,
73
+ type SharingPlatformStarter,
74
+ } from "./starter.js";
75
+
76
+ // ─── Vocabulary ──────────────────────────────────────────────────────────────
77
+
78
+ /** The purposes that are REPORTS (data.js `REPORTING_PURPOSES`, L53354) — derived from the purpose, never a caller flag. */
79
+ export const SHARE_REPORTING_PURPOSES: ReadonlySet<string> = new Set([
80
+ "mandatory_reporting",
81
+ "authority_reporting",
82
+ ]);
83
+
84
+ export type SharePosture = "open" | "approval" | "blocked";
85
+
86
+ /** data.js `POSTURE_RANK` L53645 — stricter is higher; a policy can only RAISE the posture. */
87
+ export const SHARE_POSTURE_RANK: Readonly<Record<SharePosture, number>> =
88
+ Object.freeze({
89
+ open: 0,
90
+ approval: 1,
91
+ blocked: 2,
92
+ });
93
+
94
+ /** The four states of the Platform default (CVC-133 keys; data.js `SHARE_STATE_KEYS` L53697). */
95
+ export type SharePlatformState =
96
+ "always" | "default_on" | "default_off" | "never";
97
+
98
+ /** The words a person reads for each state (data.js `SCOPE_LOCK_LABEL` L53698). */
99
+ export const SHARE_PLATFORM_STATE_LABEL: Readonly<
100
+ Record<SharePlatformState, string>
101
+ > = Object.freeze({
102
+ always: "Required",
103
+ default_on: "Default On",
104
+ default_off: "Default Off",
105
+ never: "Blocked",
106
+ });
107
+
108
+ /** Where on the ladder the governing policy was found (data.js `ATTACH_LEVEL_LABEL` keys, L53646ff). */
109
+ export type ShareLevel =
110
+ | "team_row"
111
+ | "account_internal"
112
+ | "inside_starter"
113
+ | "relationship"
114
+ | "agency_default"
115
+ | "platform_starter";
116
+
117
+ export const SHARE_LEVEL_LABEL: Readonly<Record<ShareLevel | "team", string>> =
118
+ Object.freeze({
119
+ team_row: "attached on the team-to-team row",
120
+ relationship: "attached to this relationship",
121
+ agency_default: "your account's default for this purpose",
122
+ account_internal:
123
+ "your account's default for sharing between its own teams",
124
+ team: "your account's rule for this team",
125
+ platform_starter: "Platform default",
126
+ inside_starter: "the platform's default for sharing inside your account",
127
+ });
128
+
129
+ // ─── Inputs ──────────────────────────────────────────────────────────────────
130
+
131
+ /** One link of a policy to where it governs — a Relationship record (K13-3; data.js L53577-L53587). */
132
+ export type SharePolicyAssignment =
133
+ | { readonly scope: "account" }
134
+ | { readonly scope: "account_internal" }
135
+ | { readonly scope: "account_partner"; readonly partnerId: string }
136
+ | { readonly scope: "team"; readonly teamId: string }
137
+ | {
138
+ readonly scope: "team_pair";
139
+ readonly teamRowId: string;
140
+ readonly teamId?: string;
141
+ readonly partnerId?: string | null;
142
+ };
143
+
144
+ /** A policy document as the Admin Hub stores it (data.js `policyRecord` L53540ff). */
145
+ export interface SharePolicyDoc {
146
+ readonly id: string;
147
+ readonly familyId?: string;
148
+ /** Un-ledgered = v1 (`parseInt(p.version, 10) || 1`). */
149
+ readonly version?: number | string;
150
+ readonly name?: string;
151
+ /** ONE CVC-84 purpose (invariant 3). */
152
+ readonly purpose: string;
153
+ readonly species?: string;
154
+ readonly posture?: SharePosture | null;
155
+ readonly narrowOnly?: boolean;
156
+ /** v4 codes (categories, kinds, rows). `null` = no category list (no restriction at category grain). */
157
+ readonly infoScope?: readonly string[] | null;
158
+ /** Field-group grain: category → the rows of it that may leave (K13-5c). */
159
+ readonly infoScopeItems?: Readonly<Record<string, readonly string[]>> | null;
160
+ readonly assignments?: readonly SharePolicyAssignment[];
161
+ readonly origin?: {
162
+ readonly kind?: string;
163
+ readonly parentId?: string;
164
+ } | null;
165
+ /** `false` = still synced to the Platform default (K13-11): its list does not bind, the default's does. */
166
+ readonly edited?: boolean;
167
+ /** `false` = retired: never governs. */
168
+ readonly active?: boolean;
169
+ /** `answers: "received"` (K13-9b): a share-back policy never governs a share you start. */
170
+ readonly trigger?: { readonly answers?: string } | null;
171
+ }
172
+
173
+ /** The Platform default for one purpose, as the four states (data.js `platformStarterScope` L53719ff). */
174
+ export interface SharePlatformDefault {
175
+ readonly purpose: string;
176
+ /** The versioned tier document `pol-starter-<purpose>` (un-ledgered = 1). */
177
+ readonly version: number;
178
+ /** The STARTING scope — the lists `raw` as data.js keeps it: Required categories and `system` included, Blocked ones out. */
179
+ readonly raw: readonly string[];
180
+ /** category → state. */
181
+ readonly states: Readonly<Record<string, SharePlatformState>>;
182
+ /** Categories whose state is `always` (`system` not listed). */
183
+ readonly required: readonly string[];
184
+ /** Categories whose state is `never`. */
185
+ readonly blocked: readonly string[];
186
+ readonly edited?: boolean;
187
+ }
188
+
189
+ export type ShareRecipient =
190
+ | { readonly kind: "partner"; readonly id: string }
191
+ | { readonly kind: "external" }
192
+ | { readonly kind: "sibling_team"; readonly teamId: string };
193
+
194
+ export interface ShareResolveInput {
195
+ /** The v4 tree (an information-scope resolver, or anything with its four read methods). */
196
+ readonly scope: SharingCeilingScope;
197
+ /** Every policy document of the SENDING account (retired ones are skipped). */
198
+ readonly policies: readonly SharePolicyDoc[];
199
+ /** The Platform default for `purpose`; `null` = the purpose is unknown to the platform (fails closed). */
200
+ readonly platformDefault: SharePlatformDefault | null;
201
+ /** The sender: the account and, when the share is a team's, its team (`null` = a team-blind read: no pair row, no ceiling). */
202
+ /**
203
+ * The sender: its team when the share is a team's (`null` = a team-blind read: no pair row, no
204
+ * ceiling — the account's answer, not a team's). `accountId` is informational: `policies` must
205
+ * already be the SENDING account's documents (the resolver does not filter by account).
206
+ */
207
+ readonly sender: {
208
+ readonly accountId?: string;
209
+ readonly teamId: string | null;
210
+ };
211
+ /** The purpose's label for the Platform-default document names people read (`purpose` when absent). */
212
+ readonly purposeLabel?: string;
213
+ readonly recipient: ShareRecipient;
214
+ readonly purpose: string;
215
+ /** The matched team-to-team row (`matchTeamRow`), when the sender's team has one for this recipient. */
216
+ readonly teamRowId?: string | null;
217
+ /** Clamp 1: the purpose is switched off for the account (`isSharingPurposeDisabled` in chain.ts). Blocks reports too (flow M1). */
218
+ readonly purposeOff?: boolean;
219
+ /** The partner row's own posture, which a policy can only raise (data.js `effectiveCeiling`). Default `open`. */
220
+ readonly relationshipPosture?: SharePosture | null;
221
+ /**
222
+ * The legacy cell chain for callers still carrying `sharingScopeEdits`: pass `effectiveCeiling(...)`'s
223
+ * ANSWER (its `platform_default` rung is then ignored — the resolver reads that document itself;
224
+ * K13-12), or a plain list that binds as given; `null` / absent = none.
225
+ */
226
+ readonly legacyCeiling?: readonly string[] | EffectiveSharingCeiling | null;
227
+ /**
228
+ * The account's Information Scope (clamp 4 / 4b) as EXPLICIT choices over the codebook's
229
+ * defaults: `categoriesOff` / `rowsOff` = switched off; `categoriesOn` / `rowsOn` = a heightened
230
+ * (`shareableDefault: false`, CVC-236) category or row the account has turned ON. A code in
231
+ * neither list reads the codebook default — so heightened information stays off when this is
232
+ * absent (data.js `effectiveCeiling` clamps 4 / 4b). A code in both lists is off.
233
+ */
234
+ readonly accountScope?: {
235
+ readonly categoriesOff?: readonly string[];
236
+ readonly rowsOff?: readonly string[];
237
+ readonly categoriesOn?: readonly string[];
238
+ readonly rowsOn?: readonly string[];
239
+ } | null;
240
+ }
241
+
242
+ // ─── Output ──────────────────────────────────────────────────────────────────
243
+
244
+ export interface ShareNamedPolicy {
245
+ readonly id: string;
246
+ readonly familyId: string;
247
+ readonly name: string;
248
+ readonly version: number;
249
+ readonly level: ShareLevel | "team";
250
+ readonly levelLabel: string;
251
+ readonly posture: SharePosture | null;
252
+ readonly infoScope: string[] | null;
253
+ /** Field-group grain, when the document carries it (a copy). */
254
+ readonly infoScopeItems: Record<string, string[]> | null;
255
+ readonly edited: boolean;
256
+ readonly origin: string | null;
257
+ readonly rulePath: string;
258
+ }
259
+
260
+ export interface ShareCategoryEntry {
261
+ readonly allowed: boolean;
262
+ readonly reason: string;
263
+ readonly rulePath: string;
264
+ /** Set when the Platform default marks the category Required (`always`): nothing account-grain removes it. */
265
+ readonly platformRequired: { readonly rulePath: string } | null;
266
+ /** Rows under the platform safety floor — never leave. */
267
+ readonly floorItems: string[];
268
+ /**
269
+ * Rows the governing list / the account's heightened toggles / the ceiling leave out. A code is
270
+ * withheld when it OR AN ANCESTOR is listed here. Since 0.42.1 a grouping is listed only when
271
+ * nothing beneath it is covered — when a list names some of its rows, the grouping is NOT listed
272
+ * and its uncovered rows are listed one by one instead. So a grouping code's absence here does
273
+ * not mean the whole grouping may leave: for a send decision read `shareRowCeiling` +
274
+ * `rowsOverCeiling`, never a grouping-code check against `excludedItems` alone.
275
+ */
276
+ readonly excludedItems: string[];
277
+ readonly excludedReason: string | null;
278
+ /** Rows the sending team's own policy leaves out (5d). Same shape and same caveat as `excludedItems`. */
279
+ readonly teamExcludedItems: string[];
280
+ readonly teamExcludedReason: string | null;
281
+ }
282
+
283
+ export interface ShareResolution {
284
+ /** `false` = the share as a whole is excluded (`excluded` says why). */
285
+ readonly allowed: boolean;
286
+ readonly posture: SharePosture;
287
+ readonly postureSource: "relationship" | "policy" | "team_ceiling";
288
+ readonly excluded: {
289
+ readonly reason: string;
290
+ readonly rulePath: string;
291
+ } | null;
292
+ /** A reporting purpose under a `blocked` posture: never excluded; the note names what blocks ordinary sharing. */
293
+ readonly reportCarveOut: {
294
+ readonly note: string;
295
+ readonly rulePath: string;
296
+ } | null;
297
+ /** The policy that governs; `null` only for an unknown purpose (fails closed). */
298
+ readonly governing: ShareNamedPolicy | null;
299
+ /** The sending team's own policy for the purpose, when it is not itself the governing one. */
300
+ readonly teamCeiling: ShareNamedPolicy | null;
301
+ /** A share to a sibling team of the same account. */
302
+ readonly inside: boolean;
303
+ /** Every live category of the tree, in tree order. */
304
+ readonly scope: Readonly<Record<string, ShareCategoryEntry>>;
305
+ /** The categories with `allowed === true`, tree order — the list the coverage readers take. */
306
+ readonly allowedCategories: string[];
307
+ readonly rulePath: string;
308
+ }
309
+
310
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
311
+
312
+ const own = <V>(record: unknown, key: string): V | undefined =>
313
+ record !== null &&
314
+ typeof record === "object" &&
315
+ Object.prototype.hasOwnProperty.call(record, key)
316
+ ? ((record as Record<string, V>)[key] as V)
317
+ : undefined;
318
+
319
+ const isStringList = (v: unknown): v is readonly string[] =>
320
+ Array.isArray(v) && v.every((c) => typeof c === "string");
321
+
322
+ const versionOf = (v: unknown): number => {
323
+ const n = typeof v === "number" ? v : parseInt(String(v), 10);
324
+ return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 1;
325
+ };
326
+
327
+ /**
328
+ * `infoScope` as the resolver reads it: `null` or absent = no list (data.js reads every
329
+ * non-array as "no list", L54979 / L55124); a list of strings = that list (`[]` binds an empty
330
+ * list, as in canon); any other present value = `[]` (fail closed; stricter than canon).
331
+ */
332
+ const docList = (v: unknown): string[] | null =>
333
+ v === null || v === undefined ? null : isStringList(v) ? [...v] : [];
334
+
335
+ /**
336
+ * data.js `scopeListCovers` (L54696-L54706), on the v4 tree: a non-array list
337
+ * covers everything; a category is covered when the list names it or an
338
+ * ANCESTOR (a kind such as `family`, a branch); with a row `it`, the row is
339
+ * covered when it or an ancestor is named; without one, a category is also
340
+ * covered when the list names any DESCENDANT of it (a row or grouping).
341
+ */
342
+ export function scopeListCovers(
343
+ scope: SharingCeilingScope,
344
+ list: readonly string[] | null | undefined,
345
+ categoryCode: string,
346
+ rowCode?: string,
347
+ ): boolean {
348
+ if (!Array.isArray(list)) return true;
349
+ const set = new Set(list);
350
+ if (scope.ancestorsOf(categoryCode).some((c) => set.has(c))) return true;
351
+ if (rowCode !== undefined)
352
+ return scope.ancestorsOf(rowCode).some((c) => set.has(c));
353
+ return list.some((id) =>
354
+ scope.ancestorsOf(id).slice(1).includes(categoryCode),
355
+ );
356
+ }
357
+
358
+ /** `scopeStrictCovers` (L54710ff): the list names the category or an ancestor — never a descendant. */
359
+ export function scopeListStrictlyCovers(
360
+ scope: SharingCeilingScope,
361
+ list: readonly string[] | null | undefined,
362
+ categoryCode: string,
363
+ ): boolean {
364
+ if (!Array.isArray(list)) return true;
365
+ const set = new Set(list);
366
+ return scope.ancestorsOf(categoryCode).some((c) => set.has(c));
367
+ }
368
+
369
+ /** The attachment index the ladder reads (data.js `effectiveAttachmentIndex` L53558ff), built from `assignments` only. */
370
+ export interface ShareAttachmentIndex {
371
+ readonly agencyDefaults: Readonly<Record<string, string>>;
372
+ readonly internalDefaults: Readonly<Record<string, string>>;
373
+ readonly relationships: Readonly<
374
+ Record<string, Readonly<Record<string, string>>>
375
+ >;
376
+ readonly teamRows: Readonly<Record<string, Readonly<Record<string, string>>>>;
377
+ readonly teams: Readonly<Record<string, Readonly<Record<string, string>>>>;
378
+ }
379
+
380
+ const isLiveDoc = (p: SharePolicyDoc | null | undefined): p is SharePolicyDoc =>
381
+ p !== null &&
382
+ typeof p === "object" &&
383
+ typeof p.id === "string" &&
384
+ p.id !== "" &&
385
+ typeof p.purpose === "string" &&
386
+ p.active !== false;
387
+
388
+ export function attachmentIndexFromPolicies(
389
+ policies: readonly SharePolicyDoc[] | null | undefined,
390
+ ): ShareAttachmentIndex {
391
+ // Null-prototype maps: a key such as `__proto__` is a key, never the prototype. Two live
392
+ // documents on one cell: the LATER one in `policies` wins (deterministic; a store's key forbids it).
393
+ const nullMap = <V>(): Record<string, V> =>
394
+ Object.create(null) as Record<string, V>;
395
+ const agencyDefaults = nullMap<string>();
396
+ const internalDefaults = nullMap<string>();
397
+ const relationships = nullMap<Record<string, string>>();
398
+ const teamRows = nullMap<Record<string, string>>();
399
+ const teams = nullMap<Record<string, string>>();
400
+ const put = (
401
+ map: Record<string, Record<string, string>>,
402
+ key: string,
403
+ purpose: string,
404
+ id: string,
405
+ ): void => {
406
+ const row = Object.prototype.hasOwnProperty.call(map, key)
407
+ ? map[key]
408
+ : (map[key] = nullMap<string>());
409
+ row[purpose] = id;
410
+ };
411
+ for (const p of Array.isArray(policies) ? policies : []) {
412
+ if (!isLiveDoc(p)) continue;
413
+ for (const a of Array.isArray(p.assignments) ? p.assignments : []) {
414
+ if (a === null || typeof a !== "object") continue;
415
+ switch (a.scope) {
416
+ case "account":
417
+ agencyDefaults[p.purpose] = p.id;
418
+ break;
419
+ case "account_internal":
420
+ internalDefaults[p.purpose] = p.id;
421
+ break;
422
+ case "account_partner":
423
+ if (typeof a.partnerId === "string" && a.partnerId !== "")
424
+ put(relationships, a.partnerId, p.purpose, p.id);
425
+ break;
426
+ case "team":
427
+ if (typeof a.teamId === "string" && a.teamId !== "")
428
+ put(teams, a.teamId, p.purpose, p.id);
429
+ break;
430
+ case "team_pair":
431
+ if (typeof a.teamRowId === "string" && a.teamRowId !== "")
432
+ put(teamRows, a.teamRowId, p.purpose, p.id);
433
+ break;
434
+ default:
435
+ break; // an unknown scope governs nowhere
436
+ }
437
+ }
438
+ }
439
+ return { agencyDefaults, internalDefaults, relationships, teamRows, teams };
440
+ }
441
+
442
+ /** A team-to-team row as the account stores it (data.js `teamRows` / `teamPairs`, L53493-L53514). */
443
+ export interface ShareTeamRowLike {
444
+ readonly id: string;
445
+ readonly myTeamId?: string | null;
446
+ readonly their?: { readonly type?: string; readonly id?: string } | null;
447
+ }
448
+
449
+ /**
450
+ * The row the first rung reads (data.js `internalPairRow` / `partnerTeamRow`,
451
+ * L53493-L53514). `rows` is ONE store, as the prototype keeps them: for a
452
+ * sibling team, the account's internal pairs (`policies.teamPairs`); for a
453
+ * partner, THAT partner's team rows (`partnerOverrides[partner].teamRows`, or
454
+ * the seeded rows) — never a flat list across partners. A sibling team's row
455
+ * is the one whose `their` is that team (direction matters — the sender
456
+ * first); a partner's row under a team-scoped relationship is the team's
457
+ * FIRST row, under an all-teams relationship the row whose `their` is absent,
458
+ * not a team, or this very partner. Rows that carry only share-back
459
+ * (answers-received) policies are dropped first. An external recipient has
460
+ * no row.
461
+ */
462
+ export function matchTeamRow(
463
+ rows: readonly ShareTeamRowLike[] | null | undefined,
464
+ teamId: string | null | undefined,
465
+ recipient: ShareRecipient,
466
+ options: {
467
+ readonly scopeMode?: "team_scoped" | "all_teams";
468
+ readonly shareBackOnlyRowIds?: readonly string[];
469
+ } = {},
470
+ ): string | null {
471
+ if (typeof teamId !== "string" || teamId === "" || !Array.isArray(rows))
472
+ return null;
473
+ const drop = new Set(options.shareBackOnlyRowIds ?? []);
474
+ const live = rows.filter(
475
+ (r): r is ShareTeamRowLike =>
476
+ r !== null &&
477
+ typeof r === "object" &&
478
+ typeof r.id === "string" &&
479
+ !drop.has(r.id),
480
+ );
481
+ if (recipient.kind === "sibling_team") {
482
+ // data.js `internalPairRow` (L53509-L53514): every row of the internal-pairs store is a
483
+ // team-to-team row (`teamRowIndex` L53481 types it `team`), so it matches on `their.id`
484
+ // alone — a stored pair row without `their.type` still governs.
485
+ return (
486
+ live.find(
487
+ (r) => r.myTeamId === teamId && r.their?.id === recipient.teamId,
488
+ )?.id ?? null
489
+ );
490
+ }
491
+ if (recipient.kind === "external") return null;
492
+ if (options.scopeMode === "team_scoped")
493
+ return live.find((r) => r.myTeamId === teamId)?.id ?? null;
494
+ return (
495
+ live.find(
496
+ (r) =>
497
+ r.myTeamId === teamId &&
498
+ (!r.their || r.their.type !== "team" || r.their.id === recipient.id),
499
+ )?.id ?? null
500
+ );
501
+ }
502
+
503
+ // ─── The four states ─────────────────────────────────────────────────────────
504
+
505
+ /**
506
+ * Derive one purpose's Platform default as the four states (data.js
507
+ * `starterDerivedState` L53708 + `platformStarterScope` L53719ff),
508
+ * for every live CATEGORY of the tree, in this order — the first rule wins:
509
+ * System metadata → `always`; a category the platform requires for the
510
+ * purpose → `always`; off-by-default (heightened) → `never`; the seed list
511
+ * covers it (itself, an ancestor, or any row of it) → `default_on`, else
512
+ * `default_off`. An explicit bound overrides it for every category but
513
+ * `system`. `raw` is the starting scope: the seed's codes whose category is
514
+ * not Blocked or bound off, plus every bound-on and Required category, plus
515
+ * `system`.
516
+ */
517
+ export function derivePlatformDefault(
518
+ scope: SharingCeilingScope,
519
+ purpose: string,
520
+ seedList: readonly string[] | null | undefined,
521
+ options: {
522
+ readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;
523
+ readonly required?: readonly string[] | null;
524
+ readonly version?: number | string;
525
+ readonly edited?: boolean;
526
+ } = {},
527
+ ): SharePlatformDefault {
528
+ const seed = isStringList(seedList) ? [...seedList] : [];
529
+ const req = new Set(options.required ?? []);
530
+ const states: Record<string, SharePlatformState> = {};
531
+ const required: string[] = [];
532
+ const blocked: string[] = [];
533
+ const systemCode = systemCategoryOf(scope);
534
+ for (const g of liveCategories(scope)) {
535
+ let state: SharePlatformState;
536
+ if (g === systemCode) state = "always";
537
+ else if (req.has(g)) state = "always";
538
+ else if (scope.row(g)?.shareableDefault === false) state = "never";
539
+ else state = scopeListCovers(scope, seed, g) ? "default_on" : "default_off";
540
+ const bound = own<unknown>(options.bounds, g);
541
+ if (
542
+ g !== systemCode &&
543
+ (bound === "always" ||
544
+ bound === "default_on" ||
545
+ bound === "default_off" ||
546
+ bound === "never")
547
+ )
548
+ state = bound;
549
+ states[g] = state;
550
+ if (state === "always" && g !== systemCode) required.push(g);
551
+ if (state === "never") blocked.push(g);
552
+ }
553
+ const categoryOf = (code: string): string | undefined =>
554
+ scope.ancestorsOf(code).find((c) => scope.row(c)?.rowType === "category");
555
+ const raw: string[] = [];
556
+ const push = (c: string): void => {
557
+ if (!raw.includes(c)) raw.push(c);
558
+ };
559
+ for (const code of seed) {
560
+ const g = categoryOf(code);
561
+ if (g === undefined) {
562
+ // A kind or a branch: it stands for its categories — keep the ones that are on, by name,
563
+ // so a category bound off beneath it is not covered by the kind (review r1 #4).
564
+ for (const [cat, st] of Object.entries(states)) {
565
+ if (
566
+ (st === "always" || st === "default_on") &&
567
+ scope.ancestorsOf(cat).includes(code)
568
+ )
569
+ push(cat);
570
+ }
571
+ continue;
572
+ }
573
+ const st = states[g];
574
+ if (st === "never" || st === "default_off") continue;
575
+ push(code);
576
+ }
577
+ for (const [g, st] of Object.entries(states)) {
578
+ if (
579
+ (st === "always" || st === "default_on") &&
580
+ !scopeListCovers(scope, raw, g)
581
+ )
582
+ push(g);
583
+ }
584
+ if (systemCode !== undefined) push(systemCode);
585
+ return {
586
+ purpose,
587
+ version: versionOf(options.version),
588
+ raw,
589
+ states,
590
+ required,
591
+ blocked,
592
+ edited: options.edited === true,
593
+ };
594
+ }
595
+
596
+ // ─── Tree reads ──────────────────────────────────────────────────────────────
597
+
598
+ const treeCache = new WeakMap<
599
+ object,
600
+ {
601
+ categories: string[];
602
+ system: string | undefined;
603
+ leaves: Map<string, string[]>;
604
+ descendants: Map<string, string[]>;
605
+ }
606
+ >();
607
+
608
+ function treeIndex(scope: SharingCeilingScope) {
609
+ const hit = treeCache.get(scope);
610
+ if (hit) return hit;
611
+ const live = (code: string): boolean =>
612
+ scope.row(code) !== undefined &&
613
+ scope.ancestorsOf(code).every((c) => scope.row(c)?.status !== "retired");
614
+ const categories = scope.rows
615
+ .filter((r) => r.rowType === "category" && live(r.scopeCode))
616
+ .map((r) => r.scopeCode);
617
+ const systemInfoPath =
618
+ scope.row("system_info") !== undefined
619
+ ? scope.ancestorsOf("system_info")
620
+ : [];
621
+ const system =
622
+ systemInfoPath.find((c) => categories.includes(c)) ??
623
+ categories.find((g) => g === "system");
624
+ const descendants = new Map<string, string[]>();
625
+ const leaves = new Map<string, string[]>();
626
+ for (const g of categories) {
627
+ const all: string[] = [];
628
+ const walk = (code: string): void => {
629
+ for (const c of scope.childrenOf(code)) {
630
+ if (!live(c)) continue;
631
+ all.push(c);
632
+ walk(c);
633
+ }
634
+ };
635
+ walk(g);
636
+ descendants.set(g, all);
637
+ leaves.set(
638
+ g,
639
+ all.filter((c) => !scope.childrenOf(c).some(live)),
640
+ );
641
+ }
642
+ const out = { categories, system, leaves, descendants };
643
+ treeCache.set(scope, out);
644
+ return out;
645
+ }
646
+
647
+ /** The live categories of the tree, in tree order. */
648
+ export function liveCategories(scope: SharingCeilingScope): string[] {
649
+ return [...treeIndex(scope).categories];
650
+ }
651
+
652
+ /** The System-metadata category (`system`, the parent of `system_info`). */
653
+ export function systemCategoryOf(
654
+ scope: SharingCeilingScope,
655
+ ): string | undefined {
656
+ return treeIndex(scope).system;
657
+ }
658
+
659
+ /**
660
+ * The legacy cell chain's list as clamp 5 reads it: a plain list binds as given; an
661
+ * `effectiveCeiling` answer binds only when an ACCOUNT rule answered (`partner_rule`,
662
+ * `seeded_partner_rule`, `account_default`) — its `platform_default` rung is the same document
663
+ * the resolver already reads as the Platform default (passing it as a legacy list would clamp
664
+ * every authored policy to the starter and undo K13-12), and `purpose_disabled` / `none` are
665
+ * carried by `purposeOff` / the missing Platform default.
666
+ */
667
+ function legacyCeilingList(
668
+ v: ShareResolveInput["legacyCeiling"],
669
+ ): string[] | null {
670
+ if (v === null || v === undefined) return null;
671
+ if (isStringList(v)) return [...v];
672
+ if (typeof v === "object" && "rung" in v) {
673
+ const r = (v as EffectiveSharingCeiling).rung;
674
+ if (
675
+ r === "partner_rule" ||
676
+ r === "seeded_partner_rule" ||
677
+ r === "account_default"
678
+ ) {
679
+ return isStringList(v.allowed) ? [...v.allowed] : [];
680
+ }
681
+ return null;
682
+ }
683
+ return null;
684
+ }
685
+
686
+ /**
687
+ * The categories the platform REQUIRES for a purpose (data.js `scopeRequiredByPurpose`,
688
+ * L40836-L40839): Identifying information on every report. Read by `platformDefaultFor`.
689
+ */
690
+ export const HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE: Readonly<
691
+ Record<string, readonly string[]>
692
+ > = Object.freeze({
693
+ mandatory_reporting: Object.freeze(["identifying"]),
694
+ authority_reporting: Object.freeze(["identifying"]),
695
+ });
696
+
697
+ /**
698
+ * The Platform default for one purpose from the PUBLISHED starter (the day-one tier document,
699
+ * version 1, no bounds): `derivePlatformDefault` over `HTI_SHARE_PLATFORM_STARTER.scopeByPurpose`
700
+ * and {@link HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE}. `null` for a purpose the starter has no row
701
+ * for (the resolver then fails closed). Once the platform stores `pol-starter-<purpose>` as a
702
+ * versioned document, pass ITS list, bounds and version instead.
703
+ */
704
+ export function platformDefaultFor(
705
+ scope: SharingCeilingScope,
706
+ purpose: string,
707
+ options: {
708
+ readonly starter?: SharingPlatformStarter;
709
+ readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;
710
+ readonly version?: number | string;
711
+ readonly edited?: boolean;
712
+ } = {},
713
+ ): SharePlatformDefault | null {
714
+ const starter = options.starter ?? HTI_SHARE_PLATFORM_STARTER;
715
+ const seed = own<readonly string[]>(starter.scopeByPurpose, purpose);
716
+ if (!isStringList(seed)) return null;
717
+ return derivePlatformDefault(scope, purpose, seed, {
718
+ required:
719
+ own<readonly string[]>(HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE, purpose) ??
720
+ [],
721
+ bounds: options.bounds ?? null,
722
+ version: options.version ?? 1,
723
+ edited: options.edited === true,
724
+ });
725
+ }
726
+
727
+ /**
728
+ * The ROW-grain ceiling one resolution amounts to — the list the item-grain readers take
729
+ * (`maskSelectionToCeiling` for the composer, `rowsOverCeiling` for the send door): each
730
+ * allowed category by its own code when no row of it is withheld, else its live rows minus
731
+ * the withheld ones (the governing list's, the account's heightened rows, the field-group
732
+ * limits, the team's). Rows under the platform floor are never listed (the readers never let
733
+ * them through). `[]` for an excluded share — only System metadata rides.
734
+ */
735
+ export function shareRowCeiling(
736
+ resolution: Pick<ShareResolution, "allowed" | "scope" | "allowedCategories">,
737
+ scope: SharingCeilingScope,
738
+ ): string[] {
739
+ if (!resolution.allowed) return [];
740
+ const out: string[] = [];
741
+ for (const g of resolution.allowedCategories) {
742
+ const e = own<ShareCategoryEntry>(resolution.scope, g);
743
+ if (e === undefined) continue;
744
+ const withheld = new Set([
745
+ ...e.excludedItems,
746
+ ...e.teamExcludedItems,
747
+ ...e.floorItems,
748
+ ]);
749
+ if (withheld.size === 0) {
750
+ out.push(g);
751
+ continue;
752
+ }
753
+ // walk down from the category: a row stands at its own grain when nothing beneath it is
754
+ // withheld; else its surviving children stand in for it; a withheld row (and all beneath)
755
+ // is dropped — so `instrument_full` with every full row off is not listed at all.
756
+ const live = (c: string): boolean =>
757
+ scope.row(c) !== undefined &&
758
+ scope.ancestorsOf(c).every((a) => scope.row(a)?.status !== "retired");
759
+ const anyWithheldBeneath = (c: string): boolean =>
760
+ scope
761
+ .childrenOf(c)
762
+ .some((k) => live(k) && (withheld.has(k) || anyWithheldBeneath(k)));
763
+ const visit = (c: string): void => {
764
+ if (withheld.has(c) || !live(c)) return;
765
+ if (!anyWithheldBeneath(c)) {
766
+ out.push(c);
767
+ return;
768
+ }
769
+ for (const k of scope.childrenOf(c)) visit(k);
770
+ };
771
+ for (const k of scope.childrenOf(g)) visit(k);
772
+ }
773
+ return out;
774
+ }
775
+
776
+ // ─── The resolver ────────────────────────────────────────────────────────────
777
+
778
+ interface Hit {
779
+ readonly policy: SharePolicyDoc;
780
+ readonly level: ShareLevel | "team";
781
+ readonly version: number;
782
+ readonly rulePath: string;
783
+ }
784
+
785
+ function named(h: Hit): ShareNamedPolicy {
786
+ const p = h.policy;
787
+ return {
788
+ id: p.id,
789
+ familyId:
790
+ typeof p.familyId === "string" && p.familyId !== "" ? p.familyId : p.id,
791
+ name: typeof p.name === "string" ? p.name : p.id,
792
+ version: h.version,
793
+ level: h.level,
794
+ levelLabel: SHARE_LEVEL_LABEL[h.level],
795
+ posture:
796
+ p.posture === "open" ||
797
+ p.posture === "approval" ||
798
+ p.posture === "blocked"
799
+ ? p.posture
800
+ : null,
801
+ infoScope: docList(p.infoScope),
802
+ infoScopeItems: copyItems(p.infoScopeItems),
803
+ edited: p.edited === true,
804
+ origin: typeof p.origin?.kind === "string" ? p.origin.kind : null,
805
+ rulePath: h.rulePath,
806
+ };
807
+ }
808
+
809
+ const uniq = (list: readonly string[]): string[] => [...new Set(list)];
810
+
811
+ const copyItems = (v: unknown): Record<string, string[]> | null => {
812
+ if (v === null || typeof v !== "object") return null;
813
+ const out: Record<string, string[]> = {};
814
+ for (const [k, rows] of Object.entries(v as Record<string, unknown>)) {
815
+ if (isStringList(rows)) out[k] = [...rows];
816
+ }
817
+ return out;
818
+ };
819
+
820
+ /**
821
+ * THE read. See the module header; the algorithm, step by step:
822
+ * 1. the ladder (`governingPolicyFor`): pair row → [inside: the account's
823
+ * inside default → the platform's inside starter, stop] → relationship
824
+ * (the partner id, or `__external__`) → the account default → the
825
+ * Platform default (a versioned document, `pol-starter-<purpose>`);
826
+ * 2. the sending team's own policy for the purpose rides as a CEILING when
827
+ * it is not the governing one (inside the account too);
828
+ * 3. posture: the relationship's, raised (never lowered) by the governing
829
+ * policy, then by the ceiling — stricter wins;
830
+ * 4. the whole share: the purpose switch excludes it (reports too); a
831
+ * `blocked` posture excludes a discretionary share and CARVES OUT a
832
+ * report (never blocked at the policy / partner layer);
833
+ * 5. per category: Required (`system`, or the Platform default's `always`)
834
+ * bypasses every account-grain clamp; else the account's toggle (4), the
835
+ * Platform default's Blocked (4a, not inside), the binding list (5: the
836
+ * legacy cell chain's list or the Platform default's starting scope — the
837
+ * governing policy's own list when it is authored (5b); K13-12), the
838
+ * team ceiling's list (5d); rows: the floor, heightened rows off (4b),
839
+ * field-group limits (5c), and a category every row of which is withheld
840
+ * is withheld (the group flip).
841
+ */
842
+ export function resolveShare(input: ShareResolveInput): ShareResolution {
843
+ const { scope, purpose, recipient } = input;
844
+ if (typeof purpose !== "string" || purpose === "")
845
+ throw new TypeError("resolveShare: purpose must be a share purpose code");
846
+ const teamId =
847
+ typeof input.sender?.teamId === "string" && input.sender.teamId !== ""
848
+ ? input.sender.teamId
849
+ : null;
850
+ const inside = recipient.kind === "sibling_team";
851
+ const recipientKey =
852
+ recipient.kind === "partner"
853
+ ? recipient.id
854
+ : recipient.kind === "external"
855
+ ? "__external__"
856
+ : null;
857
+ if (
858
+ recipient.kind === "partner" &&
859
+ (typeof recipient.id !== "string" || recipient.id === "")
860
+ ) {
861
+ throw new TypeError("resolveShare: a partner recipient needs an id");
862
+ }
863
+ const report = SHARE_REPORTING_PURPOSES.has(purpose);
864
+ const pd = input.platformDefault ?? null;
865
+ const purposeLabel =
866
+ typeof input.purposeLabel === "string" && input.purposeLabel !== ""
867
+ ? input.purposeLabel
868
+ : purpose;
869
+ const pdRaw = pd === null ? [] : isStringList(pd.raw) ? [...pd.raw] : [];
870
+ const pdRequired =
871
+ pd === null ? [] : isStringList(pd.required) ? [...pd.required] : [];
872
+ const pdBlocked =
873
+ pd === null ? [] : isStringList(pd.blocked) ? [...pd.blocked] : [];
874
+ const policies = (Array.isArray(input.policies) ? input.policies : []).filter(
875
+ isLiveDoc,
876
+ );
877
+ const byId = new Map<string, SharePolicyDoc>();
878
+ for (const p of policies) byId.set(p.id, p);
879
+ const att = attachmentIndexFromPolicies(policies);
880
+ const tree = treeIndex(scope);
881
+ const systemCode = tree.system;
882
+
883
+ // 1. the ladder
884
+ const hit = (
885
+ id: string | undefined,
886
+ level: ShareLevel | "team",
887
+ ): Hit | null => {
888
+ const p = id === undefined ? undefined : byId.get(id);
889
+ if (p === undefined || p.purpose !== purpose) return null;
890
+ if (p.trigger?.answers === "received") return null;
891
+ const v = versionOf(p.version);
892
+ const name = typeof p.name === "string" ? p.name : p.id;
893
+ return {
894
+ policy: p,
895
+ level,
896
+ version: v,
897
+ rulePath: `sharingPurposePolicies[${p.id}] v${v} (policy “${name}” — ${SHARE_LEVEL_LABEL[level]})`,
898
+ };
899
+ };
900
+ const cell = (
901
+ map: Record<string, Readonly<Record<string, string>>>,
902
+ key: string,
903
+ ) => own<string>(own<Readonly<Record<string, string>>>(map, key), purpose);
904
+ let gov: Hit | null = null;
905
+ // An unknown purpose (no Platform default) governs nothing — the ladder is not read at all
906
+ // (review r1 #1: a policy linked under it must not leak its own list).
907
+ const purposeKnown = pd !== null;
908
+ const teamRowId =
909
+ purposeKnown &&
910
+ teamId !== null &&
911
+ recipient.kind !== "external" &&
912
+ typeof input.teamRowId === "string" &&
913
+ input.teamRowId !== ""
914
+ ? input.teamRowId
915
+ : null;
916
+ if (teamRowId !== null) gov = hit(cell(att.teamRows, teamRowId), "team_row");
917
+ if (gov === null && inside && purposeKnown) {
918
+ gov = hit(own<string>(att.internalDefaults, purpose), "account_internal");
919
+ if (gov === null && pd !== null) {
920
+ const starter: SharePolicyDoc = {
921
+ id: `pol-inside-starter-${purpose}`,
922
+ name: `${purposeLabel} — Inside your account (platform default)`,
923
+ purpose,
924
+ infoScope: null,
925
+ posture: "open",
926
+ version: 1,
927
+ origin: { kind: "starter" },
928
+ };
929
+ gov = {
930
+ policy: starter,
931
+ level: "inside_starter",
932
+ version: 1,
933
+ rulePath: `${starter.id} v1 (${SHARE_LEVEL_LABEL.inside_starter} — the full record, open)`,
934
+ };
935
+ }
936
+ }
937
+ if (gov === null && !inside && purposeKnown && recipientKey !== null) {
938
+ gov = hit(cell(att.relationships, recipientKey), "relationship");
939
+ if (gov === null)
940
+ gov = hit(own<string>(att.agencyDefaults, purpose), "agency_default");
941
+ if (gov === null && pd !== null) {
942
+ const starter: SharePolicyDoc = {
943
+ id: `pol-starter-${purpose}`,
944
+ name: `${purposeLabel} — Platform default`,
945
+ purpose,
946
+ infoScope: pdRaw.filter((c) => c !== systemCode),
947
+ posture: "open",
948
+ version: pd.version,
949
+ origin: { kind: "platform_starter" },
950
+ edited: false,
951
+ };
952
+ gov = {
953
+ policy: starter,
954
+ level: "platform_starter",
955
+ version: pd.version,
956
+ rulePath: `${starter.id} v${pd.version} (${SHARE_LEVEL_LABEL.platform_starter})`,
957
+ };
958
+ }
959
+ }
960
+
961
+ // 2. the team ceiling
962
+ let tc: Hit | null = null;
963
+ if (teamId !== null && gov !== null) {
964
+ const t = hit(cell(att.teams, teamId), "team");
965
+ if (t !== null && t.policy.id !== gov.policy.id) tc = t;
966
+ }
967
+ const govNamed = gov === null ? null : named(gov);
968
+ const tcNamed = tc === null ? null : named(tc);
969
+ const rulePath =
970
+ gov === null
971
+ ? `no Platform default for purpose “${purpose}” — nothing governs (fails closed)`
972
+ : tc === null
973
+ ? gov.rulePath
974
+ : `${gov.rulePath} ∩ ${tc.rulePath} (the sending team's own policy is a ceiling — only what both allow)`;
975
+
976
+ // 3. posture
977
+ let posture: SharePosture =
978
+ input.relationshipPosture === "approval" ||
979
+ input.relationshipPosture === "blocked"
980
+ ? input.relationshipPosture
981
+ : "open";
982
+ let postureSource: ShareResolution["postureSource"] = "relationship";
983
+ let posturePol: ShareNamedPolicy | null = null;
984
+ if (
985
+ govNamed?.posture &&
986
+ SHARE_POSTURE_RANK[govNamed.posture] > SHARE_POSTURE_RANK[posture]
987
+ ) {
988
+ posture = govNamed.posture;
989
+ postureSource = "policy";
990
+ posturePol = govNamed;
991
+ }
992
+ if (
993
+ tcNamed?.posture &&
994
+ SHARE_POSTURE_RANK[tcNamed.posture] > SHARE_POSTURE_RANK[posture]
995
+ ) {
996
+ posture = tcNamed.posture;
997
+ postureSource = "team_ceiling";
998
+ posturePol = tcNamed;
999
+ }
1000
+
1001
+ // 4. the whole share
1002
+ let excluded: ShareResolution["excluded"] = null;
1003
+ let reportCarveOut: ShareResolution["reportCarveOut"] = null;
1004
+ if (gov === null) {
1005
+ excluded = {
1006
+ reason: `No Platform default for purpose “${purpose}” — nothing may leave under it`,
1007
+ rulePath,
1008
+ };
1009
+ } else if (input.purposeOff === true) {
1010
+ excluded = {
1011
+ reason: "Share purpose disabled by your account's sharing policy",
1012
+ rulePath: `purposeOverrides[${purpose}] = false`,
1013
+ };
1014
+ } else if (posture === "blocked") {
1015
+ const pol = posturePol; // null = the relationship's own posture blocks (review r1 #3)
1016
+ const path =
1017
+ pol === null
1018
+ ? "relationship posture = blocked"
1019
+ : `sharingPurposePolicies[${pol.id}].posture=blocked (policy “${pol.name}” — ${pol.levelLabel})`;
1020
+ if (report) {
1021
+ reportCarveOut = {
1022
+ note:
1023
+ pol === null
1024
+ ? "Blocked for ordinary sharing — reachable for reports (nothing at the partner layer extinguishes the duty)"
1025
+ : `The “${pol.name}” policy blocks ordinary sharing — reachable for reports`,
1026
+ rulePath: path,
1027
+ };
1028
+ } else {
1029
+ excluded = {
1030
+ reason:
1031
+ pol === null
1032
+ ? "Blocked for this purpose by the relationship"
1033
+ : `Blocked for this purpose by your account's “${pol.name}” policy`,
1034
+ rulePath: path,
1035
+ };
1036
+ }
1037
+ }
1038
+ const excludedAll = excluded !== null;
1039
+
1040
+ // 5. which list binds (K13-12)
1041
+ const level = gov?.level ?? null;
1042
+ const govList = govNamed?.infoScope ?? null;
1043
+ const polScopeBinds =
1044
+ gov !== null &&
1045
+ Array.isArray(govList) &&
1046
+ (level === "team_row" ||
1047
+ level === "relationship" ||
1048
+ level === "account_internal" ||
1049
+ level === "inside_starter" ||
1050
+ (level === "agency_default" && gov.policy.edited === true));
1051
+ const legacy = legacyCeilingList(input.legacyCeiling);
1052
+ const ceilingIsStarter = legacy === null;
1053
+ let groupCeiling: string[] | null = legacy ?? pdRaw;
1054
+ let ceilingPath =
1055
+ legacy !== null
1056
+ ? "sharingScopeEdits (the account's partner / default rule — the legacy cell chain)"
1057
+ : pd === null
1058
+ ? "no Platform default"
1059
+ : `pol-starter-${purpose} v${pd.version} (Platform default — the starting scope for this purpose)`;
1060
+ if (ceilingIsStarter && polScopeBinds) {
1061
+ groupCeiling = null;
1062
+ ceilingPath = "";
1063
+ }
1064
+ if (inside) {
1065
+ groupCeiling = null;
1066
+ ceilingPath = "";
1067
+ }
1068
+ const tcScope = tcNamed?.infoScope ?? null;
1069
+ const tcItems = tc?.policy.infoScopeItems ?? null;
1070
+ const govItems = gov?.policy.infoScopeItems ?? null;
1071
+ const required = (g: string): boolean =>
1072
+ g === systemCode || (!inside && pd !== null && pdRequired.includes(g));
1073
+ const blockedSet = new Set(pdBlocked);
1074
+ const asSet = (v: unknown): Set<string> => new Set(isStringList(v) ? v : []);
1075
+ const categoriesOff = asSet(input.accountScope?.categoriesOff);
1076
+ const rowsOff = asSet(input.accountScope?.rowsOff);
1077
+ const categoriesOn = asSet(input.accountScope?.categoriesOn);
1078
+ const rowsOn = asSet(input.accountScope?.rowsOn);
1079
+ const underFloor = (code: string): boolean =>
1080
+ scope.ancestorsOf(code).some((c) => scope.row(c)?.platformFloor === true);
1081
+ // Clamp 4 (data.js L55165-L55170): the account's explicit choice wins both ways; else the
1082
+ // codebook's `shareableDefault` — a heightened category is off until the account turns it on.
1083
+ const categoryOffByDefault = (g: string): boolean =>
1084
+ !categoriesOn.has(g) && scope.row(g)?.shareableDefault === false;
1085
+ // Clamp 4b (L55185-L55196): a row is off when the account switched it (or a grouping above it)
1086
+ // off, or when it — or a grouping between it and its category — is heightened by default and
1087
+ // the account has not turned that one on (`shareVerdict`'s rule: turning a grouping on does not
1088
+ // turn on an off-by-default row beneath it).
1089
+ const heightenedOff = (code: string, g: string): boolean => {
1090
+ const chain = scope.ancestorsOf(code);
1091
+ if (chain.some((c) => rowsOff.has(c))) return true;
1092
+ const below = chain.slice(0, Math.max(chain.indexOf(g), 0));
1093
+ return below.some(
1094
+ (c) => !rowsOn.has(c) && scope.row(c)?.shareableDefault === false,
1095
+ );
1096
+ };
1097
+
1098
+ const out: Record<string, ShareCategoryEntry> = {};
1099
+ const allowedCategories: string[] = [];
1100
+ const govName = govNamed?.name ?? "";
1101
+ for (const g of tree.categories) {
1102
+ const items = tree.descendants.get(g) ?? [];
1103
+ const leaves = tree.leaves.get(g) ?? [];
1104
+ const platformRequired =
1105
+ !inside && pd !== null && pdRequired.includes(g)
1106
+ ? {
1107
+ rulePath: `pol-starter-${purpose} v${pd.version} · ${g} = Required (Platform default — set by the Platform Admin)`,
1108
+ }
1109
+ : null;
1110
+ const req = required(g);
1111
+ let allowed = true;
1112
+ let reason = excluded !== null ? excluded.reason : "Allowed";
1113
+ let path = excluded !== null ? excluded.rulePath : rulePath;
1114
+ const floorItems = items.filter(underFloor);
1115
+ const excludedItems: string[] = [];
1116
+ let excludedReason: string | null = null;
1117
+ const teamExcludedItems: string[] = [];
1118
+ let teamExcludedReason: string | null = null;
1119
+ // A row is OUTSIDE a list only when neither it nor anything beneath it is covered: a grouping
1120
+ // whose rows the list names by name (`instrument_summary` named only through `summary_lap`)
1121
+ // is not withheld as a unit — its uncovered rows are, each at its own grain (0.42.1; the
1122
+ // Thread inside-ceiling adoption found the whole grouping dropped with its named rows).
1123
+ // Latent gap: a grouping that carries its OWN fields (INFORMATION_SCOPE_FIELD_HOME_ROWS) and
1124
+ // whose children are all named, but not itself, is not withheld here — its own fields would
1125
+ // then leave, contrary to coverage rule 2 (`ceilingCoverage`, hasOwnContent → false). No live
1126
+ // grouping has own content today; whoever adds a field-homed grouping must handle it here.
1127
+ const outside = (covered: (r: string) => boolean): string[] =>
1128
+ items.filter(
1129
+ (r) =>
1130
+ !covered(r) &&
1131
+ !items.some((d) => d !== r && covered(d) && scope.ancestorsOf(d).includes(r)),
1132
+ );
1133
+ const addExcluded = (rows: readonly string[], why: string): void => {
1134
+ for (const r of rows)
1135
+ if (!floorItems.includes(r) && !excludedItems.includes(r))
1136
+ excludedItems.push(r);
1137
+ if (rows.length > 0 && excludedReason === null) excludedReason = why;
1138
+ };
1139
+ if (gov === null) {
1140
+ allowed = false; // an unknown purpose: nothing leaves, System metadata included
1141
+ } else if ((!req || platformRequired !== null) && excludedAll) {
1142
+ allowed = false;
1143
+ } else if (excludedAll) {
1144
+ reason = "Allowed";
1145
+ path = rulePath;
1146
+ }
1147
+ if (allowed && !req && (categoriesOff.has(g) || categoryOffByDefault(g))) {
1148
+ allowed = false;
1149
+ reason = "Excluded by your account's Information Scope policy";
1150
+ path = categoriesOff.has(g)
1151
+ ? `policies.scopeCatalog[${g}].shareable = false`
1152
+ : `policies.scopeCatalog[${g}] not turned on — codebook core-information_scope shareableDefault = false (CVC-236 heightened protection: off until the account turns it on)`;
1153
+ }
1154
+ if (allowed && !req && !inside && blockedSet.has(g)) {
1155
+ allowed = false;
1156
+ reason =
1157
+ "Blocked for this purpose by the Platform default — no account can share it under this purpose";
1158
+ path = `pol-starter-${purpose} v${pd?.version ?? 1} · ${g} = Blocked (Platform default — CVC-236 heightened protection | set by the Platform Admin)`;
1159
+ }
1160
+ // 4b heightened rows off in the account (every category but System metadata, Required included)
1161
+ addExcluded(
1162
+ g === systemCode
1163
+ ? []
1164
+ : items.filter((r) => !underFloor(r) && heightenedOff(r, g)),
1165
+ "Heightened protection (CVC-236) — off in your account's Information Scope until the account turns it on",
1166
+ );
1167
+ if (
1168
+ allowed &&
1169
+ !req &&
1170
+ groupCeiling !== null &&
1171
+ !scopeListCovers(scope, groupCeiling, g)
1172
+ ) {
1173
+ allowed = false;
1174
+ reason = "Outside the payload for this purpose";
1175
+ path = ceilingPath;
1176
+ }
1177
+ if (
1178
+ allowed &&
1179
+ !req &&
1180
+ groupCeiling !== null &&
1181
+ !scopeListStrictlyCovers(scope, groupCeiling, g)
1182
+ ) {
1183
+ addExcluded(
1184
+ outside((r) => scopeListCovers(scope, groupCeiling, g, r)),
1185
+ "Outside the payload for this purpose",
1186
+ );
1187
+ }
1188
+ if (
1189
+ allowed &&
1190
+ !req &&
1191
+ polScopeBinds &&
1192
+ !scopeListCovers(scope, govList, g)
1193
+ ) {
1194
+ allowed = false;
1195
+ reason = `Outside what the “${govName}” policy allows for this purpose`;
1196
+ path = `sharingPurposePolicies[${gov?.policy.id}].infoScope (policy “${govName}” — ${govNamed?.levelLabel})`;
1197
+ }
1198
+ if (
1199
+ allowed &&
1200
+ !req &&
1201
+ polScopeBinds &&
1202
+ !scopeListStrictlyCovers(scope, govList, g)
1203
+ ) {
1204
+ addExcluded(
1205
+ outside((r) => scopeListCovers(scope, govList, g, r)),
1206
+ `Outside what the “${govName}” policy allows for this purpose`,
1207
+ );
1208
+ }
1209
+ const govRows = polScopeBinds ? own<unknown>(govItems, g) : undefined;
1210
+ if (allowed && !req && isStringList(govRows)) {
1211
+ const keep = new Set(govRows);
1212
+ const kept = (r: string): boolean =>
1213
+ keep.has(r) || scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));
1214
+ addExcluded(
1215
+ outside(kept),
1216
+ `Outside what the “${govName}” policy allows for this purpose`,
1217
+ );
1218
+ }
1219
+ if (
1220
+ allowed &&
1221
+ !req &&
1222
+ tcScope !== null &&
1223
+ !scopeListCovers(scope, tcScope, g)
1224
+ ) {
1225
+ allowed = false;
1226
+ reason = `Outside what your team's “${tcNamed?.name}” policy allows`;
1227
+ path = `sharingPurposePolicies[${tc?.policy.id}].infoScope (policy “${tcNamed?.name}” — ${SHARE_LEVEL_LABEL.team}; a ceiling over “${govName}”)`;
1228
+ }
1229
+ if (allowed && !req && tc !== null) {
1230
+ const why = `Outside what your team's “${tcNamed?.name}” policy allows`;
1231
+ const outRows = new Set<string>();
1232
+ if (tcScope !== null && !scopeListStrictlyCovers(scope, tcScope, g)) {
1233
+ for (const r of outside((x) => scopeListCovers(scope, tcScope, g, x))) outRows.add(r);
1234
+ }
1235
+ const tcRows = own<unknown>(tcItems, g);
1236
+ if (isStringList(tcRows)) {
1237
+ const keep = new Set(tcRows);
1238
+ const kept = (r: string): boolean =>
1239
+ keep.has(r) || scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));
1240
+ for (const r of outside(kept)) outRows.add(r);
1241
+ }
1242
+ for (const r of outRows)
1243
+ if (!floorItems.includes(r) && !excludedItems.includes(r))
1244
+ teamExcludedItems.push(r);
1245
+ if (teamExcludedItems.length > 0) teamExcludedReason = why;
1246
+ }
1247
+ // the group flip: every leaf row withheld → the category is withheld
1248
+ if (allowed && (!req || platformRequired !== null) && leaves.length > 0) {
1249
+ const gone = new Set(
1250
+ [...floorItems, ...excludedItems, ...teamExcludedItems].filter((r) =>
1251
+ leaves.includes(r),
1252
+ ),
1253
+ );
1254
+ if (gone.size >= leaves.length) {
1255
+ allowed = false;
1256
+ if (leaves.every((r) => floorItems.includes(r))) {
1257
+ reason = "Never shared — under the platform safety floor";
1258
+ path = "HTI_PLATFORM_SAFETY_FLOOR";
1259
+ } else if (leaves.some((r) => excludedItems.includes(r))) {
1260
+ reason = excludedReason ?? reason;
1261
+ } else {
1262
+ reason = teamExcludedReason ?? reason;
1263
+ }
1264
+ }
1265
+ }
1266
+ out[g] = {
1267
+ allowed,
1268
+ reason,
1269
+ rulePath: path,
1270
+ platformRequired,
1271
+ floorItems: uniq(floorItems),
1272
+ excludedItems: uniq(excludedItems),
1273
+ excludedReason,
1274
+ teamExcludedItems: uniq(teamExcludedItems),
1275
+ teamExcludedReason,
1276
+ };
1277
+ if (allowed) allowedCategories.push(g);
1278
+ }
1279
+
1280
+ return {
1281
+ allowed: !excludedAll,
1282
+ posture,
1283
+ postureSource,
1284
+ excluded,
1285
+ reportCarveOut,
1286
+ governing: govNamed,
1287
+ teamCeiling: tcNamed,
1288
+ inside,
1289
+ scope: out,
1290
+ allowedCategories,
1291
+ rulePath,
1292
+ };
1293
+ }