@htilabs/platform-common-models 0.40.0 → 0.42.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 (40) hide show
  1. package/README.md +149 -0
  2. package/dist/index.cjs +677 -0
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +1 -1
  5. package/dist/index.d.ts +1 -1
  6. package/dist/index.js +658 -0
  7. package/dist/index.js.map +1 -1
  8. package/dist/share-rules/index.cjs +822 -0
  9. package/dist/share-rules/index.cjs.map +1 -0
  10. package/dist/share-rules/index.d.cts +804 -0
  11. package/dist/share-rules/index.d.ts +804 -0
  12. package/dist/share-rules/index.js +736 -0
  13. package/dist/share-rules/index.js.map +1 -0
  14. package/dist/sharing-ceiling/index.cjs +679 -2
  15. package/dist/sharing-ceiling/index.cjs.map +1 -1
  16. package/dist/sharing-ceiling/index.d.cts +461 -1
  17. package/dist/sharing-ceiling/index.d.ts +461 -1
  18. package/dist/sharing-ceiling/index.js +659 -1
  19. package/dist/sharing-ceiling/index.js.map +1 -1
  20. package/package.json +6 -1
  21. package/src/shareRules/__tests__/caseShareLane.test.ts +259 -0
  22. package/src/shareRules/__tests__/magicLinkAddresses.test.ts +107 -0
  23. package/src/shareRules/__tests__/platformApps.test.ts +133 -0
  24. package/src/shareRules/__tests__/releaseTerms.test.ts +358 -0
  25. package/src/shareRules/__tests__/senderRoiPosture.test.ts +284 -0
  26. package/src/shareRules/__tests__/sharingMethods.test.ts +105 -0
  27. package/src/shareRules/caseShareLane.ts +289 -0
  28. package/src/shareRules/index.ts +31 -0
  29. package/src/shareRules/magicLinkAddresses.ts +185 -0
  30. package/src/shareRules/platformApps.ts +168 -0
  31. package/src/shareRules/releaseTerms.ts +359 -0
  32. package/src/shareRules/reportPurposes.ts +50 -0
  33. package/src/shareRules/senderRoiPosture.ts +296 -0
  34. package/src/shareRules/sharingMethods.ts +204 -0
  35. package/src/sharingCeiling/__tests__/resolveShare.test.ts +1305 -0
  36. package/src/sharingCeiling/__tests__/threadLift.test.ts +353 -0
  37. package/src/sharingCeiling/coverage.ts +63 -0
  38. package/src/sharingCeiling/defaults.ts +106 -0
  39. package/src/sharingCeiling/index.ts +13 -1
  40. package/src/sharingCeiling/resolve.ts +1278 -0
@@ -0,0 +1,1278 @@
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
+ /** Rows the governing list / the account's heightened toggles / the ceiling leave out. */
269
+ readonly excludedItems: string[];
270
+ readonly excludedReason: string | null;
271
+ /** Rows the sending team's own policy leaves out (5d). */
272
+ readonly teamExcludedItems: string[];
273
+ readonly teamExcludedReason: string | null;
274
+ }
275
+
276
+ export interface ShareResolution {
277
+ /** `false` = the share as a whole is excluded (`excluded` says why). */
278
+ readonly allowed: boolean;
279
+ readonly posture: SharePosture;
280
+ readonly postureSource: "relationship" | "policy" | "team_ceiling";
281
+ readonly excluded: {
282
+ readonly reason: string;
283
+ readonly rulePath: string;
284
+ } | null;
285
+ /** A reporting purpose under a `blocked` posture: never excluded; the note names what blocks ordinary sharing. */
286
+ readonly reportCarveOut: {
287
+ readonly note: string;
288
+ readonly rulePath: string;
289
+ } | null;
290
+ /** The policy that governs; `null` only for an unknown purpose (fails closed). */
291
+ readonly governing: ShareNamedPolicy | null;
292
+ /** The sending team's own policy for the purpose, when it is not itself the governing one. */
293
+ readonly teamCeiling: ShareNamedPolicy | null;
294
+ /** A share to a sibling team of the same account. */
295
+ readonly inside: boolean;
296
+ /** Every live category of the tree, in tree order. */
297
+ readonly scope: Readonly<Record<string, ShareCategoryEntry>>;
298
+ /** The categories with `allowed === true`, tree order — the list the coverage readers take. */
299
+ readonly allowedCategories: string[];
300
+ readonly rulePath: string;
301
+ }
302
+
303
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
304
+
305
+ const own = <V>(record: unknown, key: string): V | undefined =>
306
+ record !== null &&
307
+ typeof record === "object" &&
308
+ Object.prototype.hasOwnProperty.call(record, key)
309
+ ? ((record as Record<string, V>)[key] as V)
310
+ : undefined;
311
+
312
+ const isStringList = (v: unknown): v is readonly string[] =>
313
+ Array.isArray(v) && v.every((c) => typeof c === "string");
314
+
315
+ const versionOf = (v: unknown): number => {
316
+ const n = typeof v === "number" ? v : parseInt(String(v), 10);
317
+ return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 1;
318
+ };
319
+
320
+ /**
321
+ * `infoScope` as the resolver reads it: `null` or absent = no list (data.js reads every
322
+ * non-array as "no list", L54979 / L55124); a list of strings = that list (`[]` binds an empty
323
+ * list, as in canon); any other present value = `[]` (fail closed; stricter than canon).
324
+ */
325
+ const docList = (v: unknown): string[] | null =>
326
+ v === null || v === undefined ? null : isStringList(v) ? [...v] : [];
327
+
328
+ /**
329
+ * data.js `scopeListCovers` (L54696-L54706), on the v4 tree: a non-array list
330
+ * covers everything; a category is covered when the list names it or an
331
+ * ANCESTOR (a kind such as `family`, a branch); with a row `it`, the row is
332
+ * covered when it or an ancestor is named; without one, a category is also
333
+ * covered when the list names any DESCENDANT of it (a row or grouping).
334
+ */
335
+ export function scopeListCovers(
336
+ scope: SharingCeilingScope,
337
+ list: readonly string[] | null | undefined,
338
+ categoryCode: string,
339
+ rowCode?: string,
340
+ ): boolean {
341
+ if (!Array.isArray(list)) return true;
342
+ const set = new Set(list);
343
+ if (scope.ancestorsOf(categoryCode).some((c) => set.has(c))) return true;
344
+ if (rowCode !== undefined)
345
+ return scope.ancestorsOf(rowCode).some((c) => set.has(c));
346
+ return list.some((id) =>
347
+ scope.ancestorsOf(id).slice(1).includes(categoryCode),
348
+ );
349
+ }
350
+
351
+ /** `scopeStrictCovers` (L54710ff): the list names the category or an ancestor — never a descendant. */
352
+ export function scopeListStrictlyCovers(
353
+ scope: SharingCeilingScope,
354
+ list: readonly string[] | null | undefined,
355
+ categoryCode: string,
356
+ ): boolean {
357
+ if (!Array.isArray(list)) return true;
358
+ const set = new Set(list);
359
+ return scope.ancestorsOf(categoryCode).some((c) => set.has(c));
360
+ }
361
+
362
+ /** The attachment index the ladder reads (data.js `effectiveAttachmentIndex` L53558ff), built from `assignments` only. */
363
+ export interface ShareAttachmentIndex {
364
+ readonly agencyDefaults: Readonly<Record<string, string>>;
365
+ readonly internalDefaults: Readonly<Record<string, string>>;
366
+ readonly relationships: Readonly<
367
+ Record<string, Readonly<Record<string, string>>>
368
+ >;
369
+ readonly teamRows: Readonly<Record<string, Readonly<Record<string, string>>>>;
370
+ readonly teams: Readonly<Record<string, Readonly<Record<string, string>>>>;
371
+ }
372
+
373
+ const isLiveDoc = (p: SharePolicyDoc | null | undefined): p is SharePolicyDoc =>
374
+ p !== null &&
375
+ typeof p === "object" &&
376
+ typeof p.id === "string" &&
377
+ p.id !== "" &&
378
+ typeof p.purpose === "string" &&
379
+ p.active !== false;
380
+
381
+ export function attachmentIndexFromPolicies(
382
+ policies: readonly SharePolicyDoc[] | null | undefined,
383
+ ): ShareAttachmentIndex {
384
+ // Null-prototype maps: a key such as `__proto__` is a key, never the prototype. Two live
385
+ // documents on one cell: the LATER one in `policies` wins (deterministic; a store's key forbids it).
386
+ const nullMap = <V>(): Record<string, V> =>
387
+ Object.create(null) as Record<string, V>;
388
+ const agencyDefaults = nullMap<string>();
389
+ const internalDefaults = nullMap<string>();
390
+ const relationships = nullMap<Record<string, string>>();
391
+ const teamRows = nullMap<Record<string, string>>();
392
+ const teams = nullMap<Record<string, string>>();
393
+ const put = (
394
+ map: Record<string, Record<string, string>>,
395
+ key: string,
396
+ purpose: string,
397
+ id: string,
398
+ ): void => {
399
+ const row = Object.prototype.hasOwnProperty.call(map, key)
400
+ ? map[key]
401
+ : (map[key] = nullMap<string>());
402
+ row[purpose] = id;
403
+ };
404
+ for (const p of Array.isArray(policies) ? policies : []) {
405
+ if (!isLiveDoc(p)) continue;
406
+ for (const a of Array.isArray(p.assignments) ? p.assignments : []) {
407
+ if (a === null || typeof a !== "object") continue;
408
+ switch (a.scope) {
409
+ case "account":
410
+ agencyDefaults[p.purpose] = p.id;
411
+ break;
412
+ case "account_internal":
413
+ internalDefaults[p.purpose] = p.id;
414
+ break;
415
+ case "account_partner":
416
+ if (typeof a.partnerId === "string" && a.partnerId !== "")
417
+ put(relationships, a.partnerId, p.purpose, p.id);
418
+ break;
419
+ case "team":
420
+ if (typeof a.teamId === "string" && a.teamId !== "")
421
+ put(teams, a.teamId, p.purpose, p.id);
422
+ break;
423
+ case "team_pair":
424
+ if (typeof a.teamRowId === "string" && a.teamRowId !== "")
425
+ put(teamRows, a.teamRowId, p.purpose, p.id);
426
+ break;
427
+ default:
428
+ break; // an unknown scope governs nowhere
429
+ }
430
+ }
431
+ }
432
+ return { agencyDefaults, internalDefaults, relationships, teamRows, teams };
433
+ }
434
+
435
+ /** A team-to-team row as the account stores it (data.js `teamRows` / `teamPairs`, L53493-L53514). */
436
+ export interface ShareTeamRowLike {
437
+ readonly id: string;
438
+ readonly myTeamId?: string | null;
439
+ readonly their?: { readonly type?: string; readonly id?: string } | null;
440
+ }
441
+
442
+ /**
443
+ * The row the first rung reads (data.js `internalPairRow` / `partnerTeamRow`,
444
+ * L53493-L53514). `rows` is ONE store, as the prototype keeps them: for a
445
+ * sibling team, the account's internal pairs (`policies.teamPairs`); for a
446
+ * partner, THAT partner's team rows (`partnerOverrides[partner].teamRows`, or
447
+ * the seeded rows) — never a flat list across partners. A sibling team's row
448
+ * is the one whose `their` is that team (direction matters — the sender
449
+ * first); a partner's row under a team-scoped relationship is the team's
450
+ * FIRST row, under an all-teams relationship the row whose `their` is absent,
451
+ * not a team, or this very partner. Rows that carry only share-back
452
+ * (answers-received) policies are dropped first. An external recipient has
453
+ * no row.
454
+ */
455
+ export function matchTeamRow(
456
+ rows: readonly ShareTeamRowLike[] | null | undefined,
457
+ teamId: string | null | undefined,
458
+ recipient: ShareRecipient,
459
+ options: {
460
+ readonly scopeMode?: "team_scoped" | "all_teams";
461
+ readonly shareBackOnlyRowIds?: readonly string[];
462
+ } = {},
463
+ ): string | null {
464
+ if (typeof teamId !== "string" || teamId === "" || !Array.isArray(rows))
465
+ return null;
466
+ const drop = new Set(options.shareBackOnlyRowIds ?? []);
467
+ const live = rows.filter(
468
+ (r): r is ShareTeamRowLike =>
469
+ r !== null &&
470
+ typeof r === "object" &&
471
+ typeof r.id === "string" &&
472
+ !drop.has(r.id),
473
+ );
474
+ if (recipient.kind === "sibling_team") {
475
+ // data.js `internalPairRow` (L53509-L53514): every row of the internal-pairs store is a
476
+ // team-to-team row (`teamRowIndex` L53481 types it `team`), so it matches on `their.id`
477
+ // alone — a stored pair row without `their.type` still governs.
478
+ return (
479
+ live.find(
480
+ (r) => r.myTeamId === teamId && r.their?.id === recipient.teamId,
481
+ )?.id ?? null
482
+ );
483
+ }
484
+ if (recipient.kind === "external") return null;
485
+ if (options.scopeMode === "team_scoped")
486
+ return live.find((r) => r.myTeamId === teamId)?.id ?? null;
487
+ return (
488
+ live.find(
489
+ (r) =>
490
+ r.myTeamId === teamId &&
491
+ (!r.their || r.their.type !== "team" || r.their.id === recipient.id),
492
+ )?.id ?? null
493
+ );
494
+ }
495
+
496
+ // ─── The four states ─────────────────────────────────────────────────────────
497
+
498
+ /**
499
+ * Derive one purpose's Platform default as the four states (data.js
500
+ * `starterDerivedState` L53708 + `platformStarterScope` L53719ff),
501
+ * for every live CATEGORY of the tree, in this order — the first rule wins:
502
+ * System metadata → `always`; a category the platform requires for the
503
+ * purpose → `always`; off-by-default (heightened) → `never`; the seed list
504
+ * covers it (itself, an ancestor, or any row of it) → `default_on`, else
505
+ * `default_off`. An explicit bound overrides it for every category but
506
+ * `system`. `raw` is the starting scope: the seed's codes whose category is
507
+ * not Blocked or bound off, plus every bound-on and Required category, plus
508
+ * `system`.
509
+ */
510
+ export function derivePlatformDefault(
511
+ scope: SharingCeilingScope,
512
+ purpose: string,
513
+ seedList: readonly string[] | null | undefined,
514
+ options: {
515
+ readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;
516
+ readonly required?: readonly string[] | null;
517
+ readonly version?: number | string;
518
+ readonly edited?: boolean;
519
+ } = {},
520
+ ): SharePlatformDefault {
521
+ const seed = isStringList(seedList) ? [...seedList] : [];
522
+ const req = new Set(options.required ?? []);
523
+ const states: Record<string, SharePlatformState> = {};
524
+ const required: string[] = [];
525
+ const blocked: string[] = [];
526
+ const systemCode = systemCategoryOf(scope);
527
+ for (const g of liveCategories(scope)) {
528
+ let state: SharePlatformState;
529
+ if (g === systemCode) state = "always";
530
+ else if (req.has(g)) state = "always";
531
+ else if (scope.row(g)?.shareableDefault === false) state = "never";
532
+ else state = scopeListCovers(scope, seed, g) ? "default_on" : "default_off";
533
+ const bound = own<unknown>(options.bounds, g);
534
+ if (
535
+ g !== systemCode &&
536
+ (bound === "always" ||
537
+ bound === "default_on" ||
538
+ bound === "default_off" ||
539
+ bound === "never")
540
+ )
541
+ state = bound;
542
+ states[g] = state;
543
+ if (state === "always" && g !== systemCode) required.push(g);
544
+ if (state === "never") blocked.push(g);
545
+ }
546
+ const categoryOf = (code: string): string | undefined =>
547
+ scope.ancestorsOf(code).find((c) => scope.row(c)?.rowType === "category");
548
+ const raw: string[] = [];
549
+ const push = (c: string): void => {
550
+ if (!raw.includes(c)) raw.push(c);
551
+ };
552
+ for (const code of seed) {
553
+ const g = categoryOf(code);
554
+ if (g === undefined) {
555
+ // A kind or a branch: it stands for its categories — keep the ones that are on, by name,
556
+ // so a category bound off beneath it is not covered by the kind (review r1 #4).
557
+ for (const [cat, st] of Object.entries(states)) {
558
+ if (
559
+ (st === "always" || st === "default_on") &&
560
+ scope.ancestorsOf(cat).includes(code)
561
+ )
562
+ push(cat);
563
+ }
564
+ continue;
565
+ }
566
+ const st = states[g];
567
+ if (st === "never" || st === "default_off") continue;
568
+ push(code);
569
+ }
570
+ for (const [g, st] of Object.entries(states)) {
571
+ if (
572
+ (st === "always" || st === "default_on") &&
573
+ !scopeListCovers(scope, raw, g)
574
+ )
575
+ push(g);
576
+ }
577
+ if (systemCode !== undefined) push(systemCode);
578
+ return {
579
+ purpose,
580
+ version: versionOf(options.version),
581
+ raw,
582
+ states,
583
+ required,
584
+ blocked,
585
+ edited: options.edited === true,
586
+ };
587
+ }
588
+
589
+ // ─── Tree reads ──────────────────────────────────────────────────────────────
590
+
591
+ const treeCache = new WeakMap<
592
+ object,
593
+ {
594
+ categories: string[];
595
+ system: string | undefined;
596
+ leaves: Map<string, string[]>;
597
+ descendants: Map<string, string[]>;
598
+ }
599
+ >();
600
+
601
+ function treeIndex(scope: SharingCeilingScope) {
602
+ const hit = treeCache.get(scope);
603
+ if (hit) return hit;
604
+ const live = (code: string): boolean =>
605
+ scope.row(code) !== undefined &&
606
+ scope.ancestorsOf(code).every((c) => scope.row(c)?.status !== "retired");
607
+ const categories = scope.rows
608
+ .filter((r) => r.rowType === "category" && live(r.scopeCode))
609
+ .map((r) => r.scopeCode);
610
+ const systemInfoPath =
611
+ scope.row("system_info") !== undefined
612
+ ? scope.ancestorsOf("system_info")
613
+ : [];
614
+ const system =
615
+ systemInfoPath.find((c) => categories.includes(c)) ??
616
+ categories.find((g) => g === "system");
617
+ const descendants = new Map<string, string[]>();
618
+ const leaves = new Map<string, string[]>();
619
+ for (const g of categories) {
620
+ const all: string[] = [];
621
+ const walk = (code: string): void => {
622
+ for (const c of scope.childrenOf(code)) {
623
+ if (!live(c)) continue;
624
+ all.push(c);
625
+ walk(c);
626
+ }
627
+ };
628
+ walk(g);
629
+ descendants.set(g, all);
630
+ leaves.set(
631
+ g,
632
+ all.filter((c) => !scope.childrenOf(c).some(live)),
633
+ );
634
+ }
635
+ const out = { categories, system, leaves, descendants };
636
+ treeCache.set(scope, out);
637
+ return out;
638
+ }
639
+
640
+ /** The live categories of the tree, in tree order. */
641
+ export function liveCategories(scope: SharingCeilingScope): string[] {
642
+ return [...treeIndex(scope).categories];
643
+ }
644
+
645
+ /** The System-metadata category (`system`, the parent of `system_info`). */
646
+ export function systemCategoryOf(
647
+ scope: SharingCeilingScope,
648
+ ): string | undefined {
649
+ return treeIndex(scope).system;
650
+ }
651
+
652
+ /**
653
+ * The legacy cell chain's list as clamp 5 reads it: a plain list binds as given; an
654
+ * `effectiveCeiling` answer binds only when an ACCOUNT rule answered (`partner_rule`,
655
+ * `seeded_partner_rule`, `account_default`) — its `platform_default` rung is the same document
656
+ * the resolver already reads as the Platform default (passing it as a legacy list would clamp
657
+ * every authored policy to the starter and undo K13-12), and `purpose_disabled` / `none` are
658
+ * carried by `purposeOff` / the missing Platform default.
659
+ */
660
+ function legacyCeilingList(
661
+ v: ShareResolveInput["legacyCeiling"],
662
+ ): string[] | null {
663
+ if (v === null || v === undefined) return null;
664
+ if (isStringList(v)) return [...v];
665
+ if (typeof v === "object" && "rung" in v) {
666
+ const r = (v as EffectiveSharingCeiling).rung;
667
+ if (
668
+ r === "partner_rule" ||
669
+ r === "seeded_partner_rule" ||
670
+ r === "account_default"
671
+ ) {
672
+ return isStringList(v.allowed) ? [...v.allowed] : [];
673
+ }
674
+ return null;
675
+ }
676
+ return null;
677
+ }
678
+
679
+ /**
680
+ * The categories the platform REQUIRES for a purpose (data.js `scopeRequiredByPurpose`,
681
+ * L40836-L40839): Identifying information on every report. Read by `platformDefaultFor`.
682
+ */
683
+ export const HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE: Readonly<
684
+ Record<string, readonly string[]>
685
+ > = Object.freeze({
686
+ mandatory_reporting: Object.freeze(["identifying"]),
687
+ authority_reporting: Object.freeze(["identifying"]),
688
+ });
689
+
690
+ /**
691
+ * The Platform default for one purpose from the PUBLISHED starter (the day-one tier document,
692
+ * version 1, no bounds): `derivePlatformDefault` over `HTI_SHARE_PLATFORM_STARTER.scopeByPurpose`
693
+ * and {@link HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE}. `null` for a purpose the starter has no row
694
+ * for (the resolver then fails closed). Once the platform stores `pol-starter-<purpose>` as a
695
+ * versioned document, pass ITS list, bounds and version instead.
696
+ */
697
+ export function platformDefaultFor(
698
+ scope: SharingCeilingScope,
699
+ purpose: string,
700
+ options: {
701
+ readonly starter?: SharingPlatformStarter;
702
+ readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;
703
+ readonly version?: number | string;
704
+ readonly edited?: boolean;
705
+ } = {},
706
+ ): SharePlatformDefault | null {
707
+ const starter = options.starter ?? HTI_SHARE_PLATFORM_STARTER;
708
+ const seed = own<readonly string[]>(starter.scopeByPurpose, purpose);
709
+ if (!isStringList(seed)) return null;
710
+ return derivePlatformDefault(scope, purpose, seed, {
711
+ required:
712
+ own<readonly string[]>(HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE, purpose) ??
713
+ [],
714
+ bounds: options.bounds ?? null,
715
+ version: options.version ?? 1,
716
+ edited: options.edited === true,
717
+ });
718
+ }
719
+
720
+ /**
721
+ * The ROW-grain ceiling one resolution amounts to — the list the item-grain readers take
722
+ * (`maskSelectionToCeiling` for the composer, `rowsOverCeiling` for the send door): each
723
+ * allowed category by its own code when no row of it is withheld, else its live rows minus
724
+ * the withheld ones (the governing list's, the account's heightened rows, the field-group
725
+ * limits, the team's). Rows under the platform floor are never listed (the readers never let
726
+ * them through). `[]` for an excluded share — only System metadata rides.
727
+ */
728
+ export function shareRowCeiling(
729
+ resolution: Pick<ShareResolution, "allowed" | "scope" | "allowedCategories">,
730
+ scope: SharingCeilingScope,
731
+ ): string[] {
732
+ if (!resolution.allowed) return [];
733
+ const out: string[] = [];
734
+ for (const g of resolution.allowedCategories) {
735
+ const e = own<ShareCategoryEntry>(resolution.scope, g);
736
+ if (e === undefined) continue;
737
+ const withheld = new Set([
738
+ ...e.excludedItems,
739
+ ...e.teamExcludedItems,
740
+ ...e.floorItems,
741
+ ]);
742
+ if (withheld.size === 0) {
743
+ out.push(g);
744
+ continue;
745
+ }
746
+ // walk down from the category: a row stands at its own grain when nothing beneath it is
747
+ // withheld; else its surviving children stand in for it; a withheld row (and all beneath)
748
+ // is dropped — so `instrument_full` with every full row off is not listed at all.
749
+ const live = (c: string): boolean =>
750
+ scope.row(c) !== undefined &&
751
+ scope.ancestorsOf(c).every((a) => scope.row(a)?.status !== "retired");
752
+ const anyWithheldBeneath = (c: string): boolean =>
753
+ scope
754
+ .childrenOf(c)
755
+ .some((k) => live(k) && (withheld.has(k) || anyWithheldBeneath(k)));
756
+ const visit = (c: string): void => {
757
+ if (withheld.has(c) || !live(c)) return;
758
+ if (!anyWithheldBeneath(c)) {
759
+ out.push(c);
760
+ return;
761
+ }
762
+ for (const k of scope.childrenOf(c)) visit(k);
763
+ };
764
+ for (const k of scope.childrenOf(g)) visit(k);
765
+ }
766
+ return out;
767
+ }
768
+
769
+ // ─── The resolver ────────────────────────────────────────────────────────────
770
+
771
+ interface Hit {
772
+ readonly policy: SharePolicyDoc;
773
+ readonly level: ShareLevel | "team";
774
+ readonly version: number;
775
+ readonly rulePath: string;
776
+ }
777
+
778
+ function named(h: Hit): ShareNamedPolicy {
779
+ const p = h.policy;
780
+ return {
781
+ id: p.id,
782
+ familyId:
783
+ typeof p.familyId === "string" && p.familyId !== "" ? p.familyId : p.id,
784
+ name: typeof p.name === "string" ? p.name : p.id,
785
+ version: h.version,
786
+ level: h.level,
787
+ levelLabel: SHARE_LEVEL_LABEL[h.level],
788
+ posture:
789
+ p.posture === "open" ||
790
+ p.posture === "approval" ||
791
+ p.posture === "blocked"
792
+ ? p.posture
793
+ : null,
794
+ infoScope: docList(p.infoScope),
795
+ infoScopeItems: copyItems(p.infoScopeItems),
796
+ edited: p.edited === true,
797
+ origin: typeof p.origin?.kind === "string" ? p.origin.kind : null,
798
+ rulePath: h.rulePath,
799
+ };
800
+ }
801
+
802
+ const uniq = (list: readonly string[]): string[] => [...new Set(list)];
803
+
804
+ const copyItems = (v: unknown): Record<string, string[]> | null => {
805
+ if (v === null || typeof v !== "object") return null;
806
+ const out: Record<string, string[]> = {};
807
+ for (const [k, rows] of Object.entries(v as Record<string, unknown>)) {
808
+ if (isStringList(rows)) out[k] = [...rows];
809
+ }
810
+ return out;
811
+ };
812
+
813
+ /**
814
+ * THE read. See the module header; the algorithm, step by step:
815
+ * 1. the ladder (`governingPolicyFor`): pair row → [inside: the account's
816
+ * inside default → the platform's inside starter, stop] → relationship
817
+ * (the partner id, or `__external__`) → the account default → the
818
+ * Platform default (a versioned document, `pol-starter-<purpose>`);
819
+ * 2. the sending team's own policy for the purpose rides as a CEILING when
820
+ * it is not the governing one (inside the account too);
821
+ * 3. posture: the relationship's, raised (never lowered) by the governing
822
+ * policy, then by the ceiling — stricter wins;
823
+ * 4. the whole share: the purpose switch excludes it (reports too); a
824
+ * `blocked` posture excludes a discretionary share and CARVES OUT a
825
+ * report (never blocked at the policy / partner layer);
826
+ * 5. per category: Required (`system`, or the Platform default's `always`)
827
+ * bypasses every account-grain clamp; else the account's toggle (4), the
828
+ * Platform default's Blocked (4a, not inside), the binding list (5: the
829
+ * legacy cell chain's list or the Platform default's starting scope — the
830
+ * governing policy's own list when it is authored (5b); K13-12), the
831
+ * team ceiling's list (5d); rows: the floor, heightened rows off (4b),
832
+ * field-group limits (5c), and a category every row of which is withheld
833
+ * is withheld (the group flip).
834
+ */
835
+ export function resolveShare(input: ShareResolveInput): ShareResolution {
836
+ const { scope, purpose, recipient } = input;
837
+ if (typeof purpose !== "string" || purpose === "")
838
+ throw new TypeError("resolveShare: purpose must be a share purpose code");
839
+ const teamId =
840
+ typeof input.sender?.teamId === "string" && input.sender.teamId !== ""
841
+ ? input.sender.teamId
842
+ : null;
843
+ const inside = recipient.kind === "sibling_team";
844
+ const recipientKey =
845
+ recipient.kind === "partner"
846
+ ? recipient.id
847
+ : recipient.kind === "external"
848
+ ? "__external__"
849
+ : null;
850
+ if (
851
+ recipient.kind === "partner" &&
852
+ (typeof recipient.id !== "string" || recipient.id === "")
853
+ ) {
854
+ throw new TypeError("resolveShare: a partner recipient needs an id");
855
+ }
856
+ const report = SHARE_REPORTING_PURPOSES.has(purpose);
857
+ const pd = input.platformDefault ?? null;
858
+ const purposeLabel =
859
+ typeof input.purposeLabel === "string" && input.purposeLabel !== ""
860
+ ? input.purposeLabel
861
+ : purpose;
862
+ const pdRaw = pd === null ? [] : isStringList(pd.raw) ? [...pd.raw] : [];
863
+ const pdRequired =
864
+ pd === null ? [] : isStringList(pd.required) ? [...pd.required] : [];
865
+ const pdBlocked =
866
+ pd === null ? [] : isStringList(pd.blocked) ? [...pd.blocked] : [];
867
+ const policies = (Array.isArray(input.policies) ? input.policies : []).filter(
868
+ isLiveDoc,
869
+ );
870
+ const byId = new Map<string, SharePolicyDoc>();
871
+ for (const p of policies) byId.set(p.id, p);
872
+ const att = attachmentIndexFromPolicies(policies);
873
+ const tree = treeIndex(scope);
874
+ const systemCode = tree.system;
875
+
876
+ // 1. the ladder
877
+ const hit = (
878
+ id: string | undefined,
879
+ level: ShareLevel | "team",
880
+ ): Hit | null => {
881
+ const p = id === undefined ? undefined : byId.get(id);
882
+ if (p === undefined || p.purpose !== purpose) return null;
883
+ if (p.trigger?.answers === "received") return null;
884
+ const v = versionOf(p.version);
885
+ const name = typeof p.name === "string" ? p.name : p.id;
886
+ return {
887
+ policy: p,
888
+ level,
889
+ version: v,
890
+ rulePath: `sharingPurposePolicies[${p.id}] v${v} (policy “${name}” — ${SHARE_LEVEL_LABEL[level]})`,
891
+ };
892
+ };
893
+ const cell = (
894
+ map: Record<string, Readonly<Record<string, string>>>,
895
+ key: string,
896
+ ) => own<string>(own<Readonly<Record<string, string>>>(map, key), purpose);
897
+ let gov: Hit | null = null;
898
+ // An unknown purpose (no Platform default) governs nothing — the ladder is not read at all
899
+ // (review r1 #1: a policy linked under it must not leak its own list).
900
+ const purposeKnown = pd !== null;
901
+ const teamRowId =
902
+ purposeKnown &&
903
+ teamId !== null &&
904
+ recipient.kind !== "external" &&
905
+ typeof input.teamRowId === "string" &&
906
+ input.teamRowId !== ""
907
+ ? input.teamRowId
908
+ : null;
909
+ if (teamRowId !== null) gov = hit(cell(att.teamRows, teamRowId), "team_row");
910
+ if (gov === null && inside && purposeKnown) {
911
+ gov = hit(own<string>(att.internalDefaults, purpose), "account_internal");
912
+ if (gov === null && pd !== null) {
913
+ const starter: SharePolicyDoc = {
914
+ id: `pol-inside-starter-${purpose}`,
915
+ name: `${purposeLabel} — Inside your account (platform default)`,
916
+ purpose,
917
+ infoScope: null,
918
+ posture: "open",
919
+ version: 1,
920
+ origin: { kind: "starter" },
921
+ };
922
+ gov = {
923
+ policy: starter,
924
+ level: "inside_starter",
925
+ version: 1,
926
+ rulePath: `${starter.id} v1 (${SHARE_LEVEL_LABEL.inside_starter} — the full record, open)`,
927
+ };
928
+ }
929
+ }
930
+ if (gov === null && !inside && purposeKnown && recipientKey !== null) {
931
+ gov = hit(cell(att.relationships, recipientKey), "relationship");
932
+ if (gov === null)
933
+ gov = hit(own<string>(att.agencyDefaults, purpose), "agency_default");
934
+ if (gov === null && pd !== null) {
935
+ const starter: SharePolicyDoc = {
936
+ id: `pol-starter-${purpose}`,
937
+ name: `${purposeLabel} — Platform default`,
938
+ purpose,
939
+ infoScope: pdRaw.filter((c) => c !== systemCode),
940
+ posture: "open",
941
+ version: pd.version,
942
+ origin: { kind: "platform_starter" },
943
+ edited: false,
944
+ };
945
+ gov = {
946
+ policy: starter,
947
+ level: "platform_starter",
948
+ version: pd.version,
949
+ rulePath: `${starter.id} v${pd.version} (${SHARE_LEVEL_LABEL.platform_starter})`,
950
+ };
951
+ }
952
+ }
953
+
954
+ // 2. the team ceiling
955
+ let tc: Hit | null = null;
956
+ if (teamId !== null && gov !== null) {
957
+ const t = hit(cell(att.teams, teamId), "team");
958
+ if (t !== null && t.policy.id !== gov.policy.id) tc = t;
959
+ }
960
+ const govNamed = gov === null ? null : named(gov);
961
+ const tcNamed = tc === null ? null : named(tc);
962
+ const rulePath =
963
+ gov === null
964
+ ? `no Platform default for purpose “${purpose}” — nothing governs (fails closed)`
965
+ : tc === null
966
+ ? gov.rulePath
967
+ : `${gov.rulePath} ∩ ${tc.rulePath} (the sending team's own policy is a ceiling — only what both allow)`;
968
+
969
+ // 3. posture
970
+ let posture: SharePosture =
971
+ input.relationshipPosture === "approval" ||
972
+ input.relationshipPosture === "blocked"
973
+ ? input.relationshipPosture
974
+ : "open";
975
+ let postureSource: ShareResolution["postureSource"] = "relationship";
976
+ let posturePol: ShareNamedPolicy | null = null;
977
+ if (
978
+ govNamed?.posture &&
979
+ SHARE_POSTURE_RANK[govNamed.posture] > SHARE_POSTURE_RANK[posture]
980
+ ) {
981
+ posture = govNamed.posture;
982
+ postureSource = "policy";
983
+ posturePol = govNamed;
984
+ }
985
+ if (
986
+ tcNamed?.posture &&
987
+ SHARE_POSTURE_RANK[tcNamed.posture] > SHARE_POSTURE_RANK[posture]
988
+ ) {
989
+ posture = tcNamed.posture;
990
+ postureSource = "team_ceiling";
991
+ posturePol = tcNamed;
992
+ }
993
+
994
+ // 4. the whole share
995
+ let excluded: ShareResolution["excluded"] = null;
996
+ let reportCarveOut: ShareResolution["reportCarveOut"] = null;
997
+ if (gov === null) {
998
+ excluded = {
999
+ reason: `No Platform default for purpose “${purpose}” — nothing may leave under it`,
1000
+ rulePath,
1001
+ };
1002
+ } else if (input.purposeOff === true) {
1003
+ excluded = {
1004
+ reason: "Share purpose disabled by your account's sharing policy",
1005
+ rulePath: `purposeOverrides[${purpose}] = false`,
1006
+ };
1007
+ } else if (posture === "blocked") {
1008
+ const pol = posturePol; // null = the relationship's own posture blocks (review r1 #3)
1009
+ const path =
1010
+ pol === null
1011
+ ? "relationship posture = blocked"
1012
+ : `sharingPurposePolicies[${pol.id}].posture=blocked (policy “${pol.name}” — ${pol.levelLabel})`;
1013
+ if (report) {
1014
+ reportCarveOut = {
1015
+ note:
1016
+ pol === null
1017
+ ? "Blocked for ordinary sharing — reachable for reports (nothing at the partner layer extinguishes the duty)"
1018
+ : `The “${pol.name}” policy blocks ordinary sharing — reachable for reports`,
1019
+ rulePath: path,
1020
+ };
1021
+ } else {
1022
+ excluded = {
1023
+ reason:
1024
+ pol === null
1025
+ ? "Blocked for this purpose by the relationship"
1026
+ : `Blocked for this purpose by your account's “${pol.name}” policy`,
1027
+ rulePath: path,
1028
+ };
1029
+ }
1030
+ }
1031
+ const excludedAll = excluded !== null;
1032
+
1033
+ // 5. which list binds (K13-12)
1034
+ const level = gov?.level ?? null;
1035
+ const govList = govNamed?.infoScope ?? null;
1036
+ const polScopeBinds =
1037
+ gov !== null &&
1038
+ Array.isArray(govList) &&
1039
+ (level === "team_row" ||
1040
+ level === "relationship" ||
1041
+ level === "account_internal" ||
1042
+ level === "inside_starter" ||
1043
+ (level === "agency_default" && gov.policy.edited === true));
1044
+ const legacy = legacyCeilingList(input.legacyCeiling);
1045
+ const ceilingIsStarter = legacy === null;
1046
+ let groupCeiling: string[] | null = legacy ?? pdRaw;
1047
+ let ceilingPath =
1048
+ legacy !== null
1049
+ ? "sharingScopeEdits (the account's partner / default rule — the legacy cell chain)"
1050
+ : pd === null
1051
+ ? "no Platform default"
1052
+ : `pol-starter-${purpose} v${pd.version} (Platform default — the starting scope for this purpose)`;
1053
+ if (ceilingIsStarter && polScopeBinds) {
1054
+ groupCeiling = null;
1055
+ ceilingPath = "";
1056
+ }
1057
+ if (inside) {
1058
+ groupCeiling = null;
1059
+ ceilingPath = "";
1060
+ }
1061
+ const tcScope = tcNamed?.infoScope ?? null;
1062
+ const tcItems = tc?.policy.infoScopeItems ?? null;
1063
+ const govItems = gov?.policy.infoScopeItems ?? null;
1064
+ const required = (g: string): boolean =>
1065
+ g === systemCode || (!inside && pd !== null && pdRequired.includes(g));
1066
+ const blockedSet = new Set(pdBlocked);
1067
+ const asSet = (v: unknown): Set<string> => new Set(isStringList(v) ? v : []);
1068
+ const categoriesOff = asSet(input.accountScope?.categoriesOff);
1069
+ const rowsOff = asSet(input.accountScope?.rowsOff);
1070
+ const categoriesOn = asSet(input.accountScope?.categoriesOn);
1071
+ const rowsOn = asSet(input.accountScope?.rowsOn);
1072
+ const underFloor = (code: string): boolean =>
1073
+ scope.ancestorsOf(code).some((c) => scope.row(c)?.platformFloor === true);
1074
+ // Clamp 4 (data.js L55165-L55170): the account's explicit choice wins both ways; else the
1075
+ // codebook's `shareableDefault` — a heightened category is off until the account turns it on.
1076
+ const categoryOffByDefault = (g: string): boolean =>
1077
+ !categoriesOn.has(g) && scope.row(g)?.shareableDefault === false;
1078
+ // Clamp 4b (L55185-L55196): a row is off when the account switched it (or a grouping above it)
1079
+ // off, or when it — or a grouping between it and its category — is heightened by default and
1080
+ // the account has not turned that one on (`shareVerdict`'s rule: turning a grouping on does not
1081
+ // turn on an off-by-default row beneath it).
1082
+ const heightenedOff = (code: string, g: string): boolean => {
1083
+ const chain = scope.ancestorsOf(code);
1084
+ if (chain.some((c) => rowsOff.has(c))) return true;
1085
+ const below = chain.slice(0, Math.max(chain.indexOf(g), 0));
1086
+ return below.some(
1087
+ (c) => !rowsOn.has(c) && scope.row(c)?.shareableDefault === false,
1088
+ );
1089
+ };
1090
+
1091
+ const out: Record<string, ShareCategoryEntry> = {};
1092
+ const allowedCategories: string[] = [];
1093
+ const govName = govNamed?.name ?? "";
1094
+ for (const g of tree.categories) {
1095
+ const items = tree.descendants.get(g) ?? [];
1096
+ const leaves = tree.leaves.get(g) ?? [];
1097
+ const platformRequired =
1098
+ !inside && pd !== null && pdRequired.includes(g)
1099
+ ? {
1100
+ rulePath: `pol-starter-${purpose} v${pd.version} · ${g} = Required (Platform default — set by the Platform Admin)`,
1101
+ }
1102
+ : null;
1103
+ const req = required(g);
1104
+ let allowed = true;
1105
+ let reason = excluded !== null ? excluded.reason : "Allowed";
1106
+ let path = excluded !== null ? excluded.rulePath : rulePath;
1107
+ const floorItems = items.filter(underFloor);
1108
+ const excludedItems: string[] = [];
1109
+ let excludedReason: string | null = null;
1110
+ const teamExcludedItems: string[] = [];
1111
+ let teamExcludedReason: string | null = null;
1112
+ const addExcluded = (rows: readonly string[], why: string): void => {
1113
+ for (const r of rows)
1114
+ if (!floorItems.includes(r) && !excludedItems.includes(r))
1115
+ excludedItems.push(r);
1116
+ if (rows.length > 0 && excludedReason === null) excludedReason = why;
1117
+ };
1118
+ if (gov === null) {
1119
+ allowed = false; // an unknown purpose: nothing leaves, System metadata included
1120
+ } else if ((!req || platformRequired !== null) && excludedAll) {
1121
+ allowed = false;
1122
+ } else if (excludedAll) {
1123
+ reason = "Allowed";
1124
+ path = rulePath;
1125
+ }
1126
+ if (allowed && !req && (categoriesOff.has(g) || categoryOffByDefault(g))) {
1127
+ allowed = false;
1128
+ reason = "Excluded by your account's Information Scope policy";
1129
+ path = categoriesOff.has(g)
1130
+ ? `policies.scopeCatalog[${g}].shareable = false`
1131
+ : `policies.scopeCatalog[${g}] not turned on — codebook core-information_scope shareableDefault = false (CVC-236 heightened protection: off until the account turns it on)`;
1132
+ }
1133
+ if (allowed && !req && !inside && blockedSet.has(g)) {
1134
+ allowed = false;
1135
+ reason =
1136
+ "Blocked for this purpose by the Platform default — no account can share it under this purpose";
1137
+ path = `pol-starter-${purpose} v${pd?.version ?? 1} · ${g} = Blocked (Platform default — CVC-236 heightened protection | set by the Platform Admin)`;
1138
+ }
1139
+ // 4b heightened rows off in the account (every category but System metadata, Required included)
1140
+ addExcluded(
1141
+ g === systemCode
1142
+ ? []
1143
+ : items.filter((r) => !underFloor(r) && heightenedOff(r, g)),
1144
+ "Heightened protection (CVC-236) — off in your account's Information Scope until the account turns it on",
1145
+ );
1146
+ if (
1147
+ allowed &&
1148
+ !req &&
1149
+ groupCeiling !== null &&
1150
+ !scopeListCovers(scope, groupCeiling, g)
1151
+ ) {
1152
+ allowed = false;
1153
+ reason = "Outside the payload for this purpose";
1154
+ path = ceilingPath;
1155
+ }
1156
+ if (
1157
+ allowed &&
1158
+ !req &&
1159
+ groupCeiling !== null &&
1160
+ !scopeListStrictlyCovers(scope, groupCeiling, g)
1161
+ ) {
1162
+ addExcluded(
1163
+ items.filter((r) => !scopeListCovers(scope, groupCeiling, g, r)),
1164
+ "Outside the payload for this purpose",
1165
+ );
1166
+ }
1167
+ if (
1168
+ allowed &&
1169
+ !req &&
1170
+ polScopeBinds &&
1171
+ !scopeListCovers(scope, govList, g)
1172
+ ) {
1173
+ allowed = false;
1174
+ reason = `Outside what the “${govName}” policy allows for this purpose`;
1175
+ path = `sharingPurposePolicies[${gov?.policy.id}].infoScope (policy “${govName}” — ${govNamed?.levelLabel})`;
1176
+ }
1177
+ if (
1178
+ allowed &&
1179
+ !req &&
1180
+ polScopeBinds &&
1181
+ !scopeListStrictlyCovers(scope, govList, g)
1182
+ ) {
1183
+ addExcluded(
1184
+ items.filter((r) => !scopeListCovers(scope, govList, g, r)),
1185
+ `Outside what the “${govName}” policy allows for this purpose`,
1186
+ );
1187
+ }
1188
+ const govRows = polScopeBinds ? own<unknown>(govItems, g) : undefined;
1189
+ if (allowed && !req && isStringList(govRows)) {
1190
+ const keep = new Set(govRows);
1191
+ addExcluded(
1192
+ items.filter(
1193
+ (r) =>
1194
+ !keep.has(r) &&
1195
+ !scope.ancestorsOf(r).some((a) => a !== g && keep.has(a)),
1196
+ ),
1197
+ `Outside what the “${govName}” policy allows for this purpose`,
1198
+ );
1199
+ }
1200
+ if (
1201
+ allowed &&
1202
+ !req &&
1203
+ tcScope !== null &&
1204
+ !scopeListCovers(scope, tcScope, g)
1205
+ ) {
1206
+ allowed = false;
1207
+ reason = `Outside what your team's “${tcNamed?.name}” policy allows`;
1208
+ path = `sharingPurposePolicies[${tc?.policy.id}].infoScope (policy “${tcNamed?.name}” — ${SHARE_LEVEL_LABEL.team}; a ceiling over “${govName}”)`;
1209
+ }
1210
+ if (allowed && !req && tc !== null) {
1211
+ const why = `Outside what your team's “${tcNamed?.name}” policy allows`;
1212
+ const outRows = new Set<string>();
1213
+ if (tcScope !== null && !scopeListStrictlyCovers(scope, tcScope, g)) {
1214
+ for (const r of items)
1215
+ if (!scopeListCovers(scope, tcScope, g, r)) outRows.add(r);
1216
+ }
1217
+ const tcRows = own<unknown>(tcItems, g);
1218
+ if (isStringList(tcRows)) {
1219
+ const keep = new Set(tcRows);
1220
+ for (const r of items)
1221
+ if (
1222
+ !keep.has(r) &&
1223
+ !scope.ancestorsOf(r).some((a) => a !== g && keep.has(a))
1224
+ )
1225
+ outRows.add(r);
1226
+ }
1227
+ for (const r of outRows)
1228
+ if (!floorItems.includes(r) && !excludedItems.includes(r))
1229
+ teamExcludedItems.push(r);
1230
+ if (teamExcludedItems.length > 0) teamExcludedReason = why;
1231
+ }
1232
+ // the group flip: every leaf row withheld → the category is withheld
1233
+ if (allowed && (!req || platformRequired !== null) && leaves.length > 0) {
1234
+ const gone = new Set(
1235
+ [...floorItems, ...excludedItems, ...teamExcludedItems].filter((r) =>
1236
+ leaves.includes(r),
1237
+ ),
1238
+ );
1239
+ if (gone.size >= leaves.length) {
1240
+ allowed = false;
1241
+ if (leaves.every((r) => floorItems.includes(r))) {
1242
+ reason = "Never shared — under the platform safety floor";
1243
+ path = "HTI_PLATFORM_SAFETY_FLOOR";
1244
+ } else if (leaves.some((r) => excludedItems.includes(r))) {
1245
+ reason = excludedReason ?? reason;
1246
+ } else {
1247
+ reason = teamExcludedReason ?? reason;
1248
+ }
1249
+ }
1250
+ }
1251
+ out[g] = {
1252
+ allowed,
1253
+ reason,
1254
+ rulePath: path,
1255
+ platformRequired,
1256
+ floorItems: uniq(floorItems),
1257
+ excludedItems: uniq(excludedItems),
1258
+ excludedReason,
1259
+ teamExcludedItems: uniq(teamExcludedItems),
1260
+ teamExcludedReason,
1261
+ };
1262
+ if (allowed) allowedCategories.push(g);
1263
+ }
1264
+
1265
+ return {
1266
+ allowed: !excludedAll,
1267
+ posture,
1268
+ postureSource,
1269
+ excluded,
1270
+ reportCarveOut,
1271
+ governing: govNamed,
1272
+ teamCeiling: tcNamed,
1273
+ inside,
1274
+ scope: out,
1275
+ allowedCategories,
1276
+ rulePath,
1277
+ };
1278
+ }