@htilabs/platform-common-models 0.79.0 → 0.81.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 +55 -0
  2. package/dist/authz/index.cjs +154 -2
  3. package/dist/authz/index.cjs.map +1 -1
  4. package/dist/authz/index.d.cts +174 -2
  5. package/dist/authz/index.d.ts +174 -2
  6. package/dist/authz/index.js +151 -2
  7. package/dist/authz/index.js.map +1 -1
  8. package/dist/{index-XWSYon40.d.cts → index-1pWiqEBC.d.cts} +1 -1
  9. package/dist/{index-Bh1zO_Vu.d.ts → index-uz57Fic9.d.ts} +1 -1
  10. package/dist/index.cjs +126 -5
  11. package/dist/index.cjs.map +1 -1
  12. package/dist/index.d.cts +4 -4
  13. package/dist/index.d.ts +4 -4
  14. package/dist/index.js +123 -5
  15. package/dist/index.js.map +1 -1
  16. package/dist/models/index.d.cts +2 -2
  17. package/dist/models/index.d.ts +2 -2
  18. package/dist/schemas/index.d.cts +25 -25
  19. package/dist/schemas/index.d.ts +25 -25
  20. package/dist/sharing-ceiling/index.cjs +33 -3
  21. package/dist/sharing-ceiling/index.cjs.map +1 -1
  22. package/dist/sharing-ceiling/index.d.cts +11 -7
  23. package/dist/sharing-ceiling/index.d.ts +11 -7
  24. package/dist/sharing-ceiling/index.js +33 -3
  25. package/dist/sharing-ceiling/index.js.map +1 -1
  26. package/dist/validation/index.d.cts +1 -1
  27. package/dist/validation/index.d.ts +1 -1
  28. package/package.json +2 -1
  29. package/src/__tests__/authz-resolve.test.ts +3 -0
  30. package/src/__tests__/authz-seat-app-access.test.ts +304 -0
  31. package/src/authz/index.ts +1 -0
  32. package/src/authz/seatAppAccess.ts +304 -0
  33. package/src/sharingCeiling/__tests__/fixtures_starterVerdicts.json +1727 -0
  34. package/src/sharingCeiling/__tests__/personContactRows.test.ts +185 -0
  35. package/src/sharingCeiling/coverage.ts +55 -6
  36. package/src/sharingCeiling/resolve.ts +31 -8
  37. package/dist/{agency-CnVTwLeV.d.ts → agency-BHv54o79.d.ts} +4 -4
  38. package/dist/{agency-8ufZJJDH.d.cts → agency-Djp57S71.d.cts} +4 -4
  39. package/dist/{cvcEntry-D787utvP.d.cts → cvcEntry-DAuhe0cd.d.cts} +8 -8
  40. package/dist/{cvcEntry-D787utvP.d.ts → cvcEntry-DAuhe0cd.d.ts} +8 -8
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/sharingCeiling/index.ts","../../src/generated/sharingPlatformStarter.ts","../../src/sharingCeiling/starter.ts","../../src/sharingCeiling/chain.ts","../../src/services/informationScopeResolver.ts","../../src/sharingCeiling/coverage.ts","../../src/sharingCeiling/defaults.ts","../../src/sharingCeiling/resolve.ts","../../src/sharingCeiling/fireShareEvent.ts","../../src/sharingCeiling/storedPolicyScope.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models/sharing-ceiling\n *\n * Browser-safe entry for the Inter-Agency Sharing CEILING on the CVC-236 v4\n * tree (co-2sx): the platform starter (generated, gated canon data), the\n * cell fold, the ONE read chain (`effectiveCeiling`) and the ONE coverage\n * rule (`scopeRowWithinCeiling`, with its door and composer-mask readers), and\n * THE share resolver (`resolveShare` — the ladder, the team ceiling, the\n * Platform default as the four states; Kickoff 13, GDR § 5.79).\n * Pure TypeScript, no mongoose, no I/O, no SOT import — pass the v4 tree as\n * an information-scope resolver. Also re-exported from the package root.\n *\n * 0.41.0 adds, lifted from Thread `@thread/shared` `sharingCeiling.ts`\n * (behaviour unchanged): the account's per-purpose default\n * (`shareDefaultScopeFor`, alias `accountSharePurposePolicy`; ./defaults.ts)\n * and two coverage readers (`isPermittedByCeiling`,\n * `intersectSharingCeilingLists`; ./coverage.ts).\n *\n * 0.42.0 adds THE share resolver (`resolveShare`; ./resolve.ts).\n *\n * 0.55.0 adds event-driven sharing's pure half (`ShareEvent`,\n * `fireShareEvent`, `shareListenersFor`; ./fireShareEvent.ts).\n *\n * 0.61.0 names the account's authored purpose-specific partner rule as the\n * governing policy (`partnerPurposeRule` → the virtual `byPurpose` fork;\n * ./resolve.ts).\n *\n * 0.71.0 adds the one reading of a stored sharing policy's information-scope\n * list (`readStoredPolicyScope`; ./storedPolicyScope.ts).\n */\n\nexport * from \"./starter.js\";\nexport * from \"./chain.js\";\nexport * from \"./coverage.js\";\nexport * from \"./defaults.js\";\nexport * from \"./resolve.js\";\nexport * from \"./fireShareEvent.js\";\nexport * from \"./storedPolicyScope.js\";\n","/**\n * @htilabs/platform-common-models — the platform sharing starter (co-2sx)\n *\n * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.\n * Regenerate with:\n * `python3 scripts/gen-sharing-starter.py <prototype root> <platform-prototype root>`.\n *\n * Canon (read from git objects at origin/main):\n * - htilabstech/prototype HTI-LEADS-PAVE-Thread-prototype.html @ d85f05b7\n * `HTI_SHARE_PLATFORM_STARTER` L326475-L326543\n * (scopeVersion · scopeByPurpose · counterpartyOverrides);\n * - htilabstech/platform-prototype src/data.js @ a6f1f3a5 (the contract of\n * record, GDR § 5.79): `data.sharing.scopeByPurpose` /\n * `counterpartyOverrides` L38170-L38190, and the\n * platform purpose rows `sharing.purposes[].enabled`\n * L32450-L32531;\n * - htilabstech/prototype docs/share-roi/information_scope_v4.fields.csv @ d85f05b7: the distinct\n * `row_v4` homes of its 517 fields (`fieldHomeRows`; the sentinel\n * \"rides with its record\" is not a row and is left out).\n * The two starter copies are equal (the generator refuses otherwise). GATE M\n * (`src/__tests__/sharing-starter-canon.test.ts`) holds this module equal to\n * `src/__sot__/sharingStarter.pin.json` and every code to a live, non-floor\n * CVC-236 v4 row.\n *\n * CANON GAP: `counterpartyOverrides` is keyed by canon's DEMONSTRATION partner\n * ids (palomar, okcpd, legal_aid_ok). No registry agency carries them, so the\n * seeded-partner rung binds on no real data until the platform maps them.\n */\n\n/** Where this data was taken from (provenance, not compared by `--check`). */\nexport const SHARING_PLATFORM_STARTER_SOURCE = {\n \"monolith\": {\n \"repo\": \"htilabstech/prototype\",\n \"file\": \"HTI-LEADS-PAVE-Thread-prototype.html\",\n \"sha\": \"d85f05b7\",\n \"lines\": [\n 326475,\n 326543\n ]\n },\n \"mirror\": {\n \"repo\": \"htilabstech/platform-prototype\",\n \"file\": \"src/data.js\",\n \"sha\": \"a6f1f3a5\",\n \"starterLines\": [\n 38170,\n 38190\n ],\n \"purposeLines\": [\n 32450,\n 32531\n ]\n },\n \"fieldPlacements\": {\n \"repo\": \"htilabstech/prototype\",\n \"file\": \"docs/share-roi/information_scope_v4.fields.csv\",\n \"sha\": \"d85f05b7\"\n }\n} as const;\n\n// <generated-data>\nexport const SHARING_PLATFORM_STARTER_DATA = {\n scopeVersion: 4,\n scopeByPurpose: {\n \"referral\": [\"identifying\", \"contact\", \"services\", \"system\", \"summary_needs_assessment\"],\n \"case_collaboration\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_needs_assessment\"],\n \"deconfliction\": [\"identifying\", \"system\"],\n \"mandatory_reporting\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_needs_assessment\", \"offenders.identifying\", \"offenders.risk\", \"relationships_household\", \"family\"],\n \"discretionary_share\": [\"identifying\", \"system\"],\n \"authority_reporting\": [\"identifying\", \"risk\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"offenders.identifying\", \"offenders.risk\", \"relationships_household\", \"family\"],\n \"automatic_account_share\": [\"identifying\", \"system\"],\n \"records_request\": [\"identifying\", \"system\"],\n },\n counterpartyOverrides: {\n \"palomar\": {\n \"case_collaboration\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"health_accommodation\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_mental_health_screen\", \"summary_behavioral_health_intake\", \"summary_trauma_and_coping_screen\", \"summary_needs_assessment\"],\n },\n \"okcpd\": {\n \"mandatory_reporting\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_needs_assessment\", \"offenders.identifying\", \"offenders.risk\", \"relationships_household\", \"family\"],\n \"referral\": [\"identifying\", \"contact\", \"services\", \"system\", \"summary_needs_assessment\"],\n },\n \"legal_aid_ok\": {\n \"referral\": [\"identifying\", \"contact\", \"services\", \"notes\", \"system\", \"summary_needs_assessment\"],\n },\n },\n purposeEnabled: {\n \"referral\": true,\n \"case_collaboration\": true,\n \"deconfliction\": true,\n \"mandatory_reporting\": true,\n \"discretionary_share\": true,\n \"authority_reporting\": true,\n \"automatic_account_share\": true,\n \"records_request\": false,\n },\n fieldHomeRows: [\n \"accommodation_needs\",\n \"ad_content\",\n \"additional_ids\",\n \"addresses\",\n \"case_attachments\",\n \"case_determinations\",\n \"case_lifecycle\",\n \"case_notes\",\n \"commercial_activity\",\n \"contact_info\",\n \"demographics\",\n \"derived_risk_signals\",\n \"dob\",\n \"encounter_location\",\n \"family.health_accommodation\",\n \"family.identifying\",\n \"family.risk\",\n \"full_ae_intake\",\n \"full_behavioral_health_intake\",\n \"full_danger_assessment\",\n \"full_findings\",\n \"full_hope_scale\",\n \"full_ida\",\n \"full_initial_screen\",\n \"full_injury_and_strangulation\",\n \"full_lap\",\n \"full_mental_health_screen\",\n \"full_needs_assessment\",\n \"full_stalking_assessment\",\n \"full_tra\",\n \"full_trauma_and_coping_screen\",\n \"health_status\",\n \"identifying\",\n \"immigration_applications\",\n \"immigration_status\",\n \"instruments\",\n \"names\",\n \"network_membership\",\n \"object_identity_attributes\",\n \"offenders.risk\",\n \"others.risk\",\n \"persona_links\",\n \"phone_identifiers\",\n \"plans_goals\",\n \"priorities_safety\",\n \"relationships_household\",\n \"screen_indicators\",\n \"service_history\",\n \"session_summary\",\n \"summary_ae_intake\",\n \"summary_behavioral_health_intake\",\n \"summary_danger_assessment\",\n \"summary_findings\",\n \"summary_hope_scale\",\n \"summary_ida\",\n \"summary_initial_screen\",\n \"summary_injury_and_strangulation\",\n \"summary_lap\",\n \"summary_mental_health_screen\",\n \"summary_needs_assessment\",\n \"summary_stalking_assessment\",\n \"summary_tra\",\n \"summary_trauma_and_coping_screen\",\n \"system\",\n \"system_involvement\",\n \"victimization\",\n ],\n} as const;\n// </generated-data>\n","/**\n * The platform sharing starter — what governs a share before an account has\n * authored anything (co-2sx).\n *\n * The data is GENERATED from canon (`scripts/gen-sharing-starter.py` →\n * `src/generated/sharingPlatformStarter.ts`) and held equal to canon by GATE M\n * (`src/__tests__/sharing-starter-canon.test.ts`, against\n * `src/__sot__/sharingStarter.pin.json`). This module types it and freezes it.\n *\n * Canon: prototype `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7\n * `HTI_SHARE_PLATFORM_STARTER` L326475-L326543 (scopeVersion ·\n * scopeByPurpose · counterpartyOverrides); platform-prototype `src/data.js`\n * @ a6f1f3a `data.sharing.scopeByPurpose` / `counterpartyOverrides`\n * L38170-L38190 (the contract of record, GDR § 5.79) and the platform\n * purpose rows `sharing.purposes[].enabled` L32450-L32531 (`records_request`\n * ships `enabled: false`, L32527); prototype\n * `docs/share-roi/information_scope_v4.fields.csv` @ d85f05b7 (where each\n * field is homed, `row_v4`).\n */\n\nimport {\n SHARING_PLATFORM_STARTER_DATA,\n SHARING_PLATFORM_STARTER_SOURCE,\n} from \"../generated/sharingPlatformStarter.js\";\n\n/** The tree version every starter list and every stored ceiling list is stamped with. */\nexport const SHARING_CEILING_SCOPE_VERSION = 4 as const;\n\n/** purpose code (CVC-84 key) → v4 information-scope row codes. */\nexport type SharingPurposeLists = Readonly<Record<string, readonly string[]>>;\n\nexport interface SharingPlatformStarter {\n readonly scopeVersion: typeof SHARING_CEILING_SCOPE_VERSION;\n /** The platform per-purpose default — canon's last rung. A purpose with no row has no platform ceiling. */\n readonly scopeByPurpose: SharingPurposeLists;\n /** Platform-seeded partner rules: partner id → purpose → v4 row codes. */\n readonly counterpartyOverrides: Readonly<Record<string, SharingPurposeLists>>;\n}\n\nfunction freezeLists(lists: Readonly<Record<string, readonly string[]>>): SharingPurposeLists {\n const out: Record<string, readonly string[]> = {};\n for (const [purpose, codes] of Object.entries(lists)) out[purpose] = Object.freeze([...codes]);\n return Object.freeze(out);\n}\n\n/**\n * The platform's own sharing rules (canon's `HTI_SHARE_PLATFORM_STARTER`,\n * minus the demo-agency relationship / policy seeds). Deep-frozen.\n *\n * CANON GAP: `counterpartyOverrides` is keyed by canon's DEMONSTRATION partner\n * ids (`palomar`, `okcpd`, `legal_aid_ok`). No registry agency carries them,\n * so the seeded-partner rung binds on no real data until the platform maps\n * them. They ship as canon has them.\n */\nexport const HTI_SHARE_PLATFORM_STARTER: SharingPlatformStarter = Object.freeze({\n scopeVersion: SHARING_CEILING_SCOPE_VERSION,\n scopeByPurpose: freezeLists(SHARING_PLATFORM_STARTER_DATA.scopeByPurpose),\n counterpartyOverrides: Object.freeze(\n Object.fromEntries(\n Object.entries(SHARING_PLATFORM_STARTER_DATA.counterpartyOverrides).map(([cp, lists]) => [\n cp,\n freezeLists(lists),\n ]),\n ),\n ),\n});\n\n/**\n * The platform purpose rows' `enabled` flag (data.js `sharing.purposes`). The\n * contract of record disables a purpose whose platform row is `enabled:\n * false` unless the account overrides it `true` (data.js clamp 1,\n * L51352-L51354). `records_request` ships disabled.\n */\nexport const HTI_SHARE_PLATFORM_PURPOSE_ENABLED: Readonly<Record<string, boolean>> = Object.freeze({\n ...SHARING_PLATFORM_STARTER_DATA.purposeEnabled,\n});\n\n/**\n * The v4 rows at least one field is HOMED on (canon's field placements,\n * `information_scope_v4.fields.csv` `row_v4`). The ceiling coverage rule\n * reads it: a row with fields homed directly on it and no rest row is within\n * a ceiling only when it or an ancestor is listed.\n */\nexport const INFORMATION_SCOPE_FIELD_HOME_ROWS: ReadonlySet<string> = new Set(\n SHARING_PLATFORM_STARTER_DATA.fieldHomeRows,\n);\n\n/** Where the starter data was taken from (canon repo, file, SHA, line ranges). */\nexport const HTI_SHARE_PLATFORM_STARTER_SOURCE = SHARING_PLATFORM_STARTER_SOURCE;\n","/**\n * The Inter-Agency Sharing ceiling read chain (co-2sx): the account's stored\n * ceiling CELLS folded into canon's `sharingScopeEdits`, and the ONE chain\n * that turns them, the platform starter and the purpose switches into the\n * list a share for one recipient × purpose may carry.\n *\n * Pure, total on stored data, no I/O. Throws only on a caller's programming\n * error (a missing / reserved row key, a missing purpose).\n *\n * Canon — prototype `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7:\n * - `shareEffectiveCeiling` L327966-L328090; the per-purpose rung\n * L328040-L328082, the chain itself L328053-L328058:\n *\n * const rowKey = r.__external ? \"__external__\" : r.id;\n * const per = edits[rowKey] && edits[rowKey][opts.purposeCode];\n * const seeded = (starter.counterpartyOverrides[rowKey] || {})[opts.purposeCode];\n * const def = edits.__default__ && edits.__default__[opts.purposeCode];\n * const platformDefault = starter.scopeByPurpose[opts.purposeCode];\n * const allowed = per || seeded || def || platformDefault || null;\n *\n * - the purpose switch L327999-L328005 (an explicit `false` only).\n * Platform prototype `src/data.js` @ a6f1f3a — the contract of record\n * (GDR § 5.79), `HTI_SHARE_POLICY_API.effectiveCeiling` L51324ff:\n * - clamp 1 L51352-L51354: a purpose is off when the account switched it\n * off, OR when its platform row is `enabled: false` and the account has\n * not switched it on (`records_request`, L32527). This module follows the\n * contract of record; the monolith reads only the explicit `false`.\n * - clamp 5 L51516-L51525: the same chain as the monolith.\n * - `EXTERNAL_RECIPIENT_KEY = \"__external__\"` L50434: an off-platform\n * recipient resolves through the same chain under that key, so an\n * un-authored off-platform purpose follows the account default, then the\n * platform default (L50427-L50430).\n *\n * One JavaScript detail of canon's `||` chain is kept: an EMPTY authored\n * list is truthy, so it BINDS (it lets nothing but System metadata leave).\n *\n * STRICTER THAN CANON (ruling, co-2sx review): a purpose with no rung at all\n * fails CLOSED — `allowed: []`, rung `none` — where canon's `|| null` reads\n * no ceiling (`if (allowed && …)`, L328059). Every one of the eight core\n * CVC-84 purposes has a platform row, so `none` can only come from a caller\n * error (a misspelled purpose, a LEADS-wing purpose on a core share, a\n * replaced starter missing a row); an unknown purpose must never mean\n * \"anything may leave\".\n */\n\nimport {\n HTI_SHARE_PLATFORM_PURPOSE_ENABLED,\n HTI_SHARE_PLATFORM_STARTER,\n SHARING_CEILING_SCOPE_VERSION,\n type SharingPlatformStarter,\n} from \"./starter.js\";\n\n/** The account default row key — canon `sharingScopeEdits.__default__` (L328056; data.js L51519). */\nexport const SHARING_CEILING_DEFAULT_ROW_KEY = \"__default__\" as const;\n\n/** The off-platform / unspecified recipients row key (canon L328053; data.js `EXTERNAL_RECIPIENT_KEY`, L50434). */\nexport const SHARING_CEILING_EXTERNAL_ROW_KEY = \"__external__\" as const;\n\n/** rowKey (partner id · `__default__` · `__external__`) → purpose → v4 row codes. */\nexport type SharingScopeEdits = Readonly<\n Record<string, Readonly<Record<string, readonly string[]>>>\n>;\n\n/** The fields of one stored ceiling cell this read looks at (cells keyed agencyId × rowKey × purpose). */\nexport interface SharingCeilingCellLike {\n readonly rowKey?: unknown;\n readonly purpose?: unknown;\n readonly scopeVersion?: unknown;\n readonly informationScope?: unknown;\n}\n\nconst own = <V>(record: unknown, key: string): V | undefined =>\n record !== null &&\n typeof record === \"object\" &&\n Object.prototype.hasOwnProperty.call(record, key)\n ? ((record as Record<string, V>)[key] as V)\n : undefined;\n\nconst isStringList = (v: unknown): v is readonly string[] =>\n Array.isArray(v) && v.every((c) => typeof c === \"string\");\n\n/**\n * The list one PRESENT cell carries. A cell is a rule by being there: stamped\n * 4 with an array of strings → that list (a copy); anything else (unstamped,\n * a v3 stamp, a missing list, a non-array, a non-string entry) → `[]`, which\n * binds and covers nothing. A malformed rule never widens a share by falling\n * through to a broader rung.\n */\nexport function sharingCeilingCellList(cell: SharingCeilingCellLike): string[] {\n if (cell.scopeVersion === SHARING_CEILING_SCOPE_VERSION && isStringList(cell.informationScope)) {\n return [...cell.informationScope];\n }\n return [];\n}\n\nconst sameSet = (a: readonly string[], b: readonly string[]): boolean => {\n const sa = new Set(a);\n const sb = new Set(b);\n return sa.size === sb.size && [...sa].every((c) => sb.has(c));\n};\n\n/**\n * Fold ONE sending account's ceiling cells into canon's `sharingScopeEdits`.\n *\n * - A cell is present or absent; there is no status. An ABSENT cell is no\n * rule, and the chain falls through.\n * - A present cell binds with {@link sharingCeilingCellList}: `[]` binds; an\n * unstamped, v3-stamped or malformed list reads as `[]`.\n * - A cell without a string `rowKey` and `purpose` cannot be attributed to a\n * cell and is skipped (it is not a rule for any cell).\n * - Two cells for the same (rowKey, purpose) — the store's key forbids it —\n * keep the list when they agree as sets, else read `[]` (fail closed).\n *\n * The caller passes one account's cells; the fold does not filter by agency.\n */\nexport function sharingScopeEditsFromCells(\n cells: Iterable<SharingCeilingCellLike | null | undefined> | null | undefined,\n): SharingScopeEdits {\n const byRow = new Map<string, Map<string, string[]>>();\n if (cells === null || cells === undefined || typeof (cells as Iterable<unknown>)[Symbol.iterator] !== \"function\") {\n return {};\n }\n for (const cell of cells) {\n if (cell === null || typeof cell !== \"object\") continue;\n const { rowKey, purpose } = cell;\n if (typeof rowKey !== \"string\" || rowKey === \"\" || typeof purpose !== \"string\" || purpose === \"\") continue;\n const list = sharingCeilingCellList(cell);\n const row = byRow.get(rowKey) ?? new Map<string, string[]>();\n const prior = row.get(purpose);\n row.set(purpose, prior === undefined || sameSet(prior, list) ? list : []);\n byRow.set(rowKey, row);\n }\n // Object.fromEntries defines OWN properties, so a row key such as\n // `__proto__` is a key, never the prototype.\n return Object.fromEntries([...byRow].map(([k, row]) => [k, Object.fromEntries(row)]));\n}\n\n/** Which rung of the chain answered. */\nexport type SharingCeilingRung =\n | \"purpose_disabled\"\n | \"partner_rule\"\n | \"seeded_partner_rule\"\n | \"account_default\"\n | \"platform_default\"\n | \"none\";\n\nexport interface EffectiveSharingCeiling {\n /**\n * The v4 row codes a share may carry (read with `scopeRowWithinCeiling`).\n * `[]` when the purpose is disabled, and when no rung exists for the\n * purpose (rung `none` — fails closed; see the module header).\n */\n readonly allowed: string[];\n readonly rung: SharingCeilingRung;\n /** The purpose is switched off for the account (`allowed` is then `[]`). */\n readonly disabled: boolean;\n}\n\nexport interface EffectiveSharingCeilingInputs {\n /** The sending account's authored lists ({@link sharingScopeEditsFromCells}). */\n readonly edits: SharingScopeEdits | null | undefined;\n /** Defaults to {@link HTI_SHARE_PLATFORM_STARTER}. */\n readonly starter?: SharingPlatformStarter;\n /** The account's Share Purposes switches: `false` disables, `true` re-enables a platform-disabled purpose. */\n readonly purposeOverrides?: Readonly<Record<string, boolean | undefined>> | null;\n /**\n * Platform purpose `enabled` flags, merged OVER\n * {@link HTI_SHARE_PLATFORM_PURPOSE_ENABLED} (a purpose the map does not\n * name keeps the platform row). `null` / `undefined` = the platform rows.\n */\n readonly purposeEnabled?: Readonly<Record<string, boolean | undefined>> | null;\n}\n\n/**\n * One rung's list as the chain reads it: absent (`undefined` / `null`) falls\n * through, a list of strings binds (copied), anything else binds as `[]`.\n */\nfunction rungList(value: unknown): string[] | undefined {\n if (value === undefined || value === null) return undefined;\n return isStringList(value) ? [...value] : [];\n}\n\n/**\n * Is `purpose` switched off? The contract of record (data.js clamp 1,\n * L51352-L51354): the account's explicit `false`, or a platform row\n * `enabled: false` the account has not overridden `true`. `purposeEnabled`\n * is merged over the platform rows (a purpose it does not name, or names\n * with a non-boolean, keeps the platform row); `null` = the platform rows.\n */\nexport function isSharingPurposeDisabled(\n purpose: string,\n purposeOverrides?: Readonly<Record<string, boolean | undefined>> | null,\n purposeEnabled?: Readonly<Record<string, boolean | undefined>> | null,\n): boolean {\n const override = own<unknown>(purposeOverrides, purpose);\n if (override === false) return true;\n const callerRow = own<unknown>(purposeEnabled, purpose);\n const enabled =\n typeof callerRow === \"boolean\"\n ? callerRow\n : own<unknown>(HTI_SHARE_PLATFORM_PURPOSE_ENABLED, purpose);\n return enabled === false && override !== true;\n}\n\n/**\n * The ceiling row key for one recipient: `__external__` for an off-platform\n * recipient, else its partner id (canon L328053). Throws on a non-external\n * recipient with no id, or whose id is a reserved row key.\n */\nexport function sharingCeilingRowKey(recipient: {\n readonly external?: boolean;\n readonly id?: string | null;\n}): string {\n if (recipient.external === true) return SHARING_CEILING_EXTERNAL_ROW_KEY;\n const id = recipient.id;\n if (typeof id !== \"string\" || id === \"\") {\n throw new TypeError(\"sharing ceiling: an on-platform recipient needs a partner id\");\n }\n if (id === SHARING_CEILING_DEFAULT_ROW_KEY || id === SHARING_CEILING_EXTERNAL_ROW_KEY) {\n throw new RangeError(`sharing ceiling: \"${id}\" is a reserved row key, not a partner id`);\n }\n return id;\n}\n\n/**\n * The ceiling for one recipient row and one purpose, by canon's chain:\n *\n * purpose disabled (clamp 1) → [] (purpose_disabled)\n * edits[rowKey][purpose] (partner_rule)\n * || starter.counterpartyOverrides[rowKey][purpose] (seeded_partner_rule)\n * || edits.__default__[purpose] (account_default)\n * || starter.scopeByPurpose[purpose] (platform_default)\n * || [] (none — fails closed)\n *\n * `rowKey` is a partner id or `__external__` ({@link sharingCeilingRowKey});\n * `__default__` is refused (it is the account default, not a recipient).\n */\nexport function effectiveCeiling(\n rowKey: string,\n purpose: string,\n inputs: EffectiveSharingCeilingInputs,\n): EffectiveSharingCeiling {\n if (typeof rowKey !== \"string\" || rowKey === \"\") {\n throw new TypeError(\"sharing ceiling: rowKey must be a partner id or __external__\");\n }\n if (rowKey === SHARING_CEILING_DEFAULT_ROW_KEY) {\n throw new RangeError(\"sharing ceiling: __default__ is the account default, not a recipient row key\");\n }\n if (typeof purpose !== \"string\" || purpose === \"\") {\n throw new TypeError(\"sharing ceiling: purpose must be a share purpose code\");\n }\n const starter = inputs.starter ?? HTI_SHARE_PLATFORM_STARTER;\n if (isSharingPurposeDisabled(purpose, inputs.purposeOverrides, inputs.purposeEnabled)) {\n return { allowed: [], rung: \"purpose_disabled\", disabled: true };\n }\n const edits = inputs.edits;\n const rungs: readonly [SharingCeilingRung, unknown][] = [\n [\"partner_rule\", own(own(edits, rowKey), purpose)],\n [\"seeded_partner_rule\", own(own(starter.counterpartyOverrides, rowKey), purpose)],\n [\"account_default\", own(own(edits, SHARING_CEILING_DEFAULT_ROW_KEY), purpose)],\n [\"platform_default\", own(starter.scopeByPurpose, purpose)],\n ];\n for (const [rung, value] of rungs) {\n const allowed = rungList(value);\n if (allowed !== undefined) return { allowed, rung, disabled: false };\n }\n // Stricter than canon's `|| null` (module header): fail closed.\n return { allowed: [], rung: \"none\", disabled: false };\n}\n","/**\n * @htilabs/platform-common-models — Information scope resolver (CVC-236 v4)\n *\n * The ONE implementation of how a stored information-scope selection reads\n * against the v4 tree, so Thread and PAVE (preview and send, picker and door)\n * cannot disagree. Pure and dependency-free: no imports, no I/O, never\n * mutates its inputs. Browser-safe entry: `@htilabs/platform-common-models/information-scope`.\n *\n * Spec (canon, read-only): htilabstech/prototype\n * docs/share-roi/INFOSCOPE_V4_DEV_HANDOFF_2026-10-09.md\n * @ 7ca7e586ae487c608da657d426598a65d5b06111 (merge of the SIGNED-GRAIN\n * content commit e86dd89cdba5cbb39ccfc7fb35aff8cbf0774790, which amends\n * § 3 only and re-labels the migrations CSV; § 2, § 7, § 8 and the rows CSV\n * are unchanged from 6dab8a95 / 00179edc)\n * - § 2 rules 1–7 (\"the resolver contract — build exactly this, nothing\n * cleverer\") — every behaviour below cites its rule;\n * - § 3 the migration rules (identity · row · category · subtract ·\n * retired before v4) and `scopeVersion`; a signed release keeps its list\n * as signed and its current reading is DERIVED at read time; a retired\n * code \"stays recognisable in stored data forever\";\n * - § 7 row 6 a branch-grain pick is expanded to the ceiling's grain\n * before clamping; a sender can never widen;\n * - § 8 the enums.\n * Release grain (Crysta, 2026-10-09; SOT v2.1.0 `migrations.ruling`, quoted\n * verbatim there): \"a SIGNED RELEASE keeps the grain it was signed at ...\n * Policies and presets (agency-authored, not consent) take the merged\n * successor with a dated version row.\" Canon carries it since SIGNED-GRAIN\n * (prototype e86dd89c: `signed_release_grain: keep` on the nine `rows` merge\n * folds; handoff § 3 amended). So `readSelection` takes WHOSE list it is\n * (`subject`): a release or a share (frozen at send, § 3) naming a code on a\n * `releaseReading: \"retain\"` line at scopeVersion 3 is NOT mapped — the code\n * comes back under `retained` with its v3 field membership, for the builder\n * to deliver read-only; a policy takes the successor (`widened`) and the\n * reading says a dated version row is due. The widening identity line canon\n * leaves unmarked (`immigration_status`, `releaseReading: \"successor\"`) reads\n * as itself for every subject.\n * Reference implementation of rule-1 kind-row resolution:\n * tools/infoscope/phase4_stress_test.py `resolve_home` (same SHA).\n *\n * WHAT A SELECTION STORES. `information_scope: string[]` holds canon's scope\n * codes as canon spells them — `names`, `identifying.other`,\n * `offenders.risk` (handoff § 8: \"lowercase snake, or `<kind>.<row>`\") —\n * NOT the package's SOT keys (`offenders__risk`) and NOT seven-segment wire\n * codes (`236-016-001-002-…`). `ScopeRow.scopeCode` / `parentScopeCode` are\n * in that space; `scopeRowsFromSot` maps the SOT into it.\n *\n * ALWAYS COVERED. `system_info` and its ancestor `system` (\"System metadata —\n * always included, never a choice\", handoff § 1; the field placements home\n * the system fields on `system`) are covered by every selection.\n *\n * Two kinds of call:\n * - READS (`isCovered`, `isIncludedOnShare`, `shareVerdict`,\n * `isVisibleAtLevel`, `readSelection`, `readRestriction`,\n * `expandBranchPickToGrain`, `clampToCeiling`) are total: they never\n * throw on stored data. An unknown code, a null list or an unsupported\n * `scopeVersion` (absent, 2, or anything but 3 / 4) includes nothing\n * (fail closed). `readSelection`'s `subject` is the caller's, not stored\n * data: a missing or unknown one throws (no silent default).\n * - PICKER WRITES (`selectAll`, `deselectChild`, `expandSelectAll`), the\n * build-time `rowForSubject`, and the constructor throw on programming\n * errors (an unknown or non-selectable code, a malformed tree).\n */\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n/** The tree version this resolver reads to (handoff § 3: \"today 3, after this round 4\"). */\nexport const INFORMATION_SCOPE_VERSION = 4 as const;\n\n/**\n * The `scopeVersion` stamps a stored list may carry and still be read: 3\n * (through the v3 → v4 table) and 4. A 2 list, and an UNSTAMPED list (which\n * is v2-era), must go through canon's conjunctive v2 → v3 table first (SOT\n * v2.1.0 `migrations.readAt` / `migrations.unstamped`: the `retired before\n * v4` lines name \"the flattened v3 reading, not an unconditional one\"); this\n * resolver reads no v2 → v3 table, so those lists are unsupported and include\n * nothing (fail closed). The one exception is not here: a stored sharing POLICY\n * list with no stamp is read by `readStoredPolicyScope` (sharing-ceiling),\n * which carries it through canon's v2 → v3 category lines first.\n */\nexport const INFORMATION_SCOPE_READABLE_VERSIONS: readonly number[] = Object.freeze([3, 4]);\n\n/** Required on every stored selection and always included (handoff § 2 rule 1; § 6). */\nexport const INFORMATION_SCOPE_SYSTEM_INFO = \"system_info\" as const;\n\n// ─── Row and migration input shapes ─────────────────────────────────────────\n\n/** A kind of other named person (handoff § 1; § 8 `kind_branch`). */\nexport type ScopePersonKind = \"offenders\" | \"family\" | \"others\";\n\n/** Whose record a record is: the client, or another named person's kind (rule 1). */\nexport type ScopeSubjectKind = \"client\" | ScopePersonKind;\n\n/** `kind_branch` (§ 8); `null` on System and Notes rows (blank in the CSV). */\nexport type ScopeKindBranch = ScopeSubjectKind | \"leads\" | null;\n\n/**\n * `row_type` (§ 8). The tree also carries `branch` (`primary_client`,\n * `other_named_persons`) and the LEADS spelling `sub-category`, which § 8's\n * list omits; both are accepted as written.\n */\nexport type ScopeRowType =\n | \"branch\"\n | \"category\"\n | \"subcategory\"\n | \"sub-category\"\n | \"person_type\"\n | \"category_rest\"\n | \"instrument row\";\n\n/** `status` (§ 8). */\nexport type ScopeRowStatus = \"as_today\" | \"new\" | \"retired\";\n\n/** `special_data_type` (§ 8, plus `evidence`, which the tree carries on `case_attachments`). */\nexport type ScopeSpecialDataType =\n | \"none\"\n | \"survivor_confidential\"\n | \"criminal_intelligence\"\n | \"evidence\";\n\n/** The three app-relevance columns (§ 4). */\nexport type ScopeApp = \"pave\" | \"thread\" | \"leads\";\nexport type ScopeApps = Readonly<Record<ScopeApp, boolean>>;\n\n/**\n * One tree row, in the selection-code space (see header). Bind the SOT with\n * `scopeRowsFromSot`. Extra fields on a caller's row type are carried through\n * (`row(code)` returns the caller's row).\n */\nexport interface ScopeRow {\n /** The code a selection stores (canon's spelling: `offenders.risk`). */\n scopeCode: string;\n parentScopeCode: string | null;\n rowType: ScopeRowType;\n kindBranch: ScopeKindBranch;\n /** On a per-kind row (`offenders.risk`): the client row it copies (`risk`). Required there. */\n kindRow?: string;\n /** App relevance (§ 4). Informational: no resolver decision reads it. */\n apps: ScopeApps;\n selectable: boolean;\n /** `shareable_default = on` (rule 4: `false` = off by default). */\n shareableDefault: boolean;\n platformFloor: boolean;\n levelFloor: 1 | 3;\n specialDataType: ScopeSpecialDataType;\n /** A `retired` row is never covered, offered or written. */\n status: ScopeRowStatus;\n replacesV3?: readonly string[];\n}\n\n/** The four migration rules of handoff § 3, plus the pre-v4 retirement reading. */\nexport type ScopeMigrationRule = \"identity\" | \"row\" | \"category\" | \"subtract\" | \"retired before v4\";\n\n/** One from-to line (selection-code space); `to` is empty for \"(nothing)\". */\nexport interface ScopeMigration {\n from: string;\n to: readonly string[];\n rule: ScopeMigrationRule;\n note?: string;\n /** The line reads WIDER than v3 did (SOT `widens: true`). A policy takes it; see `releaseReading`. */\n widens?: boolean;\n /**\n * On every `widens` line (SOT; ruling 2026-10-09, canon SIGNED-GRAIN).\n * `retain` — canon's nine merge folds (`signed_release_grain: keep`): a\n * release or share at scopeVersion 3 keeps the code at its v3 grain instead\n * of reading `to`; requires exactly one `to` and `v3Fields` / `v3Domains`.\n * `successor` — a widening identity line canon leaves unmarked\n * (`immigration_status`): every subject reads `to` (`releaseReadingNote`).\n * Absent: `to` is every subject's reading.\n */\n releaseReading?: \"retain\" | \"successor\";\n /** Why a widening line is read as its successor by a release too. */\n releaseReadingNote?: string;\n /** `successor` (SOT, on every `widens` line): a policy or preset reads `to`. */\n policyReading?: \"successor\";\n /** A `retired before v4` line (ruling 2): a stated reading only a v2-era list can need. */\n informational?: boolean;\n /**\n * On a `retain` line: the fields whose v3 home was the `from` unit (canon\n * field placements `home_unit_today`) — what a retained release delivers,\n * read-only. Field ids (`capture.hiv_status`), not scope codes. Empty = the\n * unit homed no field, so a release retaining it delivers nothing.\n */\n v3Fields?: readonly string[];\n /**\n * On a `retain` line: the distinct `assertion_domain` of `v3Fields`. CATEGORY\n * grain in v3 (`access_accommodations`, `immigration_legal_status` each span\n * every unit of their category): the field family, NOT the unit's membership.\n * Deliver by `v3Fields`.\n */\n v3Domains?: readonly string[];\n /** On a `retain` line: why the membership is what it is (an empty unit; a derivation under veto). */\n v3FieldsNote?: string;\n}\n\n// ─── Output shapes ───────────────────────────────────────────────────────────\n\n/** How one stored code was read. `unknown` = no row, no table line: it includes nothing. */\nexport type ScopeReadingRule = ScopeMigrationRule | \"unknown\";\n\nexport interface ScopeCodeReading {\n readonly from: string;\n readonly rule: ScopeReadingRule;\n /** The v4 codes it reads as; empty for a retained code (see `ScopeReading.retained`). */\n readonly reads: readonly string[];\n /** It read through a line flagged as wider than v3 (never true for a retained code). */\n readonly widens: boolean;\n /** A release or share kept it at its v3 grain (`releaseReading: \"retain\"`). */\n readonly retained: boolean;\n}\n\n/**\n * Whose stored list is being read (handoff § 3; ruling 2026-10-09):\n * - `release` — a signed ROI / release;\n * - `share` — a share, which freezes the list it was sent with AND the\n * `scopeVersion` of the release it was composed under (handoff § 3: \"A\n * share freezes the list it was sent with ... and its version\"), so it\n * reads like a release: a share frozen under a v3 release is a stamp-3\n * list and retains;\n * - `policy` — everything agency-authored: a policy, a PRESET or a PARTNER\n * RULE (canon SIGNED-GRAIN: \"policies / presets / partner rules take the\n * successor whole\"), migrated with a dated version row.\n */\nexport type ScopeReadingSubject = \"release\" | \"share\" | \"policy\";\n\nexport interface ScopeReadOptions {\n subject: ScopeReadingSubject;\n}\n\n/**\n * A stored code a release or share keeps at the grain it was signed at\n * (ruling 2026-10-09): not mapped to `successor`, not in `informationScope`.\n * The builder delivers exactly `v3Fields`, read-only — never offered, never\n * widened, never narrowed — until the survivor re-signs on v4.\n *\n * Only a STAMP-3 list retains. A v4-stamped release or share can only hold\n * live v4 codes (the picker never offers a tombstone); if one nonetheless\n * names a code on a `retain` line, that code is recognised as retired and\n * includes NOTHING (fail closed) — never its successor, and not retained.\n */\nexport interface ScopeRetainedReading {\n readonly code: string;\n /** The fields the code delivered in v3 (field ids). Empty: it delivers nothing (`note`). */\n readonly v3Fields: readonly string[];\n /** Their assertion domains — CATEGORY grain in v3, the field family; deliver by `v3Fields`. */\n readonly v3Domains: readonly string[];\n /** What a policy reads it as, and what a v4 re-signature would name. */\n readonly successor: string;\n /** Present when the membership needs explaining (an empty unit; a derivation under veto). */\n readonly note?: string;\n}\n\n/**\n * The current (v4) reading of a stored list. `stored` and `storedVersion` are\n * the list as signed, copied, never rewritten (§ 3: \"a signed release keeps\n * its list as signed, at the version signed; its current reading is derived\n * through the table at read time\").\n */\nexport interface ScopeReading {\n /** The stamp as stored; `null` when it was absent or not a number. */\n readonly storedVersion: number | null;\n readonly stored: readonly string[];\n readonly version: typeof INFORMATION_SCOPE_VERSION;\n /** The stamp is not in `INFORMATION_SCOPE_READABLE_VERSIONS`: every code reads `unknown`. */\n readonly unsupportedVersion: boolean;\n /**\n * The derived v4 list: unique, in tree order. A selection reading always\n * contains `system_info`; a restriction reading contains only what it restricts.\n */\n readonly informationScope: readonly string[];\n /** One entry per distinct stored code, in stored order. */\n readonly codes: readonly ScopeCodeReading[];\n /** Stored codes that are retired (read by `row`, `subtract` or `retired before v4`). */\n readonly retired: readonly string[];\n /** Stored codes with no live row and no table line; they include nothing. */\n readonly unknown: readonly string[];\n /** Stored codes whose reading is wider than v3's (`widens`): surface, never hide. */\n readonly widened: readonly string[];\n /** `readSelection`'s subject; `null` on a restriction reading. */\n readonly subject: ScopeReadingSubject | null;\n /** Release / share codes kept at v3 grain, in stored order (always empty for a policy). */\n readonly retained: readonly ScopeRetainedReading[];\n /**\n * A policy read across versions (stamp 3) — `readSelection` with subject\n * `policy`, and every `readRestriction` (a restriction is a policy's):\n * handoff § 3 — \"a policy is migrated with a new version row on the record,\n * dated\" — so the app writes that dated row before acting on\n * `informationScope`. `false` otherwise.\n */\n readonly versionRowRequired: boolean;\n /** Says why, when `versionRowRequired`; otherwise `null`. */\n readonly note: string | null;\n}\n\nexport type ScopeShareVerdict =\n | { readonly included: true; readonly reason: \"included\" }\n | { readonly included: false; readonly reason: \"not_covered\" | \"platform_floor\" | \"unknown_code\" }\n | {\n readonly included: false;\n readonly reason: \"off_by_default\";\n /** The off-by-default rows in the chain the account has not enabled. */\n readonly notEnabled: readonly string[];\n };\n\nexport type ScopeShareReason = ScopeShareVerdict[\"reason\"];\n\nexport interface ScopeShareOptions {\n /** The off-by-default rows the account's policy has enabled for sharing (rule 4). */\n enabledOffByDefault?: ReadonlySet<string> | readonly string[];\n}\n\nexport interface CreateInformationScopeResolverInput<R extends ScopeRow> {\n rows: readonly R[];\n migrations?: readonly ScopeMigration[];\n}\n\n/** A stored list as it may arrive from storage (reads are total). */\nexport type StoredScopeList = readonly string[] | null | undefined;\n\nexport interface InformationScopeResolver<R extends ScopeRow = ScopeRow> {\n readonly version: typeof INFORMATION_SCOPE_VERSION;\n /** Every row in input order. */\n readonly rows: readonly R[];\n row(code: string): R | undefined;\n /** The live (non-retired) children of `code`, in input order (a copy). */\n childrenOf(code: string): string[];\n /** `code` first, then its parent, up to the root (a copy). Empty for an unknown code. */\n ancestorsOf(code: string): string[];\n\n /** Rules 2 + 3. */\n isCovered(selection: StoredScopeList, code: string): boolean;\n /** Rules 2–5. */\n isIncludedOnShare(selection: StoredScopeList, code: string, options?: ScopeShareOptions): boolean;\n /** `isIncludedOnShare` with the reason, for \"held back and counted\". */\n shareVerdict(\n selection: StoredScopeList,\n code: string,\n options?: ScopeShareOptions,\n ): ScopeShareVerdict;\n /** Rule 7 (the viewing side). */\n isVisibleAtLevel(level: number, code: string): boolean;\n\n /** Rules 3 + 6: the codes a picker writes when it expands `code` (its live children, rest row included). */\n expandSelectAll(code: string): string[];\n /** Rule 6: select-all at `code` (the code itself is stored; its now-redundant descendants drop). */\n selectAll(selection: readonly string[], code: string): string[];\n /** Rules 3 + 6: de-select one child; every selected ancestor is replaced by its other children. */\n deselectChild(selection: readonly string[], childCode: string): string[];\n\n /**\n * § 3: the current v4 reading of a stored selection, for its `subject`\n * (required; throws when missing or unknown). A release or share keeps a\n * `retain` code at its v3 grain (`retained`); a policy reads the successor.\n */\n readSelection(\n list: StoredScopeList,\n scopeVersion: number | null | undefined,\n options: ScopeReadOptions,\n ): ScopeReading;\n /**\n * § 3 `subtract`: the current v4 reading of a stored RESTRICTION. A\n * restriction is a policy's, so a stamp-3 one sets `versionRowRequired`.\n */\n readRestriction(list: StoredScopeList, scopeVersion: number | null | undefined): ScopeReading;\n\n /** Rule 1: the row a record is included under, given its field's home row and its subject. */\n rowForSubject(homeRow: string, kind: ScopeSubjectKind): string;\n\n /** § 7 row 6: expand every pick that sits above the ceiling's grain into its children. */\n expandBranchPickToGrain(selection: StoredScopeList, ceiling: StoredScopeList): string[];\n /** § 7 row 6: expand, then keep only what the ceiling covers. A sender can never widen. */\n clampToCeiling(selection: StoredScopeList, ceiling: StoredScopeList): string[];\n}\n\n// ─── Pure row guards ─────────────────────────────────────────────────────────\n\n/** A row a picker offers as a choice (§ 8 `selectable`; never a retired row). */\nexport const isSelectableScopeRow = (row: ScopeRow | undefined): boolean =>\n row !== undefined && row.selectable && row.status !== \"retired\";\n\n/**\n * The `category_rest` row (rule 3): it carries the facts filed on its category,\n * and is covered with it. Since canon's re-ruling of 2026-10-18 it is an ORDINARY\n * selectable row (\"Other identifying details\"); the row type is only the marker\n * the send path reads.\n */\nexport const isScopeRestRow = (row: ScopeRow | undefined): boolean =>\n row !== undefined && row.rowType === \"category_rest\";\n\n/** One of the 28 `summary_<x>` / `full_<x>` rows (§ 8 `instrument row`). */\nexport const isScopeInstrumentRow = (row: ScopeRow | undefined): boolean =>\n row !== undefined && row.rowType === \"instrument row\";\n\n// ─── Person kind (rule 1, Phase 3 D5) ───────────────────────────────────────\n\n/**\n * Which kind of other named person someone is (handoff § 2 rule 1; § 8; Phase\n * 3 D5): \"This person caused harm\" wins; \"Eligible family member\" (asserted\n * by the advocate, never derived from the relationship) otherwise; neither →\n * `others`. A person with both switches is listed under `offenders`; the\n * caller keeps the family-member VAWA handling, which rides `efmAsserted` on\n * the person, not the kind.\n */\nexport function kindForPerson(person: {\n causedHarm: boolean;\n efmAsserted: boolean;\n}): ScopePersonKind {\n if (person.causedHarm) return \"offenders\";\n if (person.efmAsserted) return \"family\";\n return \"others\";\n}\n\n// ─── The resolver ────────────────────────────────────────────────────────────\n\nconst PERSON_KINDS: ReadonlySet<string> = new Set<ScopePersonKind>([\"offenders\", \"family\", \"others\"]);\nconst SPECIAL_DATA_TYPES: ReadonlySet<string> = new Set<ScopeSpecialDataType>([\n \"none\",\n \"survivor_confidential\",\n \"criminal_intelligence\",\n \"evidence\",\n]);\nconst MIGRATION_RULES: ReadonlySet<string> = new Set<ScopeMigrationRule>([\n \"identity\",\n \"row\",\n \"category\",\n \"subtract\",\n \"retired before v4\",\n]);\nconst RETIRED_RULES: ReadonlySet<ScopeReadingRule> = new Set<ScopeReadingRule>([\n \"row\",\n \"subtract\",\n \"retired before v4\",\n]);\n\n/** Reading precedence per code (§ 3): a stated category line, then identity, row, pre-v4. */\nconst SELECTION_PRECEDENCE: readonly ScopeMigrationRule[] = [\n \"category\",\n \"identity\",\n \"row\",\n \"retired before v4\",\n];\nconst RESTRICTION_PRECEDENCE: readonly ScopeMigrationRule[] = [\n \"subtract\",\n ...SELECTION_PRECEDENCE,\n];\n\nconst READING_SUBJECTS: ReadonlySet<string> = new Set<ScopeReadingSubject>([\n \"release\",\n \"share\",\n \"policy\",\n]);\n\n/** The `note` on a policy reading across versions (handoff § 3). */\nexport const INFORMATION_SCOPE_POLICY_VERSION_ROW_NOTE =\n \"Handoff § 3: a policy is migrated with a new version row on the record, dated, so a Member \" +\n \"Admin sees a change in history, not a silent rewrite. Write that row before acting on this \" +\n \"reading; the stored list itself is never rewritten.\";\n\nconst asList = (list: StoredScopeList): readonly string[] => (Array.isArray(list) ? list : []);\n\n/**\n * Bind the resolver to one tree (and its migration table). Throws on a\n * malformed tree: a duplicate code, a parent that is not a row, a cycle, no\n * `system_info` row, a live row whose `specialDataType` is missing or not in\n * § 8 (rule 1 routes on it — absence fails closed by refusing to bind), a\n * per-kind row without a `kindRow` that names a row, an unknown migration\n * rule, a migration successor that is not a live row, two different\n * readings for the same code and rule, or a `releaseReading: \"retain\"` line\n * without exactly one successor and its `v3Fields` / `v3Domains`.\n */\nexport function createInformationScopeResolver<R extends ScopeRow>(\n input: CreateInformationScopeResolverInput<R>,\n): InformationScopeResolver<R> {\n const rows = Object.freeze([...input.rows]);\n const byCode = new Map<string, R>();\n const order = new Map<string, number>();\n for (const r of rows) {\n if (byCode.has(r.scopeCode)) {\n throw new Error(`information scope: duplicate code \"${r.scopeCode}\"`);\n }\n byCode.set(r.scopeCode, r);\n order.set(r.scopeCode, order.size);\n }\n const isLive = (code: string): boolean => {\n const r = byCode.get(code);\n return r !== undefined && r.status !== \"retired\";\n };\n const children = new Map<string, string[]>();\n for (const r of rows) {\n if (r.status !== \"retired\" && !SPECIAL_DATA_TYPES.has(r.specialDataType)) {\n throw new Error(\n `information scope: \"${r.scopeCode}\" has specialDataType ${JSON.stringify(r.specialDataType)}`,\n );\n }\n if (r.parentScopeCode === null || r.parentScopeCode === \"\") continue;\n if (!byCode.has(r.parentScopeCode)) {\n throw new Error(\n `information scope: \"${r.scopeCode}\" names unknown parent \"${r.parentScopeCode}\"`,\n );\n }\n if (r.status === \"retired\") continue;\n const list = children.get(r.parentScopeCode) ?? [];\n list.push(r.scopeCode);\n children.set(r.parentScopeCode, list);\n }\n const ancestorCache = new Map<string, readonly string[]>();\n const ancestors = (code: string): readonly string[] => {\n const hit = ancestorCache.get(code);\n if (hit) return hit;\n const out: string[] = [];\n let cur: string | null = code;\n while (cur !== null && cur !== \"\") {\n const r = byCode.get(cur);\n if (!r) break;\n if (out.includes(cur)) throw new Error(`information scope: cycle at \"${cur}\"`);\n out.push(cur);\n cur = r.parentScopeCode;\n }\n ancestorCache.set(code, out);\n return out;\n };\n for (const r of rows) ancestors(r.scopeCode);\n if (!isLive(INFORMATION_SCOPE_SYSTEM_INFO)) {\n throw new Error(`information scope: the tree has no \"${INFORMATION_SCOPE_SYSTEM_INFO}\" row`);\n }\n /** `system_info` and its ancestors (`system`): covered by every selection. */\n const alwaysCovered: ReadonlySet<string> = new Set(ancestors(INFORMATION_SCOPE_SYSTEM_INFO));\n\n const kids = (code: string): readonly string[] => children.get(code) ?? [];\n const descendantsOf = (code: string): string[] => {\n const out: string[] = [];\n const stack = [...kids(code)];\n while (stack.length > 0) {\n const c = stack.pop() as string;\n out.push(c);\n stack.push(...kids(c));\n }\n return out;\n };\n const restRowOf = (code: string): string | undefined =>\n kids(code).find((c) => isScopeRestRow(byCode.get(c)));\n\n // Rule 1 kind rows, read off the tree: each kind's `person_type` root, and\n // each per-kind row by (kind, the client row it copies).\n const kindRoot = new Map<string, string>();\n const perKindRow = new Map<string, string>();\n for (const r of rows) {\n if (r.status === \"retired\" || r.kindBranch === null || !PERSON_KINDS.has(r.kindBranch)) continue;\n if (r.rowType === \"person_type\") {\n kindRoot.set(r.kindBranch, r.scopeCode);\n continue;\n }\n if (r.kindRow === undefined || !isLive(r.kindRow)) {\n throw new Error(\n `information scope: per-kind row \"${r.scopeCode}\" has no live kindRow (${String(r.kindRow)})`,\n );\n }\n perKindRow.set(`${r.kindBranch}\\u0000${r.kindRow}`, r.scopeCode);\n }\n\n // Migration table, indexed by code then rule.\n const migrations = new Map<string, Map<ScopeMigrationRule, ScopeMigration>>();\n for (const m of input.migrations ?? []) {\n if (!MIGRATION_RULES.has(m.rule)) {\n throw new Error(`information scope: unknown migration rule \"${m.rule}\" on \"${m.from}\"`);\n }\n for (const to of m.to) {\n if (!isLive(to)) {\n throw new Error(\n `information scope: migration \"${m.from}\" (${m.rule}) reads as \"${to}\", not a live row`,\n );\n }\n }\n if (\n m.releaseReading !== undefined &&\n m.releaseReading !== \"retain\" &&\n m.releaseReading !== \"successor\"\n ) {\n throw new Error(`information scope: \"${m.from}\" has releaseReading \"${String(m.releaseReading)}\"`);\n }\n if (m.policyReading !== undefined && m.policyReading !== \"successor\") {\n throw new Error(`information scope: \"${m.from}\" has policyReading \"${String(m.policyReading)}\"`);\n }\n if (\n m.releaseReading === \"retain\" &&\n (m.to.length !== 1 || !Array.isArray(m.v3Fields) || !Array.isArray(m.v3Domains))\n ) {\n throw new Error(\n `information scope: retained line \"${m.from}\" needs one successor and its v3Fields / v3Domains`,\n );\n }\n const perCode = migrations.get(m.from) ?? new Map<ScopeMigrationRule, ScopeMigration>();\n const prior = perCode.get(m.rule);\n if (prior && prior.to.join(\" \") !== m.to.join(\" \")) {\n throw new Error(`information scope: two \"${m.rule}\" readings for \"${m.from}\"`);\n }\n // The resolver reads only `to`, `widens` and a `retain` line's v3 membership;\n // the other line fields stay on the caller's `ScopeMigration` / the SOT.\n const retain = m.releaseReading === \"retain\" ? m : prior?.releaseReading === \"retain\" ? prior : null;\n perCode.set(m.rule, {\n from: m.from,\n rule: m.rule,\n to: Object.freeze([...m.to]),\n widens: m.widens === true || prior?.widens === true,\n ...(retain === null\n ? {}\n : {\n releaseReading: \"retain\" as const,\n v3Fields: Object.freeze([...(retain.v3Fields ?? [])]),\n v3Domains: Object.freeze([...(retain.v3Domains ?? [])]),\n ...(retain.v3FieldsNote === undefined ? {} : { v3FieldsNote: retain.v3FieldsNote }),\n }),\n });\n migrations.set(m.from, perCode);\n }\n\n /**\n * Unique, tree order for known codes, unknown codes kept after in first-seen\n * order; a selection always carries `system_info` (a restriction does not).\n */\n const normalize = (codes: Iterable<string>, withSystemInfo = true): string[] => {\n const seen = new Set<string>();\n const known: string[] = [];\n const unknown: string[] = [];\n const all = withSystemInfo ? [INFORMATION_SCOPE_SYSTEM_INFO, ...codes] : [...codes];\n for (const c of all) {\n if (seen.has(c)) continue;\n seen.add(c);\n (byCode.has(c) ? known : unknown).push(c);\n }\n known.sort((a, b) => (order.get(a) as number) - (order.get(b) as number));\n return [...known, ...unknown];\n };\n\n const requirePickable = (code: string, op: string): void => {\n if (!byCode.has(code)) throw new RangeError(`information scope ${op}: unknown code \"${code}\"`);\n if (!isSelectableScopeRow(byCode.get(code))) {\n throw new RangeError(`information scope ${op}: \"${code}\" is not selectable`);\n }\n };\n\n // Rule 2 (self or any ancestor in the flat list) + rule 3 (a record homed on a\n // category is covered when the category OR its rest row is). `system_info` and\n // `system` are always covered (header).\n const isCovered = (selection: StoredScopeList, code: string): boolean => {\n if (!isLive(code)) return false;\n if (alwaysCovered.has(code)) return true;\n const sel = new Set(asList(selection));\n if (ancestors(code).some((a) => sel.has(a))) return true;\n const rest = restRowOf(code);\n return rest !== undefined && sel.has(rest);\n };\n\n const shareVerdict = (\n selection: StoredScopeList,\n code: string,\n options: ScopeShareOptions = {},\n ): ScopeShareVerdict => {\n if (!isLive(code)) return { included: false, reason: \"unknown_code\" };\n if (!isCovered(selection, code)) return { included: false, reason: \"not_covered\" };\n const chain = ancestors(code).map((c) => byCode.get(c) as R);\n // Rule 5: the floor (or a floor ancestor) never leaves, whatever the list says.\n if (chain.some((r) => r.platformFloor)) return { included: false, reason: \"platform_floor\" };\n // Rule 4: every off-by-default row in the chain must be enabled by the account\n // (the reference runner's `included`: enabling an ancestor does not enable an\n // off-by-default child of it).\n const enabled = new Set(options.enabledOffByDefault ?? []);\n const notEnabled = chain\n .filter((r) => !r.shareableDefault && !enabled.has(r.scopeCode))\n .map((r) => r.scopeCode);\n if (notEnabled.length > 0) return { included: false, reason: \"off_by_default\", notEnabled };\n return { included: true, reason: \"included\" };\n };\n\n const expandSelectAll = (code: string): string[] => {\n if (!byCode.has(code)) throw new RangeError(`information scope expand: unknown code \"${code}\"`);\n return [...kids(code)];\n };\n\n const selectAll = (selection: readonly string[], code: string): string[] => {\n requirePickable(code, \"selectAll\");\n const drop = new Set(descendantsOf(code));\n return normalize([...selection.filter((c) => !drop.has(c)), code]);\n };\n\n const deselectChild = (selection: readonly string[], childCode: string): string[] => {\n requirePickable(childCode, \"deselectChild\");\n if (alwaysCovered.has(childCode)) {\n throw new RangeError(`information scope deselectChild: \"${childCode}\" is always included`);\n }\n const sel = new Set(selection);\n const path = ancestors(childCode); // [child, parent, …, root]\n let top = 0;\n for (let i = 1; i < path.length; i += 1) if (sel.has(path[i])) top = i;\n // Replace every selected ancestor by its OTHER children, all the way down the\n // path (rule 3: the rest row is one of those children, so it is written too).\n for (let i = 1; i <= top; i += 1) {\n sel.delete(path[i]);\n for (const c of kids(path[i])) if (c !== path[i - 1]) sel.add(c);\n }\n sel.delete(childCode);\n for (const d of descendantsOf(childCode)) sel.delete(d);\n return normalize(sel);\n };\n\n const readOne = (\n from: string,\n scopeVersion: number,\n precedence: readonly ScopeMigrationRule[],\n keepsGrain: boolean,\n ): ScopeCodeReading => {\n // A v4 list names live codes as written.\n if (scopeVersion === INFORMATION_SCOPE_VERSION && isLive(from)) {\n return { from, rule: \"identity\", reads: [from], widens: false, retained: false };\n }\n // Every other code reads through the table — including a retired code in a\n // v4 list (§ 3 (c): it \"stays recognisable in stored data forever\").\n const lines = migrations.get(from);\n if (lines) {\n for (const rule of precedence) {\n if (scopeVersion === INFORMATION_SCOPE_VERSION && (rule === \"identity\" || rule === \"category\")) {\n continue; // a v4 code that is not live has no identity reading\n }\n const line = lines.get(rule);\n if (!line) continue;\n // Ruling 2026-10-09: a release / share signed at v3 keeps the v3 grain.\n if (keepsGrain && line.releaseReading === \"retain\") {\n // A v4-stamped release / share cannot legitimately hold this tombstone\n // (never offered): recognised as retired, includes nothing — never the\n // successor (see `ScopeRetainedReading`).\n return scopeVersion === 3\n ? { from, rule, reads: [], widens: false, retained: true }\n : { from, rule, reads: [], widens: false, retained: false };\n }\n return { from, rule, reads: [...line.to], widens: line.widens === true, retained: false };\n }\n }\n return { from, rule: \"unknown\", reads: [], widens: false, retained: false };\n };\n\n const retainedOf = (c: ScopeCodeReading): ScopeRetainedReading => {\n const line = migrations.get(c.from)?.get(c.rule as ScopeMigrationRule) as ScopeMigration;\n return {\n code: c.from,\n v3Fields: [...(line.v3Fields ?? [])],\n v3Domains: [...(line.v3Domains ?? [])],\n successor: line.to[0],\n ...(line.v3FieldsNote === undefined ? {} : { note: line.v3FieldsNote }),\n };\n };\n\n const read = (\n list: StoredScopeList,\n scopeVersion: number | null | undefined,\n precedence: readonly ScopeMigrationRule[],\n subject: ScopeReadingSubject | null,\n ): ScopeReading => {\n const isRestriction = subject === null;\n const keepsGrain = subject === \"release\" || subject === \"share\";\n // A restriction is a policy's (handoff § 3 `subtract`: \"a policy that forbids\n // a code\"), so it carries the same dated-version-row signal.\n const isPolicyLike = subject === \"policy\" || isRestriction;\n const stored = [...asList(list)];\n const supported =\n typeof scopeVersion === \"number\" && INFORMATION_SCOPE_READABLE_VERSIONS.includes(scopeVersion);\n const versionRowRequired =\n isPolicyLike && supported && scopeVersion !== INFORMATION_SCOPE_VERSION;\n const codes: ScopeCodeReading[] = [];\n const seen = new Set<string>();\n for (const from of stored) {\n if (seen.has(from)) continue;\n seen.add(from);\n codes.push(\n supported\n ? readOne(from, scopeVersion as number, precedence, keepsGrain)\n : { from, rule: \"unknown\", reads: [], widens: false, retained: false },\n );\n }\n return {\n storedVersion: typeof scopeVersion === \"number\" ? scopeVersion : null,\n stored,\n version: INFORMATION_SCOPE_VERSION,\n unsupportedVersion: !supported,\n informationScope: normalize(\n codes.flatMap((c) => c.reads),\n !isRestriction,\n ),\n codes,\n retired: codes.filter((c) => RETIRED_RULES.has(c.rule)).map((c) => c.from),\n unknown: codes.filter((c) => c.rule === \"unknown\").map((c) => c.from),\n widened: codes.filter((c) => c.widens).map((c) => c.from),\n subject,\n retained: codes.filter((c) => c.retained).map(retainedOf),\n versionRowRequired,\n note: versionRowRequired ? INFORMATION_SCOPE_POLICY_VERSION_ROW_NOTE : null,\n };\n };\n\n const readSelection = (\n list: StoredScopeList,\n scopeVersion: number | null | undefined,\n options: ScopeReadOptions,\n ): ScopeReading => {\n const subject = (options as Partial<ScopeReadOptions> | undefined)?.subject;\n if (subject === undefined || !READING_SUBJECTS.has(subject)) {\n throw new TypeError(\n `information scope readSelection: options.subject must be \"release\", \"share\" or \"policy\" ` +\n `(got ${JSON.stringify(subject)}) — there is no default`,\n );\n }\n return read(list, scopeVersion, SELECTION_PRECEDENCE, subject);\n };\n\n const rowForSubject = (homeRow: string, kind: ScopeSubjectKind): string => {\n const home = byCode.get(homeRow);\n if (!home) throw new RangeError(`information scope rowForSubject: unknown home \"${homeRow}\"`);\n if (kind === \"client\") return homeRow;\n const chain = ancestors(homeRow);\n // System, Notes and the LEADS groups sit under no `branch` row: the record stays home.\n if (byCode.get(chain[chain.length - 1])?.rowType !== \"branch\") return homeRow;\n // A criminal-intelligence row under the client (`derived_risk_signals`) stays home:\n // every per-kind row is survivor_confidential, so re-branching would move CI\n // content across a handling class. The reference keeps it home the same way\n // (`resolve_home` / `leads_codes`).\n if (home.specialDataType === \"criminal_intelligence\") return homeRow;\n const root = kindRoot.get(kind);\n if (!root) throw new RangeError(`information scope rowForSubject: the tree has no \"${kind}\" kind`);\n if (chain.includes(root)) return homeRow;\n // The deepest row the kind defines for the home (D15).\n for (const anc of chain) {\n const perKind = perKindRow.get(`${kind}\\u0000${anc}`);\n if (perKind !== undefined) return perKind;\n }\n return root;\n };\n\n const expandBranchPickToGrain = (\n selection: StoredScopeList,\n ceiling: StoredScopeList,\n ): string[] => {\n const ceil = asList(ceiling);\n const ceilSet = new Set(ceil);\n const isWithin = (c: string): boolean => ancestors(c).some((a) => ceilSet.has(a));\n const isAbove = (c: string): boolean => ceil.some((k) => k !== c && ancestors(k).includes(c));\n const out: string[] = [];\n const stack = [...asList(selection)];\n while (stack.length > 0) {\n const c = stack.pop() as string;\n if (isLive(c) && !isWithin(c) && isAbove(c)) stack.push(...kids(c));\n else out.push(c);\n }\n return normalize(out);\n };\n\n const clampToCeiling = (selection: StoredScopeList, ceiling: StoredScopeList): string[] => {\n const ceil = new Set(asList(ceiling));\n return normalize(\n expandBranchPickToGrain(selection, ceiling).filter(\n (c) => isLive(c) && ancestors(c).some((a) => ceil.has(a)),\n ),\n );\n };\n\n return {\n version: INFORMATION_SCOPE_VERSION,\n rows,\n row: (code) => byCode.get(code),\n childrenOf: (code) => [...kids(code)],\n ancestorsOf: (code) => [...ancestors(code)],\n isCovered,\n isIncludedOnShare: (selection, code, options) =>\n shareVerdict(selection, code, options).included,\n shareVerdict,\n // Rule 7: the lowest internal viewing level that sees the row. Level 2\n // (autocomplete) sees the level-1 stub (§ 5). Sharing ignores this.\n isVisibleAtLevel: (level, code) =>\n typeof level === \"number\" && isLive(code) && level >= (byCode.get(code) as R).levelFloor,\n expandSelectAll,\n selectAll,\n deselectChild,\n readSelection,\n readRestriction: (list, scopeVersion) => read(list, scopeVersion, RESTRICTION_PRECEDENCE, null),\n rowForSubject,\n expandBranchPickToGrain,\n clampToCeiling,\n };\n}\n","/**\n * THE ceiling coverage rule (co-2sx): ONE answer to \"does this ceiling list\n * let this v4 row leave?\", read the same way by the composer's mask\n * ({@link rowsOutsideCeiling} / {@link rowsExpandedByCeiling} /\n * {@link maskSelectionToCeiling}) and by the send door\n * ({@link rowsOverCeiling}), so the list a composer masks to is the list a\n * door accepts (pinned by a property test over every live row × generated\n * ceilings).\n *\n * A row `code` is WITHIN a ceiling list when\n * 1. it or an ANCESTOR is listed — canon's dumb read, `scopeListCovers`\n * (prototype `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7\n * L327953-L327964); or\n * 2. it carries no content of its own (below), has at least one coverage\n * child, and EVERY coverage child is within (recursively) — canon's door\n * expands a branch / kind pick to the grain the ceiling is written at\n * before clamping (`shareItemsWithinCeiling`, L328204-L328230), so a\n * ceiling naming every child of `identifying` but not `identifying`\n * permits the `identifying` pick.\n *\n * OWN CONTENT (ruling, strict rule 2): a row with fields HOMED directly on it\n * (canon's field placements, {@link INFORMATION_SCOPE_FIELD_HOME_ROWS}; a\n * per-kind row reads its `kindRow`, since rule 1 routes another person's\n * record there) and NO rest row is within ONLY when it or an ancestor is\n * listed — listing its children does not carry its own fields. Examples:\n * `instruments` (`capture.assessment*`) and `commercial_activity`. A row with\n * a rest row (`identifying` + `identifying.other`) keeps rule 2: its own\n * fields are its rest row's.\n *\n * A COVERAGE child is live, not under the platform safety floor (never\n * shared) and not System metadata (always rides). A row is LIVE when it and\n * every row on its ancestor path are non-retired; a code outside the tree, or\n * not live, is never within.\n *\n * Deliberately NOT the resolver's `isCovered`, under which a listed rest row\n * (`identifying.other`) would cover its whole category.\n *\n * `allowed`: a list (or set) of v4 row codes; `null` is NO ceiling (canon\n * `if (allowed && …)`), under which every live row is within. Any other value\n * reads as `[]` (fail closed). `effectiveCeiling` never answers `null`.\n *\n * The tree arrives as an information-scope resolver (or anything with its\n * four read methods), so this module carries no SOT and no I/O.\n */\n\nimport {\n INFORMATION_SCOPE_SYSTEM_INFO,\n type InformationScopeResolver,\n} from \"../services/informationScopeResolver.js\";\nimport { INFORMATION_SCOPE_FIELD_HOME_ROWS } from \"./starter.js\";\n\n/** What the coverage rule reads of a tree. */\nexport type SharingCeilingScope = Pick<\n InformationScopeResolver,\n \"rows\" | \"row\" | \"childrenOf\" | \"ancestorsOf\"\n>;\n\n/** A ceiling list as callers hold it; `null` = no ceiling. */\nexport type SharingCeilingAllowed = readonly string[] | ReadonlySet<string> | null;\n\ninterface TreeFacts {\n readonly isLive: (code: string) => boolean;\n readonly isSystem: (code: string) => boolean;\n readonly underFloor: (code: string) => boolean;\n readonly isCoverageRow: (code: string) => boolean;\n readonly coverageChildren: (code: string) => readonly string[];\n readonly hasOwnContent: (code: string) => boolean;\n}\n\nconst factsCache = new WeakMap<object, TreeFacts>();\n\nfunction memoize<V>(fn: (code: string) => V): (code: string) => V {\n const memo = new Map<string, V>();\n return (code) => {\n if (memo.has(code)) return memo.get(code) as V;\n const out = fn(code);\n memo.set(code, out);\n return out;\n };\n}\n\nfunction treeFacts(scope: SharingCeilingScope): TreeFacts {\n const hit = factsCache.get(scope);\n if (hit) return hit;\n const systemPath = scope.ancestorsOf(INFORMATION_SCOPE_SYSTEM_INFO);\n const systemRoot = systemPath.length > 0 ? systemPath[systemPath.length - 1] : undefined;\n const isLive = memoize(\n (code) =>\n scope.row(code) !== undefined &&\n scope.ancestorsOf(code).every((c) => scope.row(c)?.status !== \"retired\"),\n );\n const isSystem = memoize(\n (code) => systemRoot !== undefined && scope.ancestorsOf(code).includes(systemRoot),\n );\n const underFloor = memoize((code) =>\n scope.ancestorsOf(code).some((c) => scope.row(c)?.platformFloor === true),\n );\n const isCoverageRow = memoize((code) => isLive(code) && !isSystem(code) && !underFloor(code));\n const coverageChildren = memoize((code) =>\n Object.freeze(scope.childrenOf(code).filter(isCoverageRow)),\n );\n const hasOwnContent = memoize((code) => {\n const row = scope.row(code);\n if (row === undefined) return false;\n const homed =\n INFORMATION_SCOPE_FIELD_HOME_ROWS.has(code) ||\n (row.kindRow !== undefined && INFORMATION_SCOPE_FIELD_HOME_ROWS.has(row.kindRow));\n if (!homed) return false;\n // A rest row stands for the row's own fields; then rule 2 still applies.\n return !scope\n .childrenOf(code)\n .some((c) => scope.row(c)?.rowType === \"category_rest\" && isLive(c));\n });\n const facts: TreeFacts = {\n isLive,\n isSystem,\n underFloor,\n isCoverageRow,\n coverageChildren,\n hasOwnContent,\n };\n factsCache.set(scope, facts);\n return facts;\n}\n\nfunction asCeilingSet(allowed: unknown): ReadonlySet<string> | null {\n if (allowed === null) return null;\n if (allowed instanceof Set) return allowed as ReadonlySet<string>;\n if (Array.isArray(allowed)) {\n return new Set(allowed.filter((c): c is string => typeof c === \"string\"));\n }\n return new Set(); // malformed: covers nothing\n}\n\n/**\n * Does the coverage rule require `code` for its parent to be covered? Live,\n * not under the platform floor, not System metadata.\n */\nexport function isCeilingCoverageRow(scope: SharingCeilingScope, code: string): boolean {\n return treeFacts(scope).isCoverageRow(code);\n}\n\n/**\n * Does `code` carry content of its own that children-only coverage cannot\n * carry (fields homed directly on it, no rest row)? See the module header.\n */\nexport function hasOwnScopeContent(scope: SharingCeilingScope, code: string): boolean {\n return treeFacts(scope).hasOwnContent(code);\n}\n\n/**\n * The coverage of ONE ceiling list, memoised per row — build it once and ask\n * it about many rows. See the module header for the rule.\n */\nexport function ceilingCoverage(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n): (code: string) => boolean {\n const facts = treeFacts(scope);\n const set = asCeilingSet(allowed);\n const memo = new Map<string, boolean>();\n const within = (code: string): boolean => {\n const hit = memo.get(code);\n if (hit !== undefined) return hit;\n let out: boolean;\n if (!facts.isLive(code)) out = false;\n else if (set === null) out = true;\n else if (scope.ancestorsOf(code).some((c) => set.has(c))) out = true;\n else if (facts.hasOwnContent(code)) out = false;\n else {\n const kids = facts.coverageChildren(code);\n out = kids.length > 0 && kids.every(within);\n }\n memo.set(code, out);\n return out;\n };\n return within;\n}\n\n/** THE coverage rule for one row (see the module header). */\nexport function scopeRowWithinCeiling(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n code: string,\n): boolean {\n return ceilingCoverage(scope, allowed)(code);\n}\n\n/**\n * The DOOR reader: the codes of a declared list the ceiling does not let\n * leave, in list order, each once. `system_info` and every System-metadata\n * row ride regardless (canon L327974), and rows under the platform floor are\n * never included on any share, so neither is reported. A code outside the\n * tree, or not live, is reported (fail closed).\n */\nexport function rowsOverCeiling(\n scope: SharingCeilingScope,\n declared: readonly string[] | null | undefined,\n allowed: SharingCeilingAllowed,\n): string[] {\n const facts = treeFacts(scope);\n const within = ceilingCoverage(scope, allowed);\n const out: string[] = [];\n for (const code of new Set(Array.isArray(declared) ? declared : [])) {\n if (code === INFORMATION_SCOPE_SYSTEM_INFO) continue;\n if (!facts.isLive(code)) {\n out.push(code);\n continue;\n }\n if (facts.isSystem(code) || facts.underFloor(code)) continue;\n if (!within(code)) out.push(code);\n }\n return out;\n}\n\ninterface CeilingWalk {\n /** Rows wholly outside the ceiling, each at its highest such grain. */\n readonly outside: string[];\n /** Own-content rows not within that hold within rows: a pick of one is its children. */\n readonly expanded: string[];\n}\n\n/** One top-down walk of the live tree against a ceiling (System metadata skipped). */\nfunction walkCeiling(scope: SharingCeilingScope, allowed: SharingCeilingAllowed): CeilingWalk {\n const facts = treeFacts(scope);\n if (asCeilingSet(allowed) === null) return { outside: [], expanded: [] };\n const within = ceilingCoverage(scope, allowed);\n const holdsMemo = new Map<string, boolean>();\n const holdsWithin = (code: string): boolean => {\n const hit = holdsMemo.get(code);\n if (hit !== undefined) return hit;\n // Only a coverage row counts as content held beneath: a listed FLOOR row\n // (never included) does not make its parent partly permitted.\n const out = scope\n .childrenOf(code)\n .some((c) => (facts.isCoverageRow(c) && within(c)) || holdsWithin(c));\n holdsMemo.set(code, out);\n return out;\n };\n const outside: string[] = [];\n const expanded: string[] = [];\n const visit = (code: string): void => {\n if (!facts.isLive(code) || within(code)) return;\n if (!holdsWithin(code)) {\n outside.push(code);\n return;\n }\n if (facts.hasOwnContent(code)) expanded.push(code);\n for (const child of scope.childrenOf(code)) visit(child);\n };\n for (const r of scope.rows) {\n if (r.parentScopeCode !== null && r.parentScopeCode !== \"\") continue;\n if (facts.isSystem(r.scopeCode)) continue;\n visit(r.scopeCode);\n }\n return { outside, expanded };\n}\n\n/**\n * The COMPOSER-MASK reader: the rows a ceiling restricts, each at the\n * highest grain that is wholly outside it — a row not within and holding no\n * within coverage row beneath. A row that is not within but holds one that\n * is, is not restricted itself; its children are walked. System metadata is\n * never restricted. `null` (no ceiling) restricts nothing.\n */\nexport function rowsOutsideCeiling(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n): string[] {\n return walkCeiling(scope, allowed).outside;\n}\n\n/**\n * The rows with content of their own (strict rule 2) that are not within the\n * ceiling but hold rows that are: the row itself cannot be sent, so a pick of\n * it reads as a pick of its children (then masked). Top-down order.\n */\nexport function rowsExpandedByCeiling(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n): string[] {\n return walkCeiling(scope, allowed).expanded;\n}\n\n/** `system_info` first, then each code once, in order. */\nfunction withSystemInfo(codes: readonly string[]): string[] {\n return [...new Set([INFORMATION_SCOPE_SYSTEM_INFO, ...codes])];\n}\n\n/**\n * Take one row out of a selection at its own grain: drop it and everything\n * beneath it, and replace each selected ancestor by its other children, all\n * the way down the path (a category's rest row is one of those children, so\n * it is written too).\n */\nfunction subtractRow(\n scope: SharingCeilingScope,\n selection: readonly string[],\n code: string,\n): string[] {\n const path = scope.ancestorsOf(code); // code first, then up to the root\n let sel = selection.filter((c) => !scope.ancestorsOf(c).includes(code));\n for (;;) {\n const coverAt = path.findIndex((c, i) => i > 0 && sel.includes(c));\n if (coverAt === -1) break;\n sel = sel.filter((c) => c !== path[coverAt]);\n for (let i = coverAt; i >= 1; i -= 1) {\n const parent = path[i] as string;\n const onPath = path[i - 1];\n for (const child of scope.childrenOf(parent)) {\n if (child !== onPath && !sel.includes(child)) sel.push(child);\n }\n }\n }\n return sel;\n}\n\n/**\n * The COMPOSER MASK: a selection with every row the ceiling restricts taken\n * out at its own grain. First each covered own-content row the ceiling does\n * not permit ({@link rowsExpandedByCeiling}) is replaced by its children,\n * then every row wholly outside ({@link rowsOutsideCeiling}) is subtracted.\n * Only live rows survive (plus `system_info`, always first). A row within\n * the ceiling is never removed, and {@link rowsOverCeiling} accepts every\n * result.\n */\nexport function maskSelectionToCeiling(\n scope: SharingCeilingScope,\n selection: readonly string[] | null | undefined,\n allowed: SharingCeilingAllowed,\n): string[] {\n const facts = treeFacts(scope);\n const { outside, expanded } = walkCeiling(scope, allowed);\n let sel = (Array.isArray(selection) ? selection : []).filter(\n (c): c is string => typeof c === \"string\" && facts.isLive(c),\n );\n for (const code of expanded) {\n if (!scope.ancestorsOf(code).some((c) => sel.includes(c))) continue;\n sel = subtractRow(scope, sel, code);\n for (const child of scope.childrenOf(code)) if (!sel.includes(child)) sel.push(child);\n }\n for (const code of outside) sel = subtractRow(scope, sel, code);\n // Siblings put back by subtractRow / the expansion come from childrenOf,\n // which a caller's tree may populate with retired rows: keep live ones only.\n return withSystemInfo(sel.filter((c) => facts.isLive(c)));\n}\n\n// ─── Two readers of the coverage rule, lifted from Thread ───────────────────\n//\n// Lifted unchanged from Thread `@thread/shared` `sharingCeiling.ts`\n// L432-L480 @ thread develop f021be2. The one change is the tree: Thread\n// bound its own `INFORMATION_SCOPE_RESOLVER`; here the caller passes it as\n// `scope`, the first argument, like every other reader in this file (this\n// subpath carries no SOT). Thread keeps its two-argument names as wrappers\n// that bind its resolver; PAVE's twin `intersectSharingCeilingLists`\n// (pave-2.0 `packages/domain/src/sharingScopeCeiling.ts`) does the same.\n\n/**\n * The part of a ceiling a scope check reads: the v4 rows that may leave, or\n * `null` when no ceiling binds.\n */\nexport interface SharingScopeCeiling {\n readonly allowed: ReadonlySet<string> | readonly string[] | null;\n}\n\n/**\n * Whether the ceiling permits one v4 ROW — the coverage rule\n * ({@link scopeRowWithinCeiling}).\n *\n * - `null` ceiling or `allowed: null` ⇒ permitted (no ceiling binds).\n * - System metadata (any row under `system`) ⇒ permitted (GDR 5.17\n * clause 5 — provenance rides).\n * - A code outside the tree ⇒ NOT permitted (fail closed).\n */\nexport function isPermittedByCeiling(\n scope: SharingCeilingScope,\n ceiling: SharingScopeCeiling | null,\n code: string,\n): boolean {\n if (ceiling === null || ceiling.allowed === null) return true;\n if (scope.ancestorsOf(code).includes(\"system\")) {\n return true;\n }\n if (scope.row(code) === undefined) return false;\n return scopeRowWithinCeiling(scope, ceiling.allowed, code);\n}\n\n/**\n * What BOTH of two ceiling lists permit: a row of either list that is within\n * the other (the coverage rule). A composer intersects its selected\n * recipients' ceilings with this — one selection serves every recipient, so\n * the narrowest wins.\n */\nexport function intersectSharingCeilingLists(\n scope: SharingCeilingScope,\n a: ReadonlySet<string> | readonly string[],\n b: ReadonlySet<string> | readonly string[],\n): string[] {\n const left = [...a];\n const right = [...b];\n const within = (list: readonly string[], code: string): boolean =>\n scopeRowWithinCeiling(scope, list, code);\n return [\n ...new Set([\n ...left.filter((code) => within(right, code)),\n ...right.filter((code) => within(left, code)),\n ]),\n ];\n}\n","/**\n * The account's per-purpose DEFAULT share scope (C12b) — the prototype's\n * `shareDefaultScopeFor`: the v4 rows a share of one purpose carries by the\n * ACCOUNT's rule, before any recipient is named. The account's own\n * `__default__` cell for the purpose, else the platform starter's\n * `scopeByPurpose[purpose]`; `[]` when the purpose is off.\n *\n * Lifted unchanged from Thread `@thread/shared` `sharingCeiling.ts`\n * L383-L427 @ thread develop f021be2 (`accountSharePurposePolicy`), so Thread\n * and PAVE compute it once. Exported under the prototype's name\n * {@link shareDefaultScopeFor}; {@link accountSharePurposePolicy} is the same\n * function, kept so Thread's call sites do not change.\n *\n * It is the chain's `account_default` → `platform_default` tail\n * (`effectiveCeiling`, ./chain.ts) — what every recipient without a partner\n * rule is held to: the composer's and the release wizard's \"your account's\n * default for <purpose>\" preset. Canon: prototype\n * `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7 `shareEffectiveCeiling`\n * L327966-L328090 (the chain's tail L328053-L328058); the off reading is\n * clamp 1 (platform-prototype `src/data.js` @ a6f1f3a L51352-L51354).\n *\n * Pure: no mongoose, no I/O, no SOT import.\n */\n\nimport {\n SHARING_CEILING_DEFAULT_ROW_KEY,\n isSharingPurposeDisabled,\n type SharingScopeEdits,\n} from \"./chain.js\";\nimport {\n HTI_SHARE_PLATFORM_STARTER,\n type SharingPlatformStarter,\n} from \"./starter.js\";\n\n/**\n * The account's standing on ONE share purpose, before any recipient is named\n * — what the composer's purpose card shows beside each pill:\n *\n * - `off`: the purpose is switched off for the account (canon's clamp 1 —\n * the platform row's `enabled: false`, or the account's own Share\n * Purposes switch once the platform writes one; `isSharingPurposeDisabled`\n * is the package's one test). An off purpose binds `[]` at every door, so\n * the card renders it DISABLED-WITH-REASON (Terry ruling 2026-08-12:\n * policy exclusions on this surface stay visible).\n * - `accountDefault`: the v4 rows a share of that purpose carries by the\n * ACCOUNT'S rule — the `__default__` cell the account authored, else the\n * platform default (`starter.scopeByPurpose`); `[]` when off.\n *\n * `edits === null` (the store could not be read) → `[]` for every purpose,\n * fail closed, like the ceiling itself.\n */\nexport interface AccountSharePurposePolicy {\n readonly off: boolean;\n readonly accountDefault: readonly string[];\n}\n\n/** The options {@link shareDefaultScopeFor} reads. */\nexport interface ShareDefaultScopeOptions {\n readonly starter?: SharingPlatformStarter;\n /** The account's Share Purposes switches, when the platform writes them. */\n readonly purposeOverrides?: Readonly<\n Record<string, boolean | undefined>\n > | null;\n}\n\n/**\n * The account's default scope for `purpose` (see the module note). Total:\n * never throws; a non-string entry in a stored list is dropped.\n */\nexport function shareDefaultScopeFor(\n edits: SharingScopeEdits | null | undefined,\n purpose: string,\n opts: ShareDefaultScopeOptions = {},\n): AccountSharePurposePolicy {\n const off = isSharingPurposeDisabled(purpose, opts.purposeOverrides ?? null);\n if (off || edits === null || edits === undefined) {\n return { off, accountDefault: [] };\n }\n const starter = opts.starter ?? HTI_SHARE_PLATFORM_STARTER;\n const authored = (\n edits as Readonly<Record<string, Readonly<Record<string, unknown>>>>\n )[SHARING_CEILING_DEFAULT_ROW_KEY]?.[purpose];\n if (Array.isArray(authored)) {\n return {\n off,\n accountDefault: authored.filter(\n (v): v is string => typeof v === \"string\",\n ),\n };\n }\n const platform = (\n starter.scopeByPurpose as Readonly<Record<string, unknown>>\n )[purpose];\n return {\n off,\n accountDefault: Array.isArray(platform)\n ? platform.filter((v): v is string => typeof v === \"string\")\n : [],\n };\n}\n\n/**\n * Thread's name for {@link shareDefaultScopeFor} — the SAME function (not a\n * wrapper), kept so `@thread/shared` call sites do not change.\n */\nexport const accountSharePurposePolicy = shareDefaultScopeFor;\n","/**\n * THE share resolver (Kickoff 13, GDR § 5.79 \"ONE resolver per runtime\"): the\n * one pure read Thread and PAVE call to learn, for one sender (account +\n * team) × one recipient × one purpose, which POLICY governs and at which\n * level, the posture, whether the share is excluded as a whole, and which\n * information-scope categories may leave — with the sending team's own policy\n * as a CEILING, the Platform default read as the FOUR STATES, and reports\n * never blocked at the policy or partner layer. Every answer names policy ·\n * version · level (CAM invariant 17).\n *\n * Contract of record: platform-prototype `src/data.js` @ becfab4 (K13-18) —\n * - `governingPolicyFor` L54533ff: the team row, `hit()` (one policy =\n * one purpose; a policy that ANSWERS shares received never governs a\n * send), the ladder (pair row → [inside: account default for inside →\n * the platform's inside starter] → relationship → account default →\n * Platform default), `done()` (the sending team's own policy rides as a\n * ceiling on every rung's answer when it is not itself the governing one);\n * - `effectiveCeiling` L54879ff: the posture composition (L54977-L54994;\n * `POSTURE_RANK` L53645), the whole-share exclusion, which list binds\n * (K13-12, L55121-L55130) and the per-category clamps 0 · 4 · 4a · 4b · 5 ·\n * 5b · 5c · 5d · the group flip (L55140ff; 4 at L55165, 4b at L55185);\n * - `platformStarterScope` / `starterDerivedState` L53708-L53760: the\n * Platform default as the four CVC-133 states (`SHARE_STATE_KEYS` L53697,\n * `SCOPE_LOCK_LABEL` L53698);\n * - `scopeListCovers` L54696-L54706 (HANDOFF K13-14: a stored list may name\n * a category, a kind above it or a row of it — never read it with a flat\n * `indexOf`).\n * Behavioural specs: `tools/smoke/flows/one-resolver-k13.js` (A–G) and\n * `sharing-four-state-k13.js` (A–C); the test suite beside this file carries\n * their vectors.\n *\n * The `byPurpose` virtual fork (since 0.61.0; data.js `governingPolicyFor` @ aa2c63a\n * L55006-L55028, \"An authored byPurpose sub-row with no explicit attachment is the\n * ruled fork-with-one-attachment\"): when no policy is attached to the relationship\n * for the purpose but the account has AUTHORED a purpose-specific rule for the\n * partner (`partnerPurposeRule`), the governing policy is NAMED as that rule —\n * `pol-bp-<partner>-<purpose>`, level `relationship`, `virtual: true`. As in data.js\n * (`effectiveCeiling` L55376: \"The virtual byPurpose fork adds NAMING only\"), the\n * ladder names ONE policy, so the account default beneath it is not consulted for posture\n * (data.js L55391 skips a virtual policy) and its list does not bind as 5b (L55539). Whenever\n * a rule is present the posture STARTS from the rule (L55342 — `relationshipPosture` is then\n * ignored), whatever the ladder named. SCOPE under the fork is clamp 5's (L55504): the legacy\n * cell chain (`legacyCeiling`), else an EDITED account default's category list (data.js\n * projects it into `sharingScopeEdits[__default__]`, `projectScopeEdits` L55163-L55164), else\n * the Platform default's starting scope; that default's field groups (`infoScopeItems`) bind\n * too — deliberately narrower than data.js, whose 5c (L55658) drops them under the fork. When\n * the rule itself blocked, the share reads data.js's sentences (L55436-L55448); when an\n * attached policy blocked, the policy is named (a deliberate correction — data.js names the\n * rule there). A rule for `__external__` is ignored (L55333: scope-only).\n *\n * Deliberately NOT here (prototype storage artefacts or relationship-row\n * facts the caller holds): the legacy\n * `sharingPolicies` narrowing rows (#451 moved them onto cards), the partner\n * row's direction / team-scoped gates and item `restrictions`, deconfliction /\n * viewing / release / routing species. The legacy cell chain (`sharingScopeEdits`\n * → `effectiveCeiling` in chain.ts) arrives as `legacyCeiling` and is applied\n * exactly where data.js applies it (clamp 5; review M6: seeded partner rules\n * stay a ceiling even over an authored policy).\n *\n * Fail-closed conventions (this module's, stricter than canon where noted):\n * - an unknown purpose (no Platform default supplied) governs nothing —\n * `governing: null`, every category withheld, `excluded` says why (canon's\n * `governingPolicyFor` returns null and the read leaks unrestricted; the\n * prototype masks it upstream with `purposeIsLive`);\n * - a document's `infoScope: null` OR an absent `infoScope` is \"no category\n * list\" and is honoured, exactly as data.js reads it\n * (`Array.isArray(gp.policy.infoScope) ? … : null`, L54979 / L55124 —\n * the inside starter and a field-limits-only team ceiling are written\n * that way, flow G); an explicit `[]` binds an empty list (canon too);\n * a value that is present but is not a list of strings reads as `[]`\n * (stricter than canon, which reads it as no list);\n * - the account's Information Scope (clamps 4 / 4b) starts from the codebook:\n * a CVC-236 heightened category or row (`shareableDefault: false` —\n * immigration & legal status, the full instrument narratives) stays OFF\n * until the account turns it on (`accountScope.categoriesOn` / `rowsOn`),\n * exactly as data.js reads `cg ? cg.shareable : seedG.shareable` and\n * `saved4b ? saved4b.shareable : it.shareable` — a caller that passes no\n * `accountScope` gets the codebook's defaults, never everything;\n * - an assignment whose `scope` is not one of the five kinds is skipped; two live\n * documents on one cell — a store's key forbids it — resolve to the LATER one in\n * `policies` (deterministic), and a duplicated id to the later document;\n * - a tree with no System-metadata category has nothing Required by itself, and an\n * excluded share then lets nothing through at all.\n *\n * Pure: no I/O, no SOT import, copies never live references.\n */\n\nimport type { EffectiveSharingCeiling } from \"./chain.js\";\nimport type { SharingCeilingScope } from \"./coverage.js\";\nimport {\n HTI_SHARE_PLATFORM_STARTER,\n type SharingPlatformStarter,\n} from \"./starter.js\";\n\n// ─── Vocabulary ──────────────────────────────────────────────────────────────\n\n/** The purposes that are REPORTS (data.js `REPORTING_PURPOSES`, L53354) — derived from the purpose, never a caller flag. */\nexport const SHARE_REPORTING_PURPOSES: ReadonlySet<string> = new Set([\n \"mandatory_reporting\",\n \"authority_reporting\",\n]);\n\nexport type SharePosture = \"open\" | \"approval\" | \"blocked\";\n\n/** data.js `POSTURE_RANK` L53645 — stricter is higher; a policy can only RAISE the posture. */\nexport const SHARE_POSTURE_RANK: Readonly<Record<SharePosture, number>> =\n Object.freeze({\n open: 0,\n approval: 1,\n blocked: 2,\n });\n\n/** The four states of the Platform default (CVC-133 keys; data.js `SHARE_STATE_KEYS` L53697). */\nexport type SharePlatformState =\n \"always\" | \"default_on\" | \"default_off\" | \"never\";\n\n/** The words a person reads for each state (data.js `SCOPE_LOCK_LABEL` L53698). */\nexport const SHARE_PLATFORM_STATE_LABEL: Readonly<\n Record<SharePlatformState, string>\n> = Object.freeze({\n always: \"Required\",\n default_on: \"Default On\",\n default_off: \"Default Off\",\n never: \"Blocked\",\n});\n\n/** Where on the ladder the governing policy was found (data.js `ATTACH_LEVEL_LABEL` keys, L53646ff). */\nexport type ShareLevel =\n | \"team_row\"\n | \"account_internal\"\n | \"inside_starter\"\n | \"relationship\"\n | \"agency_default\"\n | \"platform_starter\";\n\nexport const SHARE_LEVEL_LABEL: Readonly<Record<ShareLevel | \"team\", string>> =\n Object.freeze({\n team_row: \"attached on the team-to-team row\",\n relationship: \"attached to this relationship\",\n agency_default: \"your account's default for this purpose\",\n account_internal:\n \"your account's default for sharing between its own teams\",\n team: \"your account's rule for this team\",\n platform_starter: \"Platform default\",\n inside_starter: \"the platform's default for sharing inside your account\",\n });\n\n// ─── Inputs ──────────────────────────────────────────────────────────────────\n\n/** One link of a policy to where it governs — a Relationship record (K13-3; data.js L53577-L53587). */\nexport type SharePolicyAssignment =\n | { readonly scope: \"account\" }\n | { readonly scope: \"account_internal\" }\n | { readonly scope: \"account_partner\"; readonly partnerId: string }\n | { readonly scope: \"team\"; readonly teamId: string }\n | {\n readonly scope: \"team_pair\";\n readonly teamRowId: string;\n readonly teamId?: string;\n readonly partnerId?: string | null;\n /**\n * The other end of the row, as the Admin Hub stores it on the link\n * (data.js `policyRecord`): `{ type: \"team\", id }` names a receiving\n * team — one of the account's own (no `partnerId`) or the partner's.\n * The ladder does not read it (the row decides); `fireShareEvent` does.\n */\n readonly with?: {\n readonly type?: string;\n readonly id?: string;\n } | null;\n };\n\n/** A policy document as the Admin Hub stores it (data.js `policyRecord` L53540ff). */\nexport interface SharePolicyDoc {\n readonly id: string;\n readonly familyId?: string;\n /** Un-ledgered = v1 (`parseInt(p.version, 10) || 1`). */\n readonly version?: number | string;\n readonly name?: string;\n /** ONE CVC-84 purpose (invariant 3). */\n readonly purpose: string;\n readonly species?: string;\n readonly posture?: SharePosture | null;\n readonly narrowOnly?: boolean;\n /** v4 codes (categories, kinds, rows). `null` = no category list (no restriction at category grain). */\n readonly infoScope?: readonly string[] | null;\n /** Field-group grain: category → the rows of it that may leave (K13-5c). */\n readonly infoScopeItems?: Readonly<Record<string, readonly string[]>> | null;\n readonly assignments?: readonly SharePolicyAssignment[];\n readonly origin?: {\n readonly kind?: string;\n readonly parentId?: string;\n } | null;\n /** `false` = still synced to the Platform default (K13-11): its list does not bind, the default's does. */\n readonly edited?: boolean;\n /** `false` = retired: never governs. */\n readonly active?: boolean;\n /**\n * `answers: \"received\"` (K13-9b): a share-back policy never governs a share you start.\n * `on` (K13-9a): the CVC-285 event names a LISTENER fires on — read by\n * `fireShareEvent`, never by the ladder.\n */\n readonly trigger?: {\n readonly answers?: string;\n readonly on?: readonly string[];\n } | null;\n /** CVC-85 cadences the policy grants; `ongoing` + a trigger makes it a listener (K13-9a). */\n readonly cadences?: {\n readonly ongoing?: boolean;\n readonly automatic?: boolean;\n } | null;\n}\n\n/** The Platform default for one purpose, as the four states (data.js `platformStarterScope` L53719ff). */\nexport interface SharePlatformDefault {\n readonly purpose: string;\n /** The versioned tier document `pol-starter-<purpose>` (un-ledgered = 1). */\n readonly version: number;\n /** The STARTING scope — the lists `raw` as data.js keeps it: Required categories and `system` included, Blocked ones out. */\n readonly raw: readonly string[];\n /** category → state. */\n readonly states: Readonly<Record<string, SharePlatformState>>;\n /** Categories whose state is `always` (`system` not listed). */\n readonly required: readonly string[];\n /** Categories whose state is `never`. */\n readonly blocked: readonly string[];\n readonly edited?: boolean;\n}\n\nexport type ShareRecipient =\n | { readonly kind: \"partner\"; readonly id: string }\n | { readonly kind: \"external\" }\n | { readonly kind: \"sibling_team\"; readonly teamId: string };\n\nexport interface ShareResolveInput {\n /** The v4 tree (an information-scope resolver, or anything with its four read methods). */\n readonly scope: SharingCeilingScope;\n /** Every policy document of the SENDING account (retired ones are skipped). */\n readonly policies: readonly SharePolicyDoc[];\n /** The Platform default for `purpose`; `null` = the purpose is unknown to the platform (fails closed). */\n readonly platformDefault: SharePlatformDefault | null;\n /** The sender: the account and, when the share is a team's, its team (`null` = a team-blind read: no pair row, no ceiling). */\n /**\n * The sender: its team when the share is a team's (`null` = a team-blind read: no pair row, no\n * ceiling — the account's answer, not a team's). `accountId` is informational: `policies` must\n * already be the SENDING account's documents (the resolver does not filter by account).\n */\n readonly sender: {\n readonly accountId?: string;\n readonly teamId: string | null;\n };\n /** The purpose's label for the Platform-default document names people read (`purpose` when absent). */\n readonly purposeLabel?: string;\n readonly recipient: ShareRecipient;\n readonly purpose: string;\n /** The matched team-to-team row (`matchTeamRow`), when the sender's team has one for this recipient. */\n readonly teamRowId?: string | null;\n /** Clamp 1: the purpose is switched off for the account (`isSharingPurposeDisabled` in chain.ts). Blocks reports too (flow M1). */\n readonly purposeOff?: boolean;\n /**\n * The partner row's own posture, which a policy can only raise (data.js `effectiveCeiling`). Default `open`.\n * IGNORED when a `partnerPurposeRule` is present: the posture then starts from the rule\n * (data.js L55342: `bp.sharingPosture || over.sharingPosture || …` — the rule first).\n */\n readonly relationshipPosture?: SharePosture | null;\n /**\n * The account's AUTHORED purpose-specific rule for this partner and purpose — data.js\n * `policies.partnerOverrides[partner].byPurpose[purpose]` when it carries a `sharingPosture`\n * (the Share Partners \"purpose-specific rule\"). When no policy is attached to the relationship\n * for the purpose, the answer NAMES it as the governing policy (the virtual fork\n * `pol-bp-<partner>-<purpose>`, \"<purpose label> — <partner name> variant\", level\n * `relationship`, `virtual: true`; data.js `governingPolicyFor` L55006-L55028).\n * - Posture: STARTS from `posture` whenever a rule is present, whatever the ladder named\n * (L55342; `relationshipPosture` is ignored); policies and the team ceiling can only raise\n * it. Under the fork the account default is not consulted for posture (L55391).\n * - Scope under the fork: clamp 5 (L55504) — `legacyCeiling` (a rule's category list, if the\n * caller still carries one, goes there), else an EDITED account default's list (data.js's\n * projected `sharingScopeEdits[__default__]`, L55163-L55164), else the Platform default's\n * starting scope; the default's list does not bind as 5b (L55539). The edited default's\n * field groups (`infoScopeItems`) still bind — deliberately narrower than data.js (L55658).\n * - When the rule itself blocked: \"Partner is blocked for this purpose by your account's\n * sharing policy\" (L55447-L55448), or for a report the carve-out \"Partner is blocked for\n * ordinary sharing — reachable for reports\" (L55436-L55446). When a policy blocked, the\n * policy is named (deliberate correction: data.js names the rule even when it is open).\n * Ignored inside the account and for an `__external__` recipient (L55333: scope-only); not\n * named as the fork when a pair row or a relationship policy governs or for an unknown\n * purpose; a `posture` that is not open / approval / blocked is no rule. `null` / absent = no\n * rule (the answer is the one 0.60.0 gave).\n */\n readonly partnerPurposeRule?: {\n readonly posture: SharePosture;\n /** The partner's display name for the fork's name (the recipient id when absent). */\n readonly partnerName?: string | null;\n } | null;\n /**\n * The legacy cell chain for callers still carrying `sharingScopeEdits`: pass `effectiveCeiling(...)`'s\n * ANSWER (its `platform_default` rung is then ignored — the resolver reads that document itself;\n * K13-12), or a plain list that binds as given; `null` / absent = none.\n */\n readonly legacyCeiling?: readonly string[] | EffectiveSharingCeiling | null;\n /**\n * The account's Information Scope (clamp 4 / 4b) as EXPLICIT choices over the codebook's\n * defaults: `categoriesOff` / `rowsOff` = switched off; `categoriesOn` / `rowsOn` = a heightened\n * (`shareableDefault: false`, CVC-236) category or row the account has turned ON. A code in\n * neither list reads the codebook default — so heightened information stays off when this is\n * absent (data.js `effectiveCeiling` clamps 4 / 4b). A code in both lists is off.\n */\n readonly accountScope?: {\n readonly categoriesOff?: readonly string[];\n readonly rowsOff?: readonly string[];\n readonly categoriesOn?: readonly string[];\n readonly rowsOn?: readonly string[];\n } | null;\n}\n\n// ─── Output ──────────────────────────────────────────────────────────────────\n\nexport interface ShareNamedPolicy {\n readonly id: string;\n readonly familyId: string;\n readonly name: string;\n readonly version: number;\n readonly level: ShareLevel | \"team\";\n readonly levelLabel: string;\n readonly posture: SharePosture | null;\n readonly infoScope: string[] | null;\n /** Field-group grain, when the document carries it (a copy). */\n readonly infoScopeItems: Record<string, string[]> | null;\n readonly edited: boolean;\n readonly origin: string | null;\n readonly rulePath: string;\n /**\n * `true` only on the virtual `byPurpose` fork (`partnerPurposeRule`): a NAME for the authored\n * purpose-specific rule, not a stored document — it binds nothing itself.\n */\n readonly virtual?: true;\n}\n\nexport interface ShareCategoryEntry {\n readonly allowed: boolean;\n readonly reason: string;\n readonly rulePath: string;\n /** Set when the Platform default marks the category Required (`always`): nothing account-grain removes it. */\n readonly platformRequired: { readonly rulePath: string } | null;\n /** Rows under the platform safety floor — never leave. */\n readonly floorItems: string[];\n /**\n * Rows the governing list / the account's heightened toggles / the ceiling leave out. A code is\n * withheld when it OR AN ANCESTOR is listed here. Since 0.42.1 a grouping is listed only when\n * nothing beneath it is covered — when a list names some of its rows, the grouping is NOT listed\n * and its uncovered rows are listed one by one instead. So a grouping code's absence here does\n * not mean the whole grouping may leave: for a send decision read `shareRowCeiling` +\n * `rowsOverCeiling`, never a grouping-code check against `excludedItems` alone.\n */\n readonly excludedItems: string[];\n readonly excludedReason: string | null;\n /** Rows the sending team's own policy leaves out (5d). Same shape and same caveat as `excludedItems`. */\n readonly teamExcludedItems: string[];\n readonly teamExcludedReason: string | null;\n}\n\nexport interface ShareResolution {\n /** `false` = the share as a whole is excluded (`excluded` says why). */\n readonly allowed: boolean;\n readonly posture: SharePosture;\n readonly postureSource: \"relationship\" | \"policy\" | \"team_ceiling\";\n readonly excluded: {\n readonly reason: string;\n readonly rulePath: string;\n } | null;\n /** A reporting purpose under a `blocked` posture: never excluded; the note names what blocks ordinary sharing. */\n readonly reportCarveOut: {\n readonly note: string;\n readonly rulePath: string;\n } | null;\n /** The policy that governs; `null` only for an unknown purpose (fails closed). */\n readonly governing: ShareNamedPolicy | null;\n /** The sending team's own policy for the purpose, when it is not itself the governing one. */\n readonly teamCeiling: ShareNamedPolicy | null;\n /** A share to a sibling team of the same account. */\n readonly inside: boolean;\n /** Every live category of the tree, in tree order. */\n readonly scope: Readonly<Record<string, ShareCategoryEntry>>;\n /** The categories with `allowed === true`, tree order — the list the coverage readers take. */\n readonly allowedCategories: string[];\n readonly rulePath: string;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nconst own = <V>(record: unknown, key: string): V | undefined =>\n record !== null &&\n typeof record === \"object\" &&\n Object.prototype.hasOwnProperty.call(record, key)\n ? ((record as Record<string, V>)[key] as V)\n : undefined;\n\nconst isStringList = (v: unknown): v is readonly string[] =>\n Array.isArray(v) && v.every((c) => typeof c === \"string\");\n\nconst versionOf = (v: unknown): number => {\n const n = typeof v === \"number\" ? v : parseInt(String(v), 10);\n return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 1;\n};\n\n/**\n * `infoScope` as the resolver reads it: `null` or absent = no list (data.js reads every\n * non-array as \"no list\", L54979 / L55124); a list of strings = that list (`[]` binds an empty\n * list, as in canon); any other present value = `[]` (fail closed; stricter than canon).\n */\nconst docList = (v: unknown): string[] | null =>\n v === null || v === undefined ? null : isStringList(v) ? [...v] : [];\n\n/**\n * data.js `scopeListCovers` (L54696-L54706), on the v4 tree: a non-array list\n * covers everything; a category is covered when the list names it or an\n * ANCESTOR (a kind such as `family`, a branch); with a row `it`, the row is\n * covered when it or an ancestor is named; without one, a category is also\n * covered when the list names any DESCENDANT of it (a row or grouping).\n */\nexport function scopeListCovers(\n scope: SharingCeilingScope,\n list: readonly string[] | null | undefined,\n categoryCode: string,\n rowCode?: string,\n): boolean {\n if (!Array.isArray(list)) return true;\n const set = new Set(list);\n if (scope.ancestorsOf(categoryCode).some((c) => set.has(c))) return true;\n if (rowCode !== undefined)\n return scope.ancestorsOf(rowCode).some((c) => set.has(c));\n return list.some((id) =>\n scope.ancestorsOf(id).slice(1).includes(categoryCode),\n );\n}\n\n/** `scopeStrictCovers` (L54710ff): the list names the category or an ancestor — never a descendant. */\nexport function scopeListStrictlyCovers(\n scope: SharingCeilingScope,\n list: readonly string[] | null | undefined,\n categoryCode: string,\n): boolean {\n if (!Array.isArray(list)) return true;\n const set = new Set(list);\n return scope.ancestorsOf(categoryCode).some((c) => set.has(c));\n}\n\n/** The attachment index the ladder reads (data.js `effectiveAttachmentIndex` L53558ff), built from `assignments` only. */\nexport interface ShareAttachmentIndex {\n readonly agencyDefaults: Readonly<Record<string, string>>;\n readonly internalDefaults: Readonly<Record<string, string>>;\n readonly relationships: Readonly<\n Record<string, Readonly<Record<string, string>>>\n >;\n readonly teamRows: Readonly<Record<string, Readonly<Record<string, string>>>>;\n readonly teams: Readonly<Record<string, Readonly<Record<string, string>>>>;\n}\n\nconst isLiveDoc = (p: SharePolicyDoc | null | undefined): p is SharePolicyDoc =>\n p !== null &&\n typeof p === \"object\" &&\n typeof p.id === \"string\" &&\n p.id !== \"\" &&\n typeof p.purpose === \"string\" &&\n p.active !== false;\n\nexport function attachmentIndexFromPolicies(\n policies: readonly SharePolicyDoc[] | null | undefined,\n): ShareAttachmentIndex {\n // Null-prototype maps: a key such as `__proto__` is a key, never the prototype. Two live\n // documents on one cell: the LATER one in `policies` wins (deterministic; a store's key forbids it).\n const nullMap = <V>(): Record<string, V> =>\n Object.create(null) as Record<string, V>;\n const agencyDefaults = nullMap<string>();\n const internalDefaults = nullMap<string>();\n const relationships = nullMap<Record<string, string>>();\n const teamRows = nullMap<Record<string, string>>();\n const teams = nullMap<Record<string, string>>();\n const put = (\n map: Record<string, Record<string, string>>,\n key: string,\n purpose: string,\n id: string,\n ): void => {\n const row = Object.prototype.hasOwnProperty.call(map, key)\n ? map[key]\n : (map[key] = nullMap<string>());\n row[purpose] = id;\n };\n for (const p of Array.isArray(policies) ? policies : []) {\n if (!isLiveDoc(p)) continue;\n for (const a of Array.isArray(p.assignments) ? p.assignments : []) {\n if (a === null || typeof a !== \"object\") continue;\n switch (a.scope) {\n case \"account\":\n agencyDefaults[p.purpose] = p.id;\n break;\n case \"account_internal\":\n internalDefaults[p.purpose] = p.id;\n break;\n case \"account_partner\":\n if (typeof a.partnerId === \"string\" && a.partnerId !== \"\")\n put(relationships, a.partnerId, p.purpose, p.id);\n break;\n case \"team\":\n if (typeof a.teamId === \"string\" && a.teamId !== \"\")\n put(teams, a.teamId, p.purpose, p.id);\n break;\n case \"team_pair\":\n if (typeof a.teamRowId === \"string\" && a.teamRowId !== \"\")\n put(teamRows, a.teamRowId, p.purpose, p.id);\n break;\n default:\n break; // an unknown scope governs nowhere\n }\n }\n }\n return { agencyDefaults, internalDefaults, relationships, teamRows, teams };\n}\n\n/** A team-to-team row as the account stores it (data.js `teamRows` / `teamPairs`, L53493-L53514). */\nexport interface ShareTeamRowLike {\n readonly id: string;\n readonly myTeamId?: string | null;\n readonly their?: { readonly type?: string; readonly id?: string } | null;\n}\n\n/**\n * The row the first rung reads (data.js `internalPairRow` / `partnerTeamRow`,\n * L53493-L53514). `rows` is ONE store, as the prototype keeps them: for a\n * sibling team, the account's internal pairs (`policies.teamPairs`); for a\n * partner, THAT partner's team rows (`partnerOverrides[partner].teamRows`, or\n * the seeded rows) — never a flat list across partners. A sibling team's row\n * is the one whose `their` is that team (direction matters — the sender\n * first); a partner's row under a team-scoped relationship is the team's\n * FIRST row, under an all-teams relationship the row whose `their` is absent,\n * not a team, or this very partner. Rows that carry only share-back\n * (answers-received) policies are dropped first. An external recipient has\n * no row.\n */\nexport function matchTeamRow(\n rows: readonly ShareTeamRowLike[] | null | undefined,\n teamId: string | null | undefined,\n recipient: ShareRecipient,\n options: {\n readonly scopeMode?: \"team_scoped\" | \"all_teams\";\n readonly shareBackOnlyRowIds?: readonly string[];\n } = {},\n): string | null {\n if (typeof teamId !== \"string\" || teamId === \"\" || !Array.isArray(rows))\n return null;\n const drop = new Set(options.shareBackOnlyRowIds ?? []);\n const live = rows.filter(\n (r): r is ShareTeamRowLike =>\n r !== null &&\n typeof r === \"object\" &&\n typeof r.id === \"string\" &&\n !drop.has(r.id),\n );\n if (recipient.kind === \"sibling_team\") {\n // data.js `internalPairRow` (L53509-L53514): every row of the internal-pairs store is a\n // team-to-team row (`teamRowIndex` L53481 types it `team`), so it matches on `their.id`\n // alone — a stored pair row without `their.type` still governs.\n return (\n live.find(\n (r) => r.myTeamId === teamId && r.their?.id === recipient.teamId,\n )?.id ?? null\n );\n }\n if (recipient.kind === \"external\") return null;\n if (options.scopeMode === \"team_scoped\")\n return live.find((r) => r.myTeamId === teamId)?.id ?? null;\n return (\n live.find(\n (r) =>\n r.myTeamId === teamId &&\n (!r.their || r.their.type !== \"team\" || r.their.id === recipient.id),\n )?.id ?? null\n );\n}\n\n// ─── The four states ─────────────────────────────────────────────────────────\n\n/**\n * Derive one purpose's Platform default as the four states (data.js\n * `starterDerivedState` L53708 + `platformStarterScope` L53719ff),\n * for every live CATEGORY of the tree, in this order — the first rule wins:\n * System metadata → `always`; a category the platform requires for the\n * purpose → `always`; off-by-default (heightened) → `never`; the seed list\n * covers it (itself, an ancestor, or any row of it) → `default_on`, else\n * `default_off`. An explicit bound overrides it for every category but\n * `system`. `raw` is the starting scope: the seed's codes whose category is\n * not Blocked or bound off, plus every bound-on and Required category, plus\n * `system`.\n */\nexport function derivePlatformDefault(\n scope: SharingCeilingScope,\n purpose: string,\n seedList: readonly string[] | null | undefined,\n options: {\n readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;\n readonly required?: readonly string[] | null;\n readonly version?: number | string;\n readonly edited?: boolean;\n } = {},\n): SharePlatformDefault {\n const seed = isStringList(seedList) ? [...seedList] : [];\n const req = new Set(options.required ?? []);\n const states: Record<string, SharePlatformState> = {};\n const required: string[] = [];\n const blocked: string[] = [];\n const systemCode = systemCategoryOf(scope);\n for (const g of liveCategories(scope)) {\n let state: SharePlatformState;\n if (g === systemCode) state = \"always\";\n else if (req.has(g)) state = \"always\";\n else if (scope.row(g)?.shareableDefault === false) state = \"never\";\n else state = scopeListCovers(scope, seed, g) ? \"default_on\" : \"default_off\";\n const bound = own<unknown>(options.bounds, g);\n if (\n g !== systemCode &&\n (bound === \"always\" ||\n bound === \"default_on\" ||\n bound === \"default_off\" ||\n bound === \"never\")\n )\n state = bound;\n states[g] = state;\n if (state === \"always\" && g !== systemCode) required.push(g);\n if (state === \"never\") blocked.push(g);\n }\n const categoryOf = (code: string): string | undefined =>\n scope.ancestorsOf(code).find((c) => scope.row(c)?.rowType === \"category\");\n const raw: string[] = [];\n const push = (c: string): void => {\n if (!raw.includes(c)) raw.push(c);\n };\n for (const code of seed) {\n const g = categoryOf(code);\n if (g === undefined) {\n // A kind or a branch: it stands for its categories — keep the ones that are on, by name,\n // so a category bound off beneath it is not covered by the kind (review r1 #4).\n for (const [cat, st] of Object.entries(states)) {\n if (\n (st === \"always\" || st === \"default_on\") &&\n scope.ancestorsOf(cat).includes(code)\n )\n push(cat);\n }\n continue;\n }\n const st = states[g];\n if (st === \"never\" || st === \"default_off\") continue;\n push(code);\n }\n for (const [g, st] of Object.entries(states)) {\n if (\n (st === \"always\" || st === \"default_on\") &&\n !scopeListCovers(scope, raw, g)\n )\n push(g);\n }\n if (systemCode !== undefined) push(systemCode);\n return {\n purpose,\n version: versionOf(options.version),\n raw,\n states,\n required,\n blocked,\n edited: options.edited === true,\n };\n}\n\n// ─── Tree reads ──────────────────────────────────────────────────────────────\n\nconst treeCache = new WeakMap<\n object,\n {\n categories: string[];\n system: string | undefined;\n leaves: Map<string, string[]>;\n descendants: Map<string, string[]>;\n }\n>();\n\nfunction treeIndex(scope: SharingCeilingScope) {\n const hit = treeCache.get(scope);\n if (hit) return hit;\n const live = (code: string): boolean =>\n scope.row(code) !== undefined &&\n scope.ancestorsOf(code).every((c) => scope.row(c)?.status !== \"retired\");\n const categories = scope.rows\n .filter((r) => r.rowType === \"category\" && live(r.scopeCode))\n .map((r) => r.scopeCode);\n const systemInfoPath =\n scope.row(\"system_info\") !== undefined\n ? scope.ancestorsOf(\"system_info\")\n : [];\n const system =\n systemInfoPath.find((c) => categories.includes(c)) ??\n categories.find((g) => g === \"system\");\n const descendants = new Map<string, string[]>();\n const leaves = new Map<string, string[]>();\n for (const g of categories) {\n const all: string[] = [];\n const walk = (code: string): void => {\n for (const c of scope.childrenOf(code)) {\n if (!live(c)) continue;\n all.push(c);\n walk(c);\n }\n };\n walk(g);\n descendants.set(g, all);\n leaves.set(\n g,\n all.filter((c) => !scope.childrenOf(c).some(live)),\n );\n }\n const out = { categories, system, leaves, descendants };\n treeCache.set(scope, out);\n return out;\n}\n\n/** The live categories of the tree, in tree order. */\nexport function liveCategories(scope: SharingCeilingScope): string[] {\n return [...treeIndex(scope).categories];\n}\n\n/** The System-metadata category (`system`, the parent of `system_info`). */\nexport function systemCategoryOf(\n scope: SharingCeilingScope,\n): string | undefined {\n return treeIndex(scope).system;\n}\n\n/**\n * The legacy cell chain's list as clamp 5 reads it: a plain list binds as given; an\n * `effectiveCeiling` answer binds only when an ACCOUNT rule answered (`partner_rule`,\n * `seeded_partner_rule`, `account_default`) — its `platform_default` rung is the same document\n * the resolver already reads as the Platform default (passing it as a legacy list would clamp\n * every authored policy to the starter and undo K13-12), and `purpose_disabled` / `none` are\n * carried by `purposeOff` / the missing Platform default.\n */\nfunction legacyCeilingList(\n v: ShareResolveInput[\"legacyCeiling\"],\n): string[] | null {\n if (v === null || v === undefined) return null;\n if (isStringList(v)) return [...v];\n if (typeof v === \"object\" && \"rung\" in v) {\n const r = (v as EffectiveSharingCeiling).rung;\n if (\n r === \"partner_rule\" ||\n r === \"seeded_partner_rule\" ||\n r === \"account_default\"\n ) {\n return isStringList(v.allowed) ? [...v.allowed] : [];\n }\n return null;\n }\n return null;\n}\n\n/**\n * The categories the platform REQUIRES for a purpose (data.js `scopeRequiredByPurpose`,\n * L40836-L40839): Identifying information on every report. Read by `platformDefaultFor`.\n */\nexport const HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE: Readonly<\n Record<string, readonly string[]>\n> = Object.freeze({\n mandatory_reporting: Object.freeze([\"identifying\"]),\n authority_reporting: Object.freeze([\"identifying\"]),\n});\n\n/**\n * The Platform default for one purpose from the PUBLISHED starter (the day-one tier document,\n * version 1, no bounds): `derivePlatformDefault` over `HTI_SHARE_PLATFORM_STARTER.scopeByPurpose`\n * and {@link HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE}. `null` for a purpose the starter has no row\n * for (the resolver then fails closed). Once the platform stores `pol-starter-<purpose>` as a\n * versioned document, pass ITS list, bounds and version instead.\n */\nexport function platformDefaultFor(\n scope: SharingCeilingScope,\n purpose: string,\n options: {\n readonly starter?: SharingPlatformStarter;\n readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;\n readonly version?: number | string;\n readonly edited?: boolean;\n } = {},\n): SharePlatformDefault | null {\n const starter = options.starter ?? HTI_SHARE_PLATFORM_STARTER;\n const seed = own<readonly string[]>(starter.scopeByPurpose, purpose);\n if (!isStringList(seed)) return null;\n return derivePlatformDefault(scope, purpose, seed, {\n required:\n own<readonly string[]>(HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE, purpose) ??\n [],\n bounds: options.bounds ?? null,\n version: options.version ?? 1,\n edited: options.edited === true,\n });\n}\n\n/**\n * The ROW-grain ceiling one resolution amounts to — the list the item-grain readers take\n * (`maskSelectionToCeiling` for the composer, `rowsOverCeiling` for the send door): each\n * allowed category by its own code when no row of it is withheld, else its live rows minus\n * the withheld ones (the governing list's, the account's heightened rows, the field-group\n * limits, the team's). Rows under the platform floor are never listed (the readers never let\n * them through). `[]` for an excluded share — only System metadata rides.\n */\nexport function shareRowCeiling(\n resolution: Pick<ShareResolution, \"allowed\" | \"scope\" | \"allowedCategories\">,\n scope: SharingCeilingScope,\n): string[] {\n if (!resolution.allowed) return [];\n const out: string[] = [];\n for (const g of resolution.allowedCategories) {\n const e = own<ShareCategoryEntry>(resolution.scope, g);\n if (e === undefined) continue;\n const withheld = new Set([\n ...e.excludedItems,\n ...e.teamExcludedItems,\n ...e.floorItems,\n ]);\n if (withheld.size === 0) {\n out.push(g);\n continue;\n }\n // walk down from the category: a row stands at its own grain when nothing beneath it is\n // withheld; else its surviving children stand in for it; a withheld row (and all beneath)\n // is dropped — so `instrument_full` with every full row off is not listed at all.\n const live = (c: string): boolean =>\n scope.row(c) !== undefined &&\n scope.ancestorsOf(c).every((a) => scope.row(a)?.status !== \"retired\");\n const anyWithheldBeneath = (c: string): boolean =>\n scope\n .childrenOf(c)\n .some((k) => live(k) && (withheld.has(k) || anyWithheldBeneath(k)));\n const visit = (c: string): void => {\n if (withheld.has(c) || !live(c)) return;\n if (!anyWithheldBeneath(c)) {\n out.push(c);\n return;\n }\n for (const k of scope.childrenOf(c)) visit(k);\n };\n for (const k of scope.childrenOf(g)) visit(k);\n }\n return out;\n}\n\n// ─── The resolver ────────────────────────────────────────────────────────────\n\ninterface Hit {\n readonly policy: SharePolicyDoc;\n readonly level: ShareLevel | \"team\";\n readonly version: number;\n readonly rulePath: string;\n}\n\nfunction named(h: Hit): ShareNamedPolicy {\n const p = h.policy;\n return {\n id: p.id,\n familyId:\n typeof p.familyId === \"string\" && p.familyId !== \"\" ? p.familyId : p.id,\n name: typeof p.name === \"string\" ? p.name : p.id,\n version: h.version,\n level: h.level,\n levelLabel: SHARE_LEVEL_LABEL[h.level],\n posture:\n p.posture === \"open\" ||\n p.posture === \"approval\" ||\n p.posture === \"blocked\"\n ? p.posture\n : null,\n infoScope: docList(p.infoScope),\n infoScopeItems: copyItems(p.infoScopeItems),\n edited: p.edited === true,\n origin: typeof p.origin?.kind === \"string\" ? p.origin.kind : null,\n rulePath: h.rulePath,\n };\n}\n\nconst uniq = (list: readonly string[]): string[] => [...new Set(list)];\n\nconst copyItems = (v: unknown): Record<string, string[]> | null => {\n if (v === null || typeof v !== \"object\") return null;\n const out: Record<string, string[]> = {};\n for (const [k, rows] of Object.entries(v as Record<string, unknown>)) {\n if (isStringList(rows)) out[k] = [...rows];\n }\n return out;\n};\n\n/**\n * THE read. See the module header; the algorithm, step by step:\n * 1. the ladder (`governingPolicyFor`): pair row → [inside: the account's\n * inside default → the platform's inside starter, stop] → relationship\n * (the partner id, or `__external__`) → [the account's authored\n * purpose-specific rule for the partner (`partnerPurposeRule`), NAMED as\n * its virtual fork — posture from the rule, scope from clamp 5] → the\n * account default → the Platform default (a versioned document,\n * `pol-starter-<purpose>`);\n * 2. the sending team's own policy for the purpose rides as a CEILING when\n * it is not the governing one (inside the account too);\n * 3. posture: the relationship's, raised (never lowered) by the governing\n * policy, then by the ceiling — stricter wins;\n * 4. the whole share: the purpose switch excludes it (reports too); a\n * `blocked` posture excludes a discretionary share and CARVES OUT a\n * report (never blocked at the policy / partner layer);\n * 5. per category: Required (`system`, or the Platform default's `always`)\n * bypasses every account-grain clamp; else the account's toggle (4), the\n * Platform default's Blocked (4a, not inside), the binding list (5: the\n * legacy cell chain's list or the Platform default's starting scope — the\n * governing policy's own list when it is authored (5b); K13-12), the\n * team ceiling's list (5d); rows: the floor, heightened rows off (4b),\n * field-group limits (5c), and a category every row of which is withheld\n * is withheld (the group flip).\n */\nexport function resolveShare(input: ShareResolveInput): ShareResolution {\n const { scope, purpose, recipient } = input;\n if (typeof purpose !== \"string\" || purpose === \"\")\n throw new TypeError(\"resolveShare: purpose must be a share purpose code\");\n const teamId =\n typeof input.sender?.teamId === \"string\" && input.sender.teamId !== \"\"\n ? input.sender.teamId\n : null;\n const inside = recipient.kind === \"sibling_team\";\n const recipientKey =\n recipient.kind === \"partner\"\n ? recipient.id\n : recipient.kind === \"external\"\n ? \"__external__\"\n : null;\n if (\n recipient.kind === \"partner\" &&\n (typeof recipient.id !== \"string\" || recipient.id === \"\")\n ) {\n throw new TypeError(\"resolveShare: a partner recipient needs an id\");\n }\n const report = SHARE_REPORTING_PURPOSES.has(purpose);\n const pd = input.platformDefault ?? null;\n const purposeLabel =\n typeof input.purposeLabel === \"string\" && input.purposeLabel !== \"\"\n ? input.purposeLabel\n : purpose;\n const pdRaw = pd === null ? [] : isStringList(pd.raw) ? [...pd.raw] : [];\n const pdRequired =\n pd === null ? [] : isStringList(pd.required) ? [...pd.required] : [];\n const pdBlocked =\n pd === null ? [] : isStringList(pd.blocked) ? [...pd.blocked] : [];\n const policies = (Array.isArray(input.policies) ? input.policies : []).filter(\n isLiveDoc,\n );\n const byId = new Map<string, SharePolicyDoc>();\n for (const p of policies) byId.set(p.id, p);\n const att = attachmentIndexFromPolicies(policies);\n const tree = treeIndex(scope);\n const systemCode = tree.system;\n\n // 1. the ladder\n const hit = (\n id: string | undefined,\n level: ShareLevel | \"team\",\n ): Hit | null => {\n const p = id === undefined ? undefined : byId.get(id);\n if (p === undefined || p.purpose !== purpose) return null;\n if (p.trigger?.answers === \"received\") return null;\n const v = versionOf(p.version);\n const name = typeof p.name === \"string\" ? p.name : p.id;\n return {\n policy: p,\n level,\n version: v,\n rulePath: `sharingPurposePolicies[${p.id}] v${v} (policy “${name}” — ${SHARE_LEVEL_LABEL[level]})`,\n };\n };\n const cell = (\n map: Record<string, Readonly<Record<string, string>>>,\n key: string,\n ) => own<string>(own<Readonly<Record<string, string>>>(map, key), purpose);\n let gov: Hit | null = null;\n // An unknown purpose (no Platform default) governs nothing — the ladder is not read at all\n // (review r1 #1: a policy linked under it must not leak its own list).\n const purposeKnown = pd !== null;\n const teamRowId =\n purposeKnown &&\n teamId !== null &&\n recipient.kind !== \"external\" &&\n typeof input.teamRowId === \"string\" &&\n input.teamRowId !== \"\"\n ? input.teamRowId\n : null;\n if (teamRowId !== null) gov = hit(cell(att.teamRows, teamRowId), \"team_row\");\n if (gov === null && inside && purposeKnown) {\n gov = hit(own<string>(att.internalDefaults, purpose), \"account_internal\");\n if (gov === null && pd !== null) {\n const starter: SharePolicyDoc = {\n id: `pol-inside-starter-${purpose}`,\n name: `${purposeLabel} — Inside your account (platform default)`,\n purpose,\n infoScope: null,\n posture: \"open\",\n version: 1,\n origin: { kind: \"starter\" },\n };\n gov = {\n policy: starter,\n level: \"inside_starter\",\n version: 1,\n rulePath: `${starter.id} v1 (${SHARE_LEVEL_LABEL.inside_starter} — the full record, open)`,\n };\n }\n }\n // The virtual byPurpose fork (data.js L55006-L55028): governs between the relationship\n // rung and the account default.\n let fork: Hit | null = null;\n if (gov === null && !inside && purposeKnown && recipientKey !== null) {\n gov = hit(cell(att.relationships, recipientKey), \"relationship\");\n const rule = input.partnerPurposeRule;\n const rulePosture = rule?.posture;\n if (\n gov === null &&\n recipient.kind === \"partner\" && // `__external__` stays scope-only (data.js L55333)\n (rulePosture === \"open\" ||\n rulePosture === \"approval\" ||\n rulePosture === \"blocked\")\n ) {\n const partnerName =\n typeof rule?.partnerName === \"string\" && rule.partnerName !== \"\"\n ? rule.partnerName\n : recipientKey;\n fork = {\n policy: {\n id: `pol-bp-${recipientKey}-${purpose}`,\n name: `${purposeLabel} — ${partnerName} variant`,\n purpose,\n posture: rulePosture,\n infoScope: null,\n cadences: null,\n version: 1,\n origin: { kind: \"fork\" },\n edited: true,\n },\n level: \"relationship\",\n version: 1,\n rulePath: `policies.partnerOverrides[${recipientKey}].byPurpose[${purpose}] (purpose-specific rule, reported as its fork)`,\n };\n }\n if (gov === null)\n gov = hit(own<string>(att.agencyDefaults, purpose), \"agency_default\");\n if (gov === null && pd !== null) {\n const starter: SharePolicyDoc = {\n id: `pol-starter-${purpose}`,\n name: `${purposeLabel} — Platform default`,\n purpose,\n infoScope: pdRaw.filter((c) => c !== systemCode),\n posture: \"open\",\n version: pd.version,\n origin: { kind: \"platform_starter\" },\n edited: false,\n };\n gov = {\n policy: starter,\n level: \"platform_starter\",\n version: pd.version,\n rulePath: `${starter.id} v${pd.version} (${SHARE_LEVEL_LABEL.platform_starter})`,\n };\n }\n }\n // Under the fork the account default is not consulted for posture or as 5b; an EDITED\n // account default's list still binds scope as clamp 5's ceiling, as data.js's projection\n // `sharingScopeEdits[__default__]` (projectScopeEdits L55163-L55164; read L55501, L55504).\n // Its FIELD GROUPS (`infoScopeItems`) bind too — DELIBERATELY NARROWER than data.js, whose 5c\n // (L55658) reads only the governing policy and so drops them under the fork while it keeps\n // the same default's category list: a posture-only partner rule must not release field\n // groups the admin withheld (pending the owner's word). Likewise its category list binds even\n // when `legacyCeiling` is passed (data.js would read the legacy partner rule INSTEAD of it,\n // L55504) — the 0.60.0 answer bound both, and a posture-only rule must not widen scope.\n let defaultProjection: string[] | null = null;\n let defaultItems: {\n readonly rows: Record<string, string[]>;\n readonly name: string;\n } | null = null;\n if (fork !== null) {\n if (\n gov !== null &&\n gov.level === \"agency_default\" &&\n gov.policy.edited === true\n ) {\n if (isStringList(gov.policy.infoScope))\n defaultProjection = [...gov.policy.infoScope];\n const items = copyItems(gov.policy.infoScopeItems);\n if (items !== null)\n defaultItems = {\n rows: items,\n name:\n typeof gov.policy.name === \"string\" ? gov.policy.name : gov.policy.id,\n };\n }\n gov = fork;\n }\n // data.js `postureByPurpose` (L55343): an authored purpose-specific rule for this partner\n // and purpose. Its posture is where the posture STARTS whatever the ladder named (L55342:\n // `bp.sharingPosture || over.sharingPosture || …` — the rule first). `__external__` stays\n // scope-only (L55333): a rule passed for it is ignored.\n const rulePosture = input.partnerPurposeRule?.posture;\n const ruleAuthored =\n !inside &&\n recipient.kind === \"partner\" &&\n (rulePosture === \"open\" ||\n rulePosture === \"approval\" ||\n rulePosture === \"blocked\");\n\n // 2. the team ceiling (data.js `done()` composes it over every rung's answer, the fork's too)\n let tc: Hit | null = null;\n if (teamId !== null && gov !== null) {\n const t = hit(cell(att.teams, teamId), \"team\");\n if (t !== null && t.policy.id !== gov.policy.id) tc = t;\n }\n const govNamed: ShareNamedPolicy | null =\n gov === null\n ? null\n : fork !== null\n ? { ...named(gov), virtual: true }\n : named(gov);\n const tcNamed = tc === null ? null : named(tc);\n const rulePath =\n gov === null\n ? `no Platform default for purpose “${purpose}” — nothing governs (fails closed)`\n : tc === null\n ? gov.rulePath\n : `${gov.rulePath} ∩ ${tc.rulePath} (the sending team's own policy is a ceiling — only what both allow)`;\n\n // 3. posture — the rule's when one is present (`relationshipPosture` is then ignored), else\n // the relationship row's\n let posture: SharePosture =\n ruleAuthored && rulePosture !== undefined\n ? rulePosture\n : input.relationshipPosture === \"approval\" ||\n input.relationshipPosture === \"blocked\"\n ? input.relationshipPosture\n : \"open\";\n let postureSource: ShareResolution[\"postureSource\"] = \"relationship\";\n let posturePol: ShareNamedPolicy | null = null;\n if (\n fork === null && // data.js L55391: a virtual policy's posture is never applied\n govNamed?.posture &&\n SHARE_POSTURE_RANK[govNamed.posture] > SHARE_POSTURE_RANK[posture]\n ) {\n posture = govNamed.posture;\n postureSource = \"policy\";\n posturePol = govNamed;\n }\n if (\n tcNamed?.posture &&\n SHARE_POSTURE_RANK[tcNamed.posture] > SHARE_POSTURE_RANK[posture]\n ) {\n posture = tcNamed.posture;\n postureSource = \"team_ceiling\";\n posturePol = tcNamed;\n }\n\n // 4. the whole share\n let excluded: ShareResolution[\"excluded\"] = null;\n let reportCarveOut: ShareResolution[\"reportCarveOut\"] = null;\n if (gov === null) {\n excluded = {\n reason: `No Platform default for purpose “${purpose}” — nothing may leave under it`,\n rulePath,\n };\n } else if (input.purposeOff === true) {\n excluded = {\n reason: \"Share purpose disabled by your account's sharing policy\",\n rulePath: `purposeOverrides[${purpose}] = false`,\n };\n } else if (posture === \"blocked\") {\n const pol = posturePol; // null = the relationship's own posture blocks (review r1 #3)\n const path =\n pol === null\n ? \"relationship posture = blocked\"\n : `sharingPurposePolicies[${pol.id}].posture=blocked (policy “${pol.name}” — ${pol.levelLabel})`;\n // The rule itself is what blocked (data.js `!byCeiling && postureByPurpose`, L55436 /\n // L55447). DELIBERATE CORRECTION of data.js: there the purpose-rule sentence and path also\n // stand when the rule is open and an attached policy blocked, naming a cause that is false;\n // here they stand only when the rule blocked — the decision is unchanged, the audit record\n // names the true cause.\n const byRule = ruleAuthored && postureSource === \"relationship\";\n if (report && byRule) {\n // data.js L55436-L55446\n reportCarveOut = {\n note: \"Partner is blocked for ordinary sharing — reachable for reports\",\n rulePath: `reports-never-blocked-at-partner-layer (Crysta ruling 2026-08-23; policies.partnerOverrides[${recipientKey}].byPurpose[${purpose}].sharingPosture=blocked does not bind a legal duty — who may send is a role/function question)`,\n };\n } else if (report) {\n reportCarveOut = {\n note:\n pol === null\n ? \"Blocked for ordinary sharing — reachable for reports (nothing at the partner layer extinguishes the duty)\"\n : `The “${pol.name}” policy blocks ordinary sharing — reachable for reports`,\n rulePath: path,\n };\n } else if (byRule) {\n // data.js L55447-L55448\n excluded = {\n reason:\n \"Partner is blocked for this purpose by your account's sharing policy\",\n rulePath: `policies.partnerOverrides[${recipientKey}].byPurpose[${purpose}].sharingPosture=blocked (Share Partners — purpose-specific rule)`,\n };\n } else {\n excluded = {\n reason:\n pol === null\n ? \"Blocked for this purpose by the relationship\"\n : `Blocked for this purpose by your account's “${pol.name}” policy`,\n rulePath: path,\n };\n }\n }\n const excludedAll = excluded !== null;\n\n // 5. which list binds (K13-12)\n const level = gov?.level ?? null;\n const govList = govNamed?.infoScope ?? null;\n const polScopeBinds =\n gov !== null &&\n Array.isArray(govList) &&\n (level === \"team_row\" ||\n level === \"relationship\" ||\n level === \"account_internal\" ||\n level === \"inside_starter\" ||\n (level === \"agency_default\" && gov.policy.edited === true));\n const legacy = legacyCeilingList(input.legacyCeiling);\n // data.js L55504-L55505: cpEdit || seedOverride || defEdit || the starting scope\n const projectionPath = `policies.sharingScopeEdits[__default__][${purpose}] (projected from your account default policy)`;\n const projOverLegacy: string[] | null =\n legacy !== null ? defaultProjection : null;\n const ceilingIsStarter = legacy === null && defaultProjection === null;\n let groupCeiling: string[] | null = legacy ?? defaultProjection ?? pdRaw;\n let ceilingPath =\n legacy !== null\n ? \"sharingScopeEdits (the account's partner / default rule — the legacy cell chain)\"\n : defaultProjection !== null\n ? projectionPath\n : pd === null\n ? \"no Platform default\"\n : `pol-starter-${purpose} v${pd.version} (Platform default — the starting scope for this purpose)`;\n if (ceilingIsStarter && polScopeBinds) {\n groupCeiling = null;\n ceilingPath = \"\";\n }\n if (inside) {\n groupCeiling = null;\n ceilingPath = \"\";\n }\n const tcScope = tcNamed?.infoScope ?? null;\n const tcItems = tc?.policy.infoScopeItems ?? null;\n const govItems = gov?.policy.infoScopeItems ?? null;\n const required = (g: string): boolean =>\n g === systemCode || (!inside && pd !== null && pdRequired.includes(g));\n const blockedSet = new Set(pdBlocked);\n const asSet = (v: unknown): Set<string> => new Set(isStringList(v) ? v : []);\n const categoriesOff = asSet(input.accountScope?.categoriesOff);\n const rowsOff = asSet(input.accountScope?.rowsOff);\n const categoriesOn = asSet(input.accountScope?.categoriesOn);\n const rowsOn = asSet(input.accountScope?.rowsOn);\n const underFloor = (code: string): boolean =>\n scope.ancestorsOf(code).some((c) => scope.row(c)?.platformFloor === true);\n // Clamp 4 (data.js L55165-L55170): the account's explicit choice wins both ways; else the\n // codebook's `shareableDefault` — a heightened category is off until the account turns it on.\n const categoryOffByDefault = (g: string): boolean =>\n !categoriesOn.has(g) && scope.row(g)?.shareableDefault === false;\n // Clamp 4b (L55185-L55196): a row is off when the account switched it (or a grouping above it)\n // off, or when it — or a grouping between it and its category — is heightened by default and\n // the account has not turned that one on (`shareVerdict`'s rule: turning a grouping on does not\n // turn on an off-by-default row beneath it).\n const heightenedOff = (code: string, g: string): boolean => {\n const chain = scope.ancestorsOf(code);\n if (chain.some((c) => rowsOff.has(c))) return true;\n const below = chain.slice(0, Math.max(chain.indexOf(g), 0));\n return below.some(\n (c) => !rowsOn.has(c) && scope.row(c)?.shareableDefault === false,\n );\n };\n\n const out: Record<string, ShareCategoryEntry> = {};\n const allowedCategories: string[] = [];\n const govName = govNamed?.name ?? \"\";\n for (const g of tree.categories) {\n const items = tree.descendants.get(g) ?? [];\n const leaves = tree.leaves.get(g) ?? [];\n const platformRequired =\n !inside && pd !== null && pdRequired.includes(g)\n ? {\n rulePath: `pol-starter-${purpose} v${pd.version} · ${g} = Required (Platform default — set by the Platform Admin)`,\n }\n : null;\n const req = required(g);\n let allowed = true;\n let reason = excluded !== null ? excluded.reason : \"Allowed\";\n let path = excluded !== null ? excluded.rulePath : rulePath;\n const floorItems = items.filter(underFloor);\n const excludedItems: string[] = [];\n let excludedReason: string | null = null;\n const teamExcludedItems: string[] = [];\n let teamExcludedReason: string | null = null;\n // A row is OUTSIDE a list only when neither it nor anything beneath it is covered: a grouping\n // whose rows the list names by name (`instrument_summary` named only through `summary_lap`)\n // is not withheld as a unit — its uncovered rows are, each at its own grain (0.42.1; the\n // Thread inside-ceiling adoption found the whole grouping dropped with its named rows).\n // Latent gap: a grouping that carries its OWN fields (INFORMATION_SCOPE_FIELD_HOME_ROWS) and\n // whose children are all named, but not itself, is not withheld here — its own fields would\n // then leave, contrary to coverage rule 2 (`ceilingCoverage`, hasOwnContent → false). No live\n // grouping has own content today; whoever adds a field-homed grouping must handle it here.\n const outside = (covered: (r: string) => boolean): string[] =>\n items.filter(\n (r) =>\n !covered(r) &&\n !items.some(\n (d) => d !== r && covered(d) && scope.ancestorsOf(d).includes(r),\n ),\n );\n const addExcluded = (rows: readonly string[], why: string): void => {\n for (const r of rows)\n if (!floorItems.includes(r) && !excludedItems.includes(r))\n excludedItems.push(r);\n if (rows.length > 0 && excludedReason === null) excludedReason = why;\n };\n if (gov === null) {\n allowed = false; // an unknown purpose: nothing leaves, System metadata included\n } else if ((!req || platformRequired !== null) && excludedAll) {\n allowed = false;\n } else if (excludedAll) {\n reason = \"Allowed\";\n path = rulePath;\n }\n if (allowed && !req && (categoriesOff.has(g) || categoryOffByDefault(g))) {\n allowed = false;\n reason = \"Excluded by your account's Information Scope policy\";\n path = categoriesOff.has(g)\n ? `policies.scopeCatalog[${g}].shareable = false`\n : `policies.scopeCatalog[${g}] not turned on — codebook core-information_scope shareableDefault = false (CVC-236 heightened protection: off until the account turns it on)`;\n }\n if (allowed && !req && !inside && blockedSet.has(g)) {\n allowed = false;\n reason =\n \"Blocked for this purpose by the Platform default — no account can share it under this purpose\";\n path = `pol-starter-${purpose} v${pd?.version ?? 1} · ${g} = Blocked (Platform default — CVC-236 heightened protection | set by the Platform Admin)`;\n }\n // 4b heightened rows off in the account (every category but System metadata, Required included)\n addExcluded(\n g === systemCode\n ? []\n : items.filter((r) => !underFloor(r) && heightenedOff(r, g)),\n \"Heightened protection (CVC-236) — off in your account's Information Scope until the account turns it on\",\n );\n if (\n allowed &&\n !req &&\n groupCeiling !== null &&\n !scopeListCovers(scope, groupCeiling, g)\n ) {\n allowed = false;\n reason = \"Outside the payload for this purpose\";\n path = ceilingPath;\n }\n if (\n allowed &&\n !req &&\n groupCeiling !== null &&\n !scopeListStrictlyCovers(scope, groupCeiling, g)\n ) {\n addExcluded(\n outside((r) => scopeListCovers(scope, groupCeiling, g, r)),\n \"Outside the payload for this purpose\",\n );\n }\n if (\n allowed &&\n !req &&\n polScopeBinds &&\n !scopeListCovers(scope, govList, g)\n ) {\n allowed = false;\n reason = `Outside what the “${govName}” policy allows for this purpose`;\n path = `sharingPurposePolicies[${gov?.policy.id}].infoScope (policy “${govName}” — ${govNamed?.levelLabel})`;\n }\n if (\n allowed &&\n !req &&\n polScopeBinds &&\n !scopeListStrictlyCovers(scope, govList, g)\n ) {\n addExcluded(\n outside((r) => scopeListCovers(scope, govList, g, r)),\n `Outside what the “${govName}” policy allows for this purpose`,\n );\n }\n // Under the fork with `legacyCeiling` passed: the edited account default's list binds too.\n if (\n allowed &&\n !req &&\n projOverLegacy !== null &&\n !scopeListCovers(scope, projOverLegacy, g)\n ) {\n allowed = false;\n reason = \"Outside the payload for this purpose\";\n path = projectionPath;\n }\n if (\n allowed &&\n !req &&\n projOverLegacy !== null &&\n !scopeListStrictlyCovers(scope, projOverLegacy, g)\n ) {\n addExcluded(\n outside((r) => scopeListCovers(scope, projOverLegacy, g, r)),\n \"Outside the payload for this purpose\",\n );\n }\n const govRows = polScopeBinds ? own<unknown>(govItems, g) : undefined;\n if (allowed && !req && isStringList(govRows)) {\n const keep = new Set(govRows);\n const kept = (r: string): boolean =>\n keep.has(r) || scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));\n addExcluded(\n outside(kept),\n `Outside what the “${govName}” policy allows for this purpose`,\n );\n }\n // Under the fork: the edited account default's field groups still bind (see above).\n const defRows =\n defaultItems === null ? undefined : own<unknown>(defaultItems.rows, g);\n if (allowed && !req && isStringList(defRows)) {\n const keep = new Set(defRows);\n const kept = (r: string): boolean =>\n keep.has(r) || scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));\n addExcluded(\n outside(kept),\n `Outside what the “${defaultItems?.name ?? \"\"}” policy allows for this purpose`,\n );\n }\n if (\n allowed &&\n !req &&\n tcScope !== null &&\n !scopeListCovers(scope, tcScope, g)\n ) {\n allowed = false;\n reason = `Outside what your team's “${tcNamed?.name}” policy allows`;\n path = `sharingPurposePolicies[${tc?.policy.id}].infoScope (policy “${tcNamed?.name}” — ${SHARE_LEVEL_LABEL.team}; a ceiling over “${govName}”)`;\n }\n if (allowed && !req && tc !== null) {\n const why = `Outside what your team's “${tcNamed?.name}” policy allows`;\n const outRows = new Set<string>();\n if (tcScope !== null && !scopeListStrictlyCovers(scope, tcScope, g)) {\n for (const r of outside((x) => scopeListCovers(scope, tcScope, g, x)))\n outRows.add(r);\n }\n const tcRows = own<unknown>(tcItems, g);\n if (isStringList(tcRows)) {\n const keep = new Set(tcRows);\n const kept = (r: string): boolean =>\n keep.has(r) ||\n scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));\n for (const r of outside(kept)) outRows.add(r);\n }\n for (const r of outRows)\n if (!floorItems.includes(r) && !excludedItems.includes(r))\n teamExcludedItems.push(r);\n if (teamExcludedItems.length > 0) teamExcludedReason = why;\n }\n // the group flip: every leaf row withheld → the category is withheld\n if (allowed && (!req || platformRequired !== null) && leaves.length > 0) {\n const gone = new Set(\n [...floorItems, ...excludedItems, ...teamExcludedItems].filter((r) =>\n leaves.includes(r),\n ),\n );\n if (gone.size >= leaves.length) {\n allowed = false;\n if (leaves.every((r) => floorItems.includes(r))) {\n reason = \"Never shared — under the platform safety floor\";\n path = \"HTI_PLATFORM_SAFETY_FLOOR\";\n } else if (leaves.some((r) => excludedItems.includes(r))) {\n reason = excludedReason ?? reason;\n } else {\n reason = teamExcludedReason ?? reason;\n }\n }\n }\n out[g] = {\n allowed,\n reason,\n rulePath: path,\n platformRequired,\n floorItems: uniq(floorItems),\n excludedItems: uniq(excludedItems),\n excludedReason,\n teamExcludedItems: uniq(teamExcludedItems),\n teamExcludedReason,\n };\n if (allowed) allowedCategories.push(g);\n }\n\n return {\n allowed: !excludedAll,\n posture,\n postureSource,\n excluded,\n reportCarveOut,\n governing: govNamed,\n teamCeiling: tcNamed,\n inside,\n scope: out,\n allowedCategories,\n rulePath,\n };\n}\n","/**\n * EVENT-DRIVEN SHARING — which listeners an event fires (Kickoff 13 build\n * item 9a; Crysta 2026-10-19 14:26 \"enabling vs firing\"; home ruled\n * 2026-11-01: platform-common exports `ShareEvent` + `fireShareEvent(policies,\n * event)` as a pure function, and each app calls it after commit at session\n * submit and case close).\n *\n * Contract of record: platform-prototype `src/data.js` — `TRIGGER_EVENTS`,\n * `policyIsListener`, `listenersFor`, `fireShareEvent` (K13-9a\n * EVENT-LISTENER 2026-10-22).\n *\n * ENABLING is a Policy with the `ongoing` cadence and a trigger, linked team\n * → team or team → partner: standing permission, authored by the Member\n * Admin. FIRING writes an ORDINARY share — the policy's purpose and version\n * on it — down the normal notify → review → claim path; only the author\n * differs.\n *\n * This module answers ONE question and decides nothing else: given the\n * sending account's policy documents and an event raised by a team, which\n * listeners fire, and to whom. Everything a manual share of that purpose\n * would be held to still applies and stays where it lives — the app sends\n * each answer through its own send door: `resolveShare` for what may leave\n * (and the policy's posture — `approval` waits, `blocked` holds), the release\n * for a partner (one that covers the `ongoing` cadence), the account's\n * catalog, the floor. A fired share is never a way around a rule.\n *\n * THE CALLER'S TWO DUTIES. (1) A link is read from the policy document's own\n * `assignments`; pass the account's team rows as `options.teamRows` (or check\n * `teamRowId` against your row store before sending) so a link whose row was\n * deleted, or no longer says what the document says, fires nothing. (2) An\n * event that can happen more than once on one subject (a note, a service, a\n * status change) needs its own `ref`, or the second is taken for the first.\n *\n * Pure: no I/O, no clock, no randomness. The same input gives the same\n * output, so a caller can run it twice and compare `key`s to fire each\n * listener ONCE per event per subject (pass the keys already written as\n * `alreadyFired`).\n */\n\nimport {\n attachmentIndexFromPolicies,\n type SharePolicyAssignment,\n type SharePolicyDoc,\n type ShareRecipient,\n type ShareTeamRowLike,\n} from \"./resolve.js\";\n\n/**\n * The events a listener may name. A trigger is a flag over EXISTING codes —\n * the CVC-285 event names the platform already emits — and mints no new CVC\n * (open point 5's default). The subset a case or a share can raise, in the\n * prototype's order and words.\n */\nexport const SHARE_TRIGGER_EVENTS = Object.freeze([\n { code: \"sessionSubmitted\", label: \"Session submitted\", group: \"case\" },\n { code: \"caseOpened\", label: \"Case opened\", group: \"case\" },\n { code: \"caseStatusChanged\", label: \"Case status changed\", group: \"case\" },\n { code: \"caseCloseRuled\", label: \"Case closed\", group: \"case\" },\n {\n code: \"determinationIssued\",\n label: \"Determination issued\",\n group: \"case\",\n },\n { code: \"serviceLogged\", label: \"Service logged\", group: \"case\" },\n { code: \"noteAdded\", label: \"Note added\", group: \"case\" },\n { code: \"shareClaimed\", label: \"Share you sent claimed\", group: \"share\" },\n {\n code: \"referralClaimed\",\n label: \"Referral you sent claimed\",\n group: \"share\",\n },\n {\n code: \"shareAcknowledged\",\n label: \"Share you sent acknowledged\",\n group: \"share\",\n },\n] as const);\n\nexport type ShareTriggerEventCode =\n (typeof SHARE_TRIGGER_EVENTS)[number][\"code\"];\n\n/** The two events the apps raise today (session submit · case close). */\nexport const SHARE_EVENT = Object.freeze({\n SESSION_SUBMITTED: \"sessionSubmitted\",\n CASE_CLOSED: \"caseCloseRuled\",\n} as const satisfies Record<string, ShareTriggerEventCode>);\n\n/** The words a person reads for a trigger code (the code itself when unknown). */\nexport function shareTriggerLabel(code: string): string {\n return SHARE_TRIGGER_EVENTS.find((t) => t.code === code)?.label ?? code;\n}\n\n/** Something that happened on a case or a session, raised by the team that did it. */\nexport interface ShareEvent {\n /** The CVC-285 event name (`SHARE_EVENT`, `SHARE_TRIGGER_EVENTS`). */\n readonly event: string;\n /**\n * The ACTING team — a listener is a link FROM a team, so an event with no\n * team fires nothing.\n */\n readonly teamId: string | null | undefined;\n /** Informational: `policies` must already be the sending account's documents. */\n readonly accountId?: string | null;\n readonly caseId?: string | null;\n readonly sessionId?: string | null;\n /**\n * What the event is about, for the once-only key. Default: the session id\n * for `sessionSubmitted`; for every other event the case id, else the\n * session id; else none (every such event shares one key). Pass it\n * explicitly for an event that can repeat on one case.\n */\n readonly ref?: string | null;\n}\n\n/** One listener: a policy with the `ongoing` cadence and a trigger, on one team link. */\nexport interface ShareListener {\n readonly policy: {\n readonly id: string;\n readonly familyId: string;\n readonly name: string;\n readonly version: number;\n };\n readonly purpose: string;\n readonly fromTeamId: string;\n /** The link's row — what `resolveShare` takes as `teamRowId`. */\n readonly teamRowId: string;\n /** Who it sends to, in the resolver's own vocabulary. */\n readonly recipient: Extract<\n ShareRecipient,\n { kind: \"partner\" } | { kind: \"sibling_team\" }\n >;\n /** A team → partner-team link names the partner's team; else `null`. */\n readonly partnerTeamId: string | null;\n /** The events it listens for. */\n readonly events: readonly string[];\n}\n\n/** One listener an event raised — the share the app is to write. */\nexport interface FiredShare extends ShareListener {\n readonly event: string;\n readonly ref: string | null;\n /**\n * Stable for one event × subject × policy × sending team × recipient: the\n * same event on the same case fires each listener ONCE. Opaque — compare\n * it, never parse it.\n */\n readonly key: string;\n}\n\nconst str = (v: unknown): v is string => typeof v === \"string\" && v !== \"\";\n\n/**\n * A policy that listens: live, `ongoing` cadence, at least one trigger event\n * (data.js `policyIsListener`) — and NOT a share-back policy\n * (`trigger.answers === \"received\"`, K13-9b), which answers a share received\n * and never fires on a case event.\n */\nexport function policyIsShareListener(\n p: SharePolicyDoc | null | undefined,\n): boolean {\n if (p === null || p === undefined || typeof p !== \"object\") return false;\n if (p.active === false) return false;\n // strictly `true` (the prototype accepts any truthy value; a stored `1` or\n // `\"true\"` does not listen here — fail closed)\n if (p.cadences?.ongoing !== true) return false;\n const on = p.trigger?.on;\n if (!Array.isArray(on) || !on.some(str)) return false;\n return p.trigger?.answers !== \"received\";\n}\n\ntype PairLink = Extract<SharePolicyAssignment, { scope: \"team_pair\" }>;\n\n/**\n * Where a team link sends, or `null` when the link does not say (never\n * guessed) — data.js `listenersFor`: a row with no partner whose `with` is a\n * team is a team → team link; with a partner, `with` (a team) names the\n * partner's team.\n */\nfunction linkTarget(\n a: PairLink,\n): Pick<ShareListener, \"recipient\" | \"partnerTeamId\"> | null {\n const withTeam =\n a.with !== null &&\n typeof a.with === \"object\" &&\n a.with.type === \"team\" &&\n str(a.with.id)\n ? a.with.id\n : null;\n if (str(a.partnerId)) {\n return {\n recipient: { kind: \"partner\", id: a.partnerId },\n partnerTeamId: withTeam,\n };\n }\n if (withTeam !== null) {\n return {\n recipient: { kind: \"sibling_team\", teamId: withTeam },\n partnerTeamId: null,\n };\n }\n return null;\n}\n\n/** Collision-free whatever the ids contain. */\nconst targetKey = (\n l: Pick<ShareListener, \"recipient\" | \"partnerTeamId\">,\n): readonly (string | null)[] =>\n l.recipient.kind === \"partner\"\n ? [\"partner\", l.recipient.id, l.partnerTeamId]\n : [\"team\", l.recipient.teamId, null];\n\n/** Does the account's row store still say what the link says? */\nfunction rowAgrees(\n rows: readonly ShareTeamRowLike[],\n a: PairLink,\n target: Pick<ShareListener, \"recipient\" | \"partnerTeamId\">,\n): boolean {\n const row = rows.find(\n (r) => r !== null && typeof r === \"object\" && r.id === a.teamRowId,\n );\n if (row === undefined || row.myTeamId !== a.teamId) return false;\n const theirTeam =\n row.their?.type === \"team\" && str(row.their.id) ? row.their.id : null;\n return target.recipient.kind === \"sibling_team\"\n ? theirTeam === target.recipient.teamId\n : theirTeam === target.partnerTeamId;\n}\n\n/**\n * The listeners linked FROM one team (data.js `listenersFor`): each listening\n * policy × each of its team → team / team → partner links whose sending team\n * is `teamId`. A link that names no sending team, a different team, or no\n * target is not a listener for this team. The policy must also be the one\n * that HOLDS the row's cell for its purpose (`attachmentIndexFromPolicies` —\n * two live documents on one cell: the later wins, exactly as the ladder\n * reads it), so the share a listener fires is governed by that same policy.\n * Two links of one policy to the same place are one listener (the first, in\n * document order). `options.event` keeps only the policies listening for\n * that event; `options.teamRows`, when given, drops a link whose row is gone\n * or disagrees with it.\n */\nexport function shareListenersFor(\n policies: readonly SharePolicyDoc[] | null | undefined,\n teamId: string | null | undefined,\n options: {\n readonly event?: string | null;\n readonly teamRows?: readonly ShareTeamRowLike[] | null;\n } = {},\n): ShareListener[] {\n if (!Array.isArray(policies) || !str(teamId)) return [];\n const cells = attachmentIndexFromPolicies(policies).teamRows;\n const rows = Array.isArray(options.teamRows) ? options.teamRows : null;\n const out: ShareListener[] = [];\n const seen = new Set<string>();\n for (const p of policies) {\n if (!policyIsShareListener(p) || !str(p.id) || !str(p.purpose)) continue;\n const events = (p.trigger?.on ?? []).filter(str);\n if (str(options.event) && !events.includes(options.event)) continue;\n for (const a of Array.isArray(p.assignments) ? p.assignments : []) {\n if (a === null || typeof a !== \"object\" || a.scope !== \"team_pair\")\n continue;\n if (!str(a.teamRowId) || a.teamId !== teamId) continue;\n // the cell's holder listens; a document another one displaced does not\n if (cells[a.teamRowId]?.[p.purpose] !== p.id) continue;\n const target = linkTarget(a);\n if (target === null) continue;\n if (rows !== null && !rowAgrees(rows, a, target)) continue;\n // a team never listens to itself\n if (\n target.recipient.kind === \"sibling_team\" &&\n target.recipient.teamId === teamId\n )\n continue;\n const dedupe = JSON.stringify([p.id, ...targetKey(target)]);\n if (seen.has(dedupe)) continue;\n seen.add(dedupe);\n out.push({\n policy: {\n id: p.id,\n familyId: str(p.familyId) ? p.familyId : p.id,\n name: str(p.name) ? p.name : p.id,\n version: parseInt(String(p.version), 10) || 1,\n },\n purpose: p.purpose,\n fromTeamId: teamId,\n teamRowId: a.teamRowId,\n ...target,\n events,\n });\n }\n }\n return out;\n}\n\n/** The once-only key of one fired share (see `FiredShare.key`). */\nexport function firedShareKey(\n event: string,\n ref: string | null,\n listener: Pick<\n ShareListener,\n \"policy\" | \"fromTeamId\" | \"recipient\" | \"partnerTeamId\"\n >,\n): string {\n return JSON.stringify([\n event,\n ref,\n listener.policy.id,\n listener.fromTeamId,\n ...targetKey(listener),\n ]);\n}\n\n/**\n * FIRING (data.js `fireShareEvent`, the pure half): the listeners linked from\n * the acting team that listen for this event, each as the share to write.\n * Call it AFTER the event's own write commits. `[]` when the event names no\n * team or no event, when nothing listens — and for every listener whose key\n * is in `alreadyFired` (what the app has written for this event before).\n *\n * The app then sends each one as an ordinary share of `purpose` to\n * `recipient` from `fromTeamId` on `teamRowId`, stamped with `policy`, through\n * its own send door. This function never decides what leaves or whether it\n * may.\n */\nexport function fireShareEvent(\n policies: readonly SharePolicyDoc[] | null | undefined,\n event: ShareEvent | null | undefined,\n options: {\n readonly alreadyFired?: Iterable<string> | null;\n readonly teamRows?: readonly ShareTeamRowLike[] | null;\n } = {},\n): FiredShare[] {\n if (event === null || event === undefined || !str(event.event)) return [];\n const session = str(event.sessionId) ? event.sessionId : null;\n const kase = str(event.caseId) ? event.caseId : null;\n const ref = str(event.ref)\n ? event.ref\n : event.event === SHARE_EVENT.SESSION_SUBMITTED\n ? (session ?? kase)\n : (kase ?? session);\n const done = new Set(options.alreadyFired ?? []);\n const fired: FiredShare[] = [];\n for (const l of shareListenersFor(policies, event.teamId, {\n event: event.event,\n teamRows: options.teamRows ?? null,\n })) {\n const key = firedShareKey(event.event, ref, l);\n if (done.has(key)) continue;\n fired.push({ ...l, event: event.event, ref, key });\n }\n return fired;\n}\n","/**\n * Reading a STORED SHARING POLICY's information-scope list — once, for every\n * app (CVC-236 `core-information_scope`, the version-4 tree).\n *\n * WHAT THIS IS FOR. Every sharing policy the Admin Hub has stored is the old\n * category names with NO version mark (`scopeVersion` absent). PAVE and Thread\n * each read that unmarked list their own way, and the two readings differed\n * (Thread's left out the instrument Summary rows). {@link readStoredPolicyScope}\n * is the one reading both call, so they cannot differ.\n *\n * THE RULE (PAVE pave-2.0 #2358, merge 38b1008a6 —\n * `storedPolicyScopeReadingV4` + `migrateUnstampedPolicySeedToV3` + `termV4`;\n * ADR-CONTRACT-policy-ceiling-shared-resolver § 13; reproduced here exactly):\n *\n * - A list MARKED version 3 or 4 is read at its mark, as it is. A marked\n * list never gains the rows the table below adds.\n * - An UNMARKED list (an array, with `scopeVersion` absent or `null`) is\n * carried forward through the codebook's published old → new conversion,\n * oldest step first: canon's v2 → v3 CATEGORY lines\n * ({@link UNMARKED_POLICY_CATEGORY_LINES}), then the resolver's own\n * v3 → v4 policy reading (`readSelection(…, 3, { subject: \"policy\" })`,\n * the SOT's `migrations.table`). A code that is not one of the old\n * category names is not guessed at: it includes nothing and is reported\n * in `unknown`.\n * - A mark that is not the number 3 or 4 (the string \"3\", the number 2)\n * cannot be read: the list includes nothing. Nothing is guessed.\n * - A list that names nothing permits NOTHING (`permits` is `[]`) — never\n * \"metadata only\", although every reading contains `system_info`.\n * Metadata only is an answer only when the list itself names the metadata\n * row. \"Names nothing\" is judged on the rows the CALLING APP carries, so\n * the app is a required argument: a list naming only categories that app\n * never carries permits nothing there.\n *\n * POLICY LISTS ONLY. This applies to a sharing policy's `infoScope` and to\n * nothing else. A share, a release, a preset, a restriction and a viewing\n * list keep the developers' rule of 2026-10-10: an unmarked list includes\n * nothing (the resolver's `readSelection` / `readRestriction` with no stamp).\n * Do not call this for them.\n *\n * THE TABLE. {@link UNMARKED_POLICY_CATEGORY_LINES} is canon's, verbatim:\n * `data/cvcs/core_information_scope.yaml` `migrations.categories`, L559-L564\n * @ htilabstech/prototype 00179edc — the v2 → v3 table the SOT's\n * `migrations.unstamped` and `migrations.readAt` point at (\"L539-565 @\n * 00179edc\"). They are the same three lines PAVE transcribed; PAVE deletes its\n * copy when it adopts this call, and until then there are two. This one is\n * held to canon by a pin: `src/__sot__/informationScopeV2V3Categories.pin.json`\n * (derived by `scripts/sot-pins.ts` from the yaml's `migrations_history`), and\n * a test fails when the constant and the pin differ. It is not a second\n * v3 → v4 table and not a codebook.\n *\n * Pure: no I/O, no SOT import — pass the bound v4 tree, as every reader in\n * this module takes it.\n */\nimport {\n INFORMATION_SCOPE_SYSTEM_INFO,\n type InformationScopeResolver,\n type ScopeApp,\n} from \"../services/informationScopeResolver.js\";\n\n/** The tree as this reader needs it. */\nexport type StoredPolicyScopeTree = Pick<InformationScopeResolver, \"readSelection\" | \"row\">;\n\n/**\n * The old category names an unmarked policy list may carry: the eight a policy\n * is authored in, and the four LEADS-only categories (recognised so they read\n * as themselves; an app that never carries them drops them by `app`).\n */\nexport const UNMARKED_POLICY_CATEGORY_CODES = [\n \"identifying\",\n \"risk\",\n \"contact\",\n \"services\",\n \"notes\",\n \"health_accommodation\",\n \"immigration_legal_status\",\n \"system\",\n \"network_associations\",\n \"commercial_activity\",\n \"investigative_work_product\",\n \"object_identifiers\",\n] as const;\n\n/**\n * Canon's v2 → v3 CATEGORY lines, verbatim (see the module header). A line\n * fires when EVERY `allOf` name is in the list and ADDS `to`. \"Every Full row\n * stays off.\"\n */\nexport const UNMARKED_POLICY_CATEGORY_LINES: readonly {\n readonly to: readonly string[];\n readonly allOf: readonly string[];\n}[] = [\n {\n to: [\n \"summary_initial_screen\",\n \"summary_lap\",\n \"summary_danger_assessment\",\n \"summary_stalking_assessment\",\n \"summary_injury_and_strangulation\",\n \"summary_ae_intake\",\n \"summary_tra\",\n ],\n allOf: [\"risk\"],\n },\n {\n to: [\n \"summary_mental_health_screen\",\n \"summary_behavioral_health_intake\",\n \"summary_trauma_and_coping_screen\",\n ],\n allOf: [\"risk\", \"health_accommodation\"],\n },\n { to: [\"summary_needs_assessment\"], allOf: [\"services\"] },\n];\n\n/** The version an unmarked list is read at once the category lines are applied. */\nexport const UNMARKED_POLICY_CARRY_VERSION = 3 as const;\n\nconst CATEGORY_CODES: ReadonlySet<string> = new Set(UNMARKED_POLICY_CATEGORY_CODES);\n\nconst strings = (list: unknown): string[] =>\n Array.isArray(list) ? list.filter((c): c is string => typeof c === \"string\") : [];\n\n/**\n * The first step for an unmarked policy list: the list it reads as at version\n * 3 (its category names plus the rows the category lines add), and the codes\n * that are not old category names (`refused` — they include nothing).\n */\nexport function carryUnmarkedPolicyList(list: unknown): { list: string[]; refused: string[] } {\n const stored = strings(list);\n const categories = stored.filter((c) => CATEGORY_CODES.has(c));\n const refused = stored.filter((c) => !CATEGORY_CODES.has(c));\n const named = new Set(categories);\n const added = UNMARKED_POLICY_CATEGORY_LINES.filter((line) =>\n line.allOf.every((c) => named.has(c)),\n ).flatMap((line) => line.to);\n return { list: [...new Set([...categories, ...added])], refused };\n}\n\n/**\n * What the reader did:\n * - `marked` — the list carried a readable mark and was read at it;\n * - `carried` — the list had no mark and was carried forward (above);\n * - `empty` — the list permits nothing (it names nothing `options.app`\n * carries, or its mark cannot be read).\n */\nexport type StoredPolicyScopeOutcome = \"marked\" | \"carried\" | \"empty\";\n\nexport interface StoredPolicyScopeReading {\n readonly outcome: StoredPolicyScopeOutcome;\n /** The list had no version mark (an array with `scopeVersion` absent or `null`). */\n readonly unmarked: boolean;\n /** The mark as stored when it is a number; otherwise `null`. Never inferred. */\n readonly storedVersion: number | null;\n /** The list as stored (its string codes) — never rewritten. */\n readonly stored: readonly string[];\n /**\n * The list as read on the current tree: unique, tree order, always\n * containing `system_info` (the resolver's reading). Use `permits` to decide\n * what the policy allows.\n */\n readonly informationScope: readonly string[];\n /**\n * What the policy permits: `informationScope`, or `[]` when the list names\n * nothing (\"an empty term stays empty\").\n */\n readonly permits: readonly string[];\n /** Stored codes whose reading is wider than at version 3 (surface, never hide). */\n readonly widened: readonly string[];\n /** Stored codes that are retired and read through the table. */\n readonly retired: readonly string[];\n /** Stored codes with no reading; they include nothing. */\n readonly unknown: readonly string[];\n /** The mark is present and is not the number 3 or 4, or a non-list had no mark. */\n readonly unsupportedVersion: boolean;\n /**\n * The app writes a dated version row before acting on this reading: true\n * for a version-3 list and for an unmarked list carried forward.\n */\n readonly versionRowRequired: boolean;\n}\n\nexport interface ReadStoredPolicyScopeOptions {\n /**\n * REQUIRED — the app that is reading. \"Names nothing\" is judged on the rows\n * this app carries (the row's `apps` flag): a list naming only categories\n * the app never carries permits nothing. PAVE passes `\"pave\"`, Thread\n * `\"thread\"`. There is no default and no \"every row\" value: leaving the app\n * out would be the widest answer, and could allow what PAVE refuses.\n */\n readonly app: ScopeApp;\n}\n\nconst APPS: ReadonlySet<string> = new Set<ScopeApp>([\"pave\", \"thread\", \"leads\"]);\n\n/**\n * Read one stored sharing-policy `infoScope` list on the current tree. Total\n * on stored data (`list`, `versionMark`): never throws on it. Throws a\n * `RangeError` when `options.app` is missing or not an app — a caller's\n * mistake, never a stored value. See the module header for the rule; POLICY\n * lists only.\n *\n * @param scope the bound CVC-236 v4 tree\n * @param list the stored `infoScope`\n * @param versionMark the stored `scopeVersion` (`undefined` / `null` = unmarked)\n * @param options `{ app }` — the app that is reading (required)\n */\nexport function readStoredPolicyScope(\n scope: StoredPolicyScopeTree,\n list: unknown,\n versionMark: unknown,\n options: ReadStoredPolicyScopeOptions,\n): StoredPolicyScopeReading {\n const app = (options as ReadStoredPolicyScopeOptions | undefined)?.app;\n if (typeof app !== \"string\" || !APPS.has(app)) {\n throw new RangeError(\n 'readStoredPolicyScope: options.app must be \"pave\", \"thread\" or \"leads\" (the app that is reading)',\n );\n }\n const stored = strings(list);\n const unmarked = Array.isArray(list) && (versionMark === undefined || versionMark === null);\n const stamp = typeof versionMark === \"number\" ? versionMark : null;\n\n const forward = unmarked ? carryUnmarkedPolicyList(stored) : null;\n const read = forward\n ? scope.readSelection(forward.list, UNMARKED_POLICY_CARRY_VERSION, { subject: \"policy\" })\n : scope.readSelection(stored, stamp, { subject: \"policy\" });\n const unknown = forward ? [...new Set([...read.unknown, ...forward.refused])] : read.unknown;\n\n // \"An empty term stays empty\": the reader adds `system_info` to every\n // reading, which must not turn \"names nothing\" into \"metadata only\".\n const counted = read.informationScope.filter((c) => scope.row(c)?.apps[app] === true);\n const namesARow = counted.some((c) => c !== INFORMATION_SCOPE_SYSTEM_INFO);\n // The list names the metadata row only when the reading ACCEPTED that code:\n // an unmarked list is category names, so `system` counts and the row code\n // `system_info` is refused (reported `unknown`).\n const namesMetadata = stored.some(\n (c) => (c === \"system\" || c === INFORMATION_SCOPE_SYSTEM_INFO) && !unknown.includes(c),\n );\n const permits = namesARow || namesMetadata ? read.informationScope : [];\n\n return {\n outcome: permits.length === 0 ? \"empty\" : unmarked ? \"carried\" : \"marked\",\n unmarked,\n storedVersion: unmarked ? null : stamp,\n stored,\n informationScope: read.informationScope,\n permits,\n widened: read.widened,\n retired: read.retired,\n unknown,\n unsupportedVersion: read.unsupportedVersion,\n versionRowRequired: read.versionRowRequired,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8BO,IAAM,kCAAkC;AAAA,EAC7C,YAAY;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,SAAS;AAAA,MACP;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,gBAAgB;AAAA,MACd;AAAA,MACA;AAAA,IACF;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,mBAAmB;AAAA,IACjB,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,EACT;AACF;AAGO,IAAM,gCAAgC;AAAA,EAC3C,cAAc;AAAA,EACd,gBAAgB;AAAA,IACd,YAAY,CAAC,eAAe,WAAW,YAAY,UAAU,0BAA0B;AAAA,IACvF,sBAAsB,CAAC,eAAe,QAAQ,WAAW,YAAY,SAAS,UAAU,0BAA0B,eAAe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AAO,EAAE,SAAS,SAAS,CAAC;AAC5D,QAAM,UAAU,UAAU,CAAC,GAAG,oBAAI,IAAI,CAAC,GAAG,KAAK,SAAS,GAAG,QAAQ,OAAO,CAAC,CAAC,IAAI,KAAK;AAIrF,QAAM,UAAU,KAAK,iBAAiB,OAAO,CAAC,MAAM,MAAM,IAAI,CAAC,GAAG,KAAK,GAAG,MAAM,IAAI;AACpF,QAAM,YAAY,QAAQ,KAAK,CAAC,MAAM,MAAM,6BAA6B;AAIzE,QAAM,gBAAgB,OAAO;AAAA,IAC3B,CAAC,OAAO,MAAM,YAAY,MAAM,kCAAkC,CAAC,QAAQ,SAAS,CAAC;AAAA,EACvF;AACA,QAAM,UAAU,aAAa,gBAAgB,KAAK,mBAAmB,CAAC;AAEtE,SAAO;AAAA,IACL,SAAS,QAAQ,WAAW,IAAI,UAAU,WAAW,YAAY;AAAA,IACjE;AAAA,IACA,eAAe,WAAW,OAAO;AAAA,IACjC;AAAA,IACA,kBAAkB,KAAK;AAAA,IACvB;AAAA,IACA,SAAS,KAAK;AAAA,IACd,SAAS,KAAK;AAAA,IACd;AAAA,IACA,oBAAoB,KAAK;AAAA,IACzB,oBAAoB,KAAK;AAAA,EAC3B;AACF;","names":["own","isStringList","st","level","rulePosture","named"]}
1
+ {"version":3,"sources":["../../src/sharingCeiling/index.ts","../../src/generated/sharingPlatformStarter.ts","../../src/sharingCeiling/starter.ts","../../src/sharingCeiling/chain.ts","../../src/services/informationScopeResolver.ts","../../src/sharingCeiling/coverage.ts","../../src/sharingCeiling/defaults.ts","../../src/sharingCeiling/resolve.ts","../../src/sharingCeiling/fireShareEvent.ts","../../src/sharingCeiling/storedPolicyScope.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models/sharing-ceiling\n *\n * Browser-safe entry for the Inter-Agency Sharing CEILING on the CVC-236 v4\n * tree (co-2sx): the platform starter (generated, gated canon data), the\n * cell fold, the ONE read chain (`effectiveCeiling`) and the ONE coverage\n * rule (`scopeRowWithinCeiling`, with its door and composer-mask readers), and\n * THE share resolver (`resolveShare` — the ladder, the team ceiling, the\n * Platform default as the four states; Kickoff 13, GDR § 5.79).\n * Pure TypeScript, no mongoose, no I/O, no SOT import — pass the v4 tree as\n * an information-scope resolver. Also re-exported from the package root.\n *\n * 0.41.0 adds, lifted from Thread `@thread/shared` `sharingCeiling.ts`\n * (behaviour unchanged): the account's per-purpose default\n * (`shareDefaultScopeFor`, alias `accountSharePurposePolicy`; ./defaults.ts)\n * and two coverage readers (`isPermittedByCeiling`,\n * `intersectSharingCeilingLists`; ./coverage.ts).\n *\n * 0.42.0 adds THE share resolver (`resolveShare`; ./resolve.ts).\n *\n * 0.55.0 adds event-driven sharing's pure half (`ShareEvent`,\n * `fireShareEvent`, `shareListenersFor`; ./fireShareEvent.ts).\n *\n * 0.61.0 names the account's authored purpose-specific partner rule as the\n * governing policy (`partnerPurposeRule` → the virtual `byPurpose` fork;\n * ./resolve.ts).\n *\n * 0.71.0 adds the one reading of a stored sharing policy's information-scope\n * list (`readStoredPolicyScope`; ./storedPolicyScope.ts).\n */\n\nexport * from \"./starter.js\";\nexport * from \"./chain.js\";\nexport * from \"./coverage.js\";\nexport * from \"./defaults.js\";\nexport * from \"./resolve.js\";\nexport * from \"./fireShareEvent.js\";\nexport * from \"./storedPolicyScope.js\";\n","/**\n * @htilabs/platform-common-models — the platform sharing starter (co-2sx)\n *\n * AUTO-GENERATED FILE — DO NOT EDIT BY HAND.\n * Regenerate with:\n * `python3 scripts/gen-sharing-starter.py <prototype root> <platform-prototype root>`.\n *\n * Canon (read from git objects at origin/main):\n * - htilabstech/prototype HTI-LEADS-PAVE-Thread-prototype.html @ d85f05b7\n * `HTI_SHARE_PLATFORM_STARTER` L326475-L326543\n * (scopeVersion · scopeByPurpose · counterpartyOverrides);\n * - htilabstech/platform-prototype src/data.js @ a6f1f3a5 (the contract of\n * record, GDR § 5.79): `data.sharing.scopeByPurpose` /\n * `counterpartyOverrides` L38170-L38190, and the\n * platform purpose rows `sharing.purposes[].enabled`\n * L32450-L32531;\n * - htilabstech/prototype docs/share-roi/information_scope_v4.fields.csv @ d85f05b7: the distinct\n * `row_v4` homes of its 517 fields (`fieldHomeRows`; the sentinel\n * \"rides with its record\" is not a row and is left out).\n * The two starter copies are equal (the generator refuses otherwise). GATE M\n * (`src/__tests__/sharing-starter-canon.test.ts`) holds this module equal to\n * `src/__sot__/sharingStarter.pin.json` and every code to a live, non-floor\n * CVC-236 v4 row.\n *\n * CANON GAP: `counterpartyOverrides` is keyed by canon's DEMONSTRATION partner\n * ids (palomar, okcpd, legal_aid_ok). No registry agency carries them, so the\n * seeded-partner rung binds on no real data until the platform maps them.\n */\n\n/** Where this data was taken from (provenance, not compared by `--check`). */\nexport const SHARING_PLATFORM_STARTER_SOURCE = {\n \"monolith\": {\n \"repo\": \"htilabstech/prototype\",\n \"file\": \"HTI-LEADS-PAVE-Thread-prototype.html\",\n \"sha\": \"d85f05b7\",\n \"lines\": [\n 326475,\n 326543\n ]\n },\n \"mirror\": {\n \"repo\": \"htilabstech/platform-prototype\",\n \"file\": \"src/data.js\",\n \"sha\": \"a6f1f3a5\",\n \"starterLines\": [\n 38170,\n 38190\n ],\n \"purposeLines\": [\n 32450,\n 32531\n ]\n },\n \"fieldPlacements\": {\n \"repo\": \"htilabstech/prototype\",\n \"file\": \"docs/share-roi/information_scope_v4.fields.csv\",\n \"sha\": \"d85f05b7\"\n }\n} as const;\n\n// <generated-data>\nexport const SHARING_PLATFORM_STARTER_DATA = {\n scopeVersion: 4,\n scopeByPurpose: {\n \"referral\": [\"identifying\", \"contact\", \"services\", \"system\", \"summary_needs_assessment\"],\n \"case_collaboration\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_needs_assessment\"],\n \"deconfliction\": [\"identifying\", \"system\"],\n \"mandatory_reporting\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_needs_assessment\", \"offenders.identifying\", \"offenders.risk\", \"relationships_household\", \"family\"],\n \"discretionary_share\": [\"identifying\", \"system\"],\n \"authority_reporting\": [\"identifying\", \"risk\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"offenders.identifying\", \"offenders.risk\", \"relationships_household\", \"family\"],\n \"automatic_account_share\": [\"identifying\", \"system\"],\n \"records_request\": [\"identifying\", \"system\"],\n },\n counterpartyOverrides: {\n \"palomar\": {\n \"case_collaboration\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"health_accommodation\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_mental_health_screen\", \"summary_behavioral_health_intake\", \"summary_trauma_and_coping_screen\", \"summary_needs_assessment\"],\n },\n \"okcpd\": {\n \"mandatory_reporting\": [\"identifying\", \"risk\", \"contact\", \"services\", \"notes\", \"system\", \"summary_initial_screen\", \"summary_lap\", \"summary_danger_assessment\", \"summary_stalking_assessment\", \"summary_injury_and_strangulation\", \"summary_ae_intake\", \"summary_tra\", \"summary_needs_assessment\", \"offenders.identifying\", \"offenders.risk\", \"relationships_household\", \"family\"],\n \"referral\": [\"identifying\", \"contact\", \"services\", \"system\", \"summary_needs_assessment\"],\n },\n \"legal_aid_ok\": {\n \"referral\": [\"identifying\", \"contact\", \"services\", \"notes\", \"system\", \"summary_needs_assessment\"],\n },\n },\n purposeEnabled: {\n \"referral\": true,\n \"case_collaboration\": true,\n \"deconfliction\": true,\n \"mandatory_reporting\": true,\n \"discretionary_share\": true,\n \"authority_reporting\": true,\n \"automatic_account_share\": true,\n \"records_request\": false,\n },\n fieldHomeRows: [\n \"accommodation_needs\",\n \"ad_content\",\n \"additional_ids\",\n \"addresses\",\n \"case_attachments\",\n \"case_determinations\",\n \"case_lifecycle\",\n \"case_notes\",\n \"commercial_activity\",\n \"contact_info\",\n \"demographics\",\n \"derived_risk_signals\",\n \"dob\",\n \"encounter_location\",\n \"family.health_accommodation\",\n \"family.identifying\",\n \"family.risk\",\n \"full_ae_intake\",\n \"full_behavioral_health_intake\",\n \"full_danger_assessment\",\n \"full_findings\",\n \"full_hope_scale\",\n \"full_ida\",\n \"full_initial_screen\",\n \"full_injury_and_strangulation\",\n \"full_lap\",\n \"full_mental_health_screen\",\n \"full_needs_assessment\",\n \"full_stalking_assessment\",\n \"full_tra\",\n \"full_trauma_and_coping_screen\",\n \"health_status\",\n \"identifying\",\n \"immigration_applications\",\n \"immigration_status\",\n \"instruments\",\n \"names\",\n \"network_membership\",\n \"object_identity_attributes\",\n \"offenders.risk\",\n \"others.risk\",\n \"persona_links\",\n \"phone_identifiers\",\n \"plans_goals\",\n \"priorities_safety\",\n \"relationships_household\",\n \"screen_indicators\",\n \"service_history\",\n \"session_summary\",\n \"summary_ae_intake\",\n \"summary_behavioral_health_intake\",\n \"summary_danger_assessment\",\n \"summary_findings\",\n \"summary_hope_scale\",\n \"summary_ida\",\n \"summary_initial_screen\",\n \"summary_injury_and_strangulation\",\n \"summary_lap\",\n \"summary_mental_health_screen\",\n \"summary_needs_assessment\",\n \"summary_stalking_assessment\",\n \"summary_tra\",\n \"summary_trauma_and_coping_screen\",\n \"system\",\n \"system_involvement\",\n \"victimization\",\n ],\n} as const;\n// </generated-data>\n","/**\n * The platform sharing starter — what governs a share before an account has\n * authored anything (co-2sx).\n *\n * The data is GENERATED from canon (`scripts/gen-sharing-starter.py` →\n * `src/generated/sharingPlatformStarter.ts`) and held equal to canon by GATE M\n * (`src/__tests__/sharing-starter-canon.test.ts`, against\n * `src/__sot__/sharingStarter.pin.json`). This module types it and freezes it.\n *\n * Canon: prototype `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7\n * `HTI_SHARE_PLATFORM_STARTER` L326475-L326543 (scopeVersion ·\n * scopeByPurpose · counterpartyOverrides); platform-prototype `src/data.js`\n * @ a6f1f3a `data.sharing.scopeByPurpose` / `counterpartyOverrides`\n * L38170-L38190 (the contract of record, GDR § 5.79) and the platform\n * purpose rows `sharing.purposes[].enabled` L32450-L32531 (`records_request`\n * ships `enabled: false`, L32527); prototype\n * `docs/share-roi/information_scope_v4.fields.csv` @ d85f05b7 (where each\n * field is homed, `row_v4`).\n */\n\nimport {\n SHARING_PLATFORM_STARTER_DATA,\n SHARING_PLATFORM_STARTER_SOURCE,\n} from \"../generated/sharingPlatformStarter.js\";\n\n/** The tree version every starter list and every stored ceiling list is stamped with. */\nexport const SHARING_CEILING_SCOPE_VERSION = 4 as const;\n\n/** purpose code (CVC-84 key) → v4 information-scope row codes. */\nexport type SharingPurposeLists = Readonly<Record<string, readonly string[]>>;\n\nexport interface SharingPlatformStarter {\n readonly scopeVersion: typeof SHARING_CEILING_SCOPE_VERSION;\n /** The platform per-purpose default — canon's last rung. A purpose with no row has no platform ceiling. */\n readonly scopeByPurpose: SharingPurposeLists;\n /** Platform-seeded partner rules: partner id → purpose → v4 row codes. */\n readonly counterpartyOverrides: Readonly<Record<string, SharingPurposeLists>>;\n}\n\nfunction freezeLists(lists: Readonly<Record<string, readonly string[]>>): SharingPurposeLists {\n const out: Record<string, readonly string[]> = {};\n for (const [purpose, codes] of Object.entries(lists)) out[purpose] = Object.freeze([...codes]);\n return Object.freeze(out);\n}\n\n/**\n * The platform's own sharing rules (canon's `HTI_SHARE_PLATFORM_STARTER`,\n * minus the demo-agency relationship / policy seeds). Deep-frozen.\n *\n * CANON GAP: `counterpartyOverrides` is keyed by canon's DEMONSTRATION partner\n * ids (`palomar`, `okcpd`, `legal_aid_ok`). No registry agency carries them,\n * so the seeded-partner rung binds on no real data until the platform maps\n * them. They ship as canon has them.\n */\nexport const HTI_SHARE_PLATFORM_STARTER: SharingPlatformStarter = Object.freeze({\n scopeVersion: SHARING_CEILING_SCOPE_VERSION,\n scopeByPurpose: freezeLists(SHARING_PLATFORM_STARTER_DATA.scopeByPurpose),\n counterpartyOverrides: Object.freeze(\n Object.fromEntries(\n Object.entries(SHARING_PLATFORM_STARTER_DATA.counterpartyOverrides).map(([cp, lists]) => [\n cp,\n freezeLists(lists),\n ]),\n ),\n ),\n});\n\n/**\n * The platform purpose rows' `enabled` flag (data.js `sharing.purposes`). The\n * contract of record disables a purpose whose platform row is `enabled:\n * false` unless the account overrides it `true` (data.js clamp 1,\n * L51352-L51354). `records_request` ships disabled.\n */\nexport const HTI_SHARE_PLATFORM_PURPOSE_ENABLED: Readonly<Record<string, boolean>> = Object.freeze({\n ...SHARING_PLATFORM_STARTER_DATA.purposeEnabled,\n});\n\n/**\n * The v4 rows at least one field is HOMED on (canon's field placements,\n * `information_scope_v4.fields.csv` `row_v4`). The ceiling coverage rule\n * reads it: a row with fields homed directly on it and no rest row is within\n * a ceiling only when it or an ancestor is listed.\n */\nexport const INFORMATION_SCOPE_FIELD_HOME_ROWS: ReadonlySet<string> = new Set(\n SHARING_PLATFORM_STARTER_DATA.fieldHomeRows,\n);\n\n/** Where the starter data was taken from (canon repo, file, SHA, line ranges). */\nexport const HTI_SHARE_PLATFORM_STARTER_SOURCE = SHARING_PLATFORM_STARTER_SOURCE;\n","/**\n * The Inter-Agency Sharing ceiling read chain (co-2sx): the account's stored\n * ceiling CELLS folded into canon's `sharingScopeEdits`, and the ONE chain\n * that turns them, the platform starter and the purpose switches into the\n * list a share for one recipient × purpose may carry.\n *\n * Pure, total on stored data, no I/O. Throws only on a caller's programming\n * error (a missing / reserved row key, a missing purpose).\n *\n * Canon — prototype `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7:\n * - `shareEffectiveCeiling` L327966-L328090; the per-purpose rung\n * L328040-L328082, the chain itself L328053-L328058:\n *\n * const rowKey = r.__external ? \"__external__\" : r.id;\n * const per = edits[rowKey] && edits[rowKey][opts.purposeCode];\n * const seeded = (starter.counterpartyOverrides[rowKey] || {})[opts.purposeCode];\n * const def = edits.__default__ && edits.__default__[opts.purposeCode];\n * const platformDefault = starter.scopeByPurpose[opts.purposeCode];\n * const allowed = per || seeded || def || platformDefault || null;\n *\n * - the purpose switch L327999-L328005 (an explicit `false` only).\n * Platform prototype `src/data.js` @ a6f1f3a — the contract of record\n * (GDR § 5.79), `HTI_SHARE_POLICY_API.effectiveCeiling` L51324ff:\n * - clamp 1 L51352-L51354: a purpose is off when the account switched it\n * off, OR when its platform row is `enabled: false` and the account has\n * not switched it on (`records_request`, L32527). This module follows the\n * contract of record; the monolith reads only the explicit `false`.\n * - clamp 5 L51516-L51525: the same chain as the monolith.\n * - `EXTERNAL_RECIPIENT_KEY = \"__external__\"` L50434: an off-platform\n * recipient resolves through the same chain under that key, so an\n * un-authored off-platform purpose follows the account default, then the\n * platform default (L50427-L50430).\n *\n * One JavaScript detail of canon's `||` chain is kept: an EMPTY authored\n * list is truthy, so it BINDS (it lets nothing but System metadata leave).\n *\n * STRICTER THAN CANON (ruling, co-2sx review): a purpose with no rung at all\n * fails CLOSED — `allowed: []`, rung `none` — where canon's `|| null` reads\n * no ceiling (`if (allowed && …)`, L328059). Every one of the eight core\n * CVC-84 purposes has a platform row, so `none` can only come from a caller\n * error (a misspelled purpose, a LEADS-wing purpose on a core share, a\n * replaced starter missing a row); an unknown purpose must never mean\n * \"anything may leave\".\n */\n\nimport {\n HTI_SHARE_PLATFORM_PURPOSE_ENABLED,\n HTI_SHARE_PLATFORM_STARTER,\n SHARING_CEILING_SCOPE_VERSION,\n type SharingPlatformStarter,\n} from \"./starter.js\";\n\n/** The account default row key — canon `sharingScopeEdits.__default__` (L328056; data.js L51519). */\nexport const SHARING_CEILING_DEFAULT_ROW_KEY = \"__default__\" as const;\n\n/** The off-platform / unspecified recipients row key (canon L328053; data.js `EXTERNAL_RECIPIENT_KEY`, L50434). */\nexport const SHARING_CEILING_EXTERNAL_ROW_KEY = \"__external__\" as const;\n\n/** rowKey (partner id · `__default__` · `__external__`) → purpose → v4 row codes. */\nexport type SharingScopeEdits = Readonly<\n Record<string, Readonly<Record<string, readonly string[]>>>\n>;\n\n/** The fields of one stored ceiling cell this read looks at (cells keyed agencyId × rowKey × purpose). */\nexport interface SharingCeilingCellLike {\n readonly rowKey?: unknown;\n readonly purpose?: unknown;\n readonly scopeVersion?: unknown;\n readonly informationScope?: unknown;\n}\n\nconst own = <V>(record: unknown, key: string): V | undefined =>\n record !== null &&\n typeof record === \"object\" &&\n Object.prototype.hasOwnProperty.call(record, key)\n ? ((record as Record<string, V>)[key] as V)\n : undefined;\n\nconst isStringList = (v: unknown): v is readonly string[] =>\n Array.isArray(v) && v.every((c) => typeof c === \"string\");\n\n/**\n * The list one PRESENT cell carries. A cell is a rule by being there: stamped\n * 4 with an array of strings → that list (a copy); anything else (unstamped,\n * a v3 stamp, a missing list, a non-array, a non-string entry) → `[]`, which\n * binds and covers nothing. A malformed rule never widens a share by falling\n * through to a broader rung.\n */\nexport function sharingCeilingCellList(cell: SharingCeilingCellLike): string[] {\n if (cell.scopeVersion === SHARING_CEILING_SCOPE_VERSION && isStringList(cell.informationScope)) {\n return [...cell.informationScope];\n }\n return [];\n}\n\nconst sameSet = (a: readonly string[], b: readonly string[]): boolean => {\n const sa = new Set(a);\n const sb = new Set(b);\n return sa.size === sb.size && [...sa].every((c) => sb.has(c));\n};\n\n/**\n * Fold ONE sending account's ceiling cells into canon's `sharingScopeEdits`.\n *\n * - A cell is present or absent; there is no status. An ABSENT cell is no\n * rule, and the chain falls through.\n * - A present cell binds with {@link sharingCeilingCellList}: `[]` binds; an\n * unstamped, v3-stamped or malformed list reads as `[]`.\n * - A cell without a string `rowKey` and `purpose` cannot be attributed to a\n * cell and is skipped (it is not a rule for any cell).\n * - Two cells for the same (rowKey, purpose) — the store's key forbids it —\n * keep the list when they agree as sets, else read `[]` (fail closed).\n *\n * The caller passes one account's cells; the fold does not filter by agency.\n */\nexport function sharingScopeEditsFromCells(\n cells: Iterable<SharingCeilingCellLike | null | undefined> | null | undefined,\n): SharingScopeEdits {\n const byRow = new Map<string, Map<string, string[]>>();\n if (cells === null || cells === undefined || typeof (cells as Iterable<unknown>)[Symbol.iterator] !== \"function\") {\n return {};\n }\n for (const cell of cells) {\n if (cell === null || typeof cell !== \"object\") continue;\n const { rowKey, purpose } = cell;\n if (typeof rowKey !== \"string\" || rowKey === \"\" || typeof purpose !== \"string\" || purpose === \"\") continue;\n const list = sharingCeilingCellList(cell);\n const row = byRow.get(rowKey) ?? new Map<string, string[]>();\n const prior = row.get(purpose);\n row.set(purpose, prior === undefined || sameSet(prior, list) ? list : []);\n byRow.set(rowKey, row);\n }\n // Object.fromEntries defines OWN properties, so a row key such as\n // `__proto__` is a key, never the prototype.\n return Object.fromEntries([...byRow].map(([k, row]) => [k, Object.fromEntries(row)]));\n}\n\n/** Which rung of the chain answered. */\nexport type SharingCeilingRung =\n | \"purpose_disabled\"\n | \"partner_rule\"\n | \"seeded_partner_rule\"\n | \"account_default\"\n | \"platform_default\"\n | \"none\";\n\nexport interface EffectiveSharingCeiling {\n /**\n * The v4 row codes a share may carry (read with `scopeRowWithinCeiling`).\n * `[]` when the purpose is disabled, and when no rung exists for the\n * purpose (rung `none` — fails closed; see the module header).\n */\n readonly allowed: string[];\n readonly rung: SharingCeilingRung;\n /** The purpose is switched off for the account (`allowed` is then `[]`). */\n readonly disabled: boolean;\n}\n\nexport interface EffectiveSharingCeilingInputs {\n /** The sending account's authored lists ({@link sharingScopeEditsFromCells}). */\n readonly edits: SharingScopeEdits | null | undefined;\n /** Defaults to {@link HTI_SHARE_PLATFORM_STARTER}. */\n readonly starter?: SharingPlatformStarter;\n /** The account's Share Purposes switches: `false` disables, `true` re-enables a platform-disabled purpose. */\n readonly purposeOverrides?: Readonly<Record<string, boolean | undefined>> | null;\n /**\n * Platform purpose `enabled` flags, merged OVER\n * {@link HTI_SHARE_PLATFORM_PURPOSE_ENABLED} (a purpose the map does not\n * name keeps the platform row). `null` / `undefined` = the platform rows.\n */\n readonly purposeEnabled?: Readonly<Record<string, boolean | undefined>> | null;\n}\n\n/**\n * One rung's list as the chain reads it: absent (`undefined` / `null`) falls\n * through, a list of strings binds (copied), anything else binds as `[]`.\n */\nfunction rungList(value: unknown): string[] | undefined {\n if (value === undefined || value === null) return undefined;\n return isStringList(value) ? [...value] : [];\n}\n\n/**\n * Is `purpose` switched off? The contract of record (data.js clamp 1,\n * L51352-L51354): the account's explicit `false`, or a platform row\n * `enabled: false` the account has not overridden `true`. `purposeEnabled`\n * is merged over the platform rows (a purpose it does not name, or names\n * with a non-boolean, keeps the platform row); `null` = the platform rows.\n */\nexport function isSharingPurposeDisabled(\n purpose: string,\n purposeOverrides?: Readonly<Record<string, boolean | undefined>> | null,\n purposeEnabled?: Readonly<Record<string, boolean | undefined>> | null,\n): boolean {\n const override = own<unknown>(purposeOverrides, purpose);\n if (override === false) return true;\n const callerRow = own<unknown>(purposeEnabled, purpose);\n const enabled =\n typeof callerRow === \"boolean\"\n ? callerRow\n : own<unknown>(HTI_SHARE_PLATFORM_PURPOSE_ENABLED, purpose);\n return enabled === false && override !== true;\n}\n\n/**\n * The ceiling row key for one recipient: `__external__` for an off-platform\n * recipient, else its partner id (canon L328053). Throws on a non-external\n * recipient with no id, or whose id is a reserved row key.\n */\nexport function sharingCeilingRowKey(recipient: {\n readonly external?: boolean;\n readonly id?: string | null;\n}): string {\n if (recipient.external === true) return SHARING_CEILING_EXTERNAL_ROW_KEY;\n const id = recipient.id;\n if (typeof id !== \"string\" || id === \"\") {\n throw new TypeError(\"sharing ceiling: an on-platform recipient needs a partner id\");\n }\n if (id === SHARING_CEILING_DEFAULT_ROW_KEY || id === SHARING_CEILING_EXTERNAL_ROW_KEY) {\n throw new RangeError(`sharing ceiling: \"${id}\" is a reserved row key, not a partner id`);\n }\n return id;\n}\n\n/**\n * The ceiling for one recipient row and one purpose, by canon's chain:\n *\n * purpose disabled (clamp 1) → [] (purpose_disabled)\n * edits[rowKey][purpose] (partner_rule)\n * || starter.counterpartyOverrides[rowKey][purpose] (seeded_partner_rule)\n * || edits.__default__[purpose] (account_default)\n * || starter.scopeByPurpose[purpose] (platform_default)\n * || [] (none — fails closed)\n *\n * `rowKey` is a partner id or `__external__` ({@link sharingCeilingRowKey});\n * `__default__` is refused (it is the account default, not a recipient).\n */\nexport function effectiveCeiling(\n rowKey: string,\n purpose: string,\n inputs: EffectiveSharingCeilingInputs,\n): EffectiveSharingCeiling {\n if (typeof rowKey !== \"string\" || rowKey === \"\") {\n throw new TypeError(\"sharing ceiling: rowKey must be a partner id or __external__\");\n }\n if (rowKey === SHARING_CEILING_DEFAULT_ROW_KEY) {\n throw new RangeError(\"sharing ceiling: __default__ is the account default, not a recipient row key\");\n }\n if (typeof purpose !== \"string\" || purpose === \"\") {\n throw new TypeError(\"sharing ceiling: purpose must be a share purpose code\");\n }\n const starter = inputs.starter ?? HTI_SHARE_PLATFORM_STARTER;\n if (isSharingPurposeDisabled(purpose, inputs.purposeOverrides, inputs.purposeEnabled)) {\n return { allowed: [], rung: \"purpose_disabled\", disabled: true };\n }\n const edits = inputs.edits;\n const rungs: readonly [SharingCeilingRung, unknown][] = [\n [\"partner_rule\", own(own(edits, rowKey), purpose)],\n [\"seeded_partner_rule\", own(own(starter.counterpartyOverrides, rowKey), purpose)],\n [\"account_default\", own(own(edits, SHARING_CEILING_DEFAULT_ROW_KEY), purpose)],\n [\"platform_default\", own(starter.scopeByPurpose, purpose)],\n ];\n for (const [rung, value] of rungs) {\n const allowed = rungList(value);\n if (allowed !== undefined) return { allowed, rung, disabled: false };\n }\n // Stricter than canon's `|| null` (module header): fail closed.\n return { allowed: [], rung: \"none\", disabled: false };\n}\n","/**\n * @htilabs/platform-common-models — Information scope resolver (CVC-236 v4)\n *\n * The ONE implementation of how a stored information-scope selection reads\n * against the v4 tree, so Thread and PAVE (preview and send, picker and door)\n * cannot disagree. Pure and dependency-free: no imports, no I/O, never\n * mutates its inputs. Browser-safe entry: `@htilabs/platform-common-models/information-scope`.\n *\n * Spec (canon, read-only): htilabstech/prototype\n * docs/share-roi/INFOSCOPE_V4_DEV_HANDOFF_2026-10-09.md\n * @ 7ca7e586ae487c608da657d426598a65d5b06111 (merge of the SIGNED-GRAIN\n * content commit e86dd89cdba5cbb39ccfc7fb35aff8cbf0774790, which amends\n * § 3 only and re-labels the migrations CSV; § 2, § 7, § 8 and the rows CSV\n * are unchanged from 6dab8a95 / 00179edc)\n * - § 2 rules 1–7 (\"the resolver contract — build exactly this, nothing\n * cleverer\") — every behaviour below cites its rule;\n * - § 3 the migration rules (identity · row · category · subtract ·\n * retired before v4) and `scopeVersion`; a signed release keeps its list\n * as signed and its current reading is DERIVED at read time; a retired\n * code \"stays recognisable in stored data forever\";\n * - § 7 row 6 a branch-grain pick is expanded to the ceiling's grain\n * before clamping; a sender can never widen;\n * - § 8 the enums.\n * Release grain (Crysta, 2026-10-09; SOT v2.1.0 `migrations.ruling`, quoted\n * verbatim there): \"a SIGNED RELEASE keeps the grain it was signed at ...\n * Policies and presets (agency-authored, not consent) take the merged\n * successor with a dated version row.\" Canon carries it since SIGNED-GRAIN\n * (prototype e86dd89c: `signed_release_grain: keep` on the nine `rows` merge\n * folds; handoff § 3 amended). So `readSelection` takes WHOSE list it is\n * (`subject`): a release or a share (frozen at send, § 3) naming a code on a\n * `releaseReading: \"retain\"` line at scopeVersion 3 is NOT mapped — the code\n * comes back under `retained` with its v3 field membership, for the builder\n * to deliver read-only; a policy takes the successor (`widened`) and the\n * reading says a dated version row is due. The widening identity line canon\n * leaves unmarked (`immigration_status`, `releaseReading: \"successor\"`) reads\n * as itself for every subject.\n * Reference implementation of rule-1 kind-row resolution:\n * tools/infoscope/phase4_stress_test.py `resolve_home` (same SHA).\n *\n * WHAT A SELECTION STORES. `information_scope: string[]` holds canon's scope\n * codes as canon spells them — `names`, `identifying.other`,\n * `offenders.risk` (handoff § 8: \"lowercase snake, or `<kind>.<row>`\") —\n * NOT the package's SOT keys (`offenders__risk`) and NOT seven-segment wire\n * codes (`236-016-001-002-…`). `ScopeRow.scopeCode` / `parentScopeCode` are\n * in that space; `scopeRowsFromSot` maps the SOT into it.\n *\n * ALWAYS COVERED. `system_info` and its ancestor `system` (\"System metadata —\n * always included, never a choice\", handoff § 1; the field placements home\n * the system fields on `system`) are covered by every selection.\n *\n * Two kinds of call:\n * - READS (`isCovered`, `isIncludedOnShare`, `shareVerdict`,\n * `isVisibleAtLevel`, `readSelection`, `readRestriction`,\n * `expandBranchPickToGrain`, `clampToCeiling`) are total: they never\n * throw on stored data. An unknown code, a null list or an unsupported\n * `scopeVersion` (absent, 2, or anything but 3 / 4) includes nothing\n * (fail closed). `readSelection`'s `subject` is the caller's, not stored\n * data: a missing or unknown one throws (no silent default).\n * - PICKER WRITES (`selectAll`, `deselectChild`, `expandSelectAll`), the\n * build-time `rowForSubject`, and the constructor throw on programming\n * errors (an unknown or non-selectable code, a malformed tree).\n */\n\n// ─── Constants ───────────────────────────────────────────────────────────────\n\n/** The tree version this resolver reads to (handoff § 3: \"today 3, after this round 4\"). */\nexport const INFORMATION_SCOPE_VERSION = 4 as const;\n\n/**\n * The `scopeVersion` stamps a stored list may carry and still be read: 3\n * (through the v3 → v4 table) and 4. A 2 list, and an UNSTAMPED list (which\n * is v2-era), must go through canon's conjunctive v2 → v3 table first (SOT\n * v2.1.0 `migrations.readAt` / `migrations.unstamped`: the `retired before\n * v4` lines name \"the flattened v3 reading, not an unconditional one\"); this\n * resolver reads no v2 → v3 table, so those lists are unsupported and include\n * nothing (fail closed). The one exception is not here: a stored sharing POLICY\n * list with no stamp is read by `readStoredPolicyScope` (sharing-ceiling),\n * which carries it through canon's v2 → v3 category lines first.\n */\nexport const INFORMATION_SCOPE_READABLE_VERSIONS: readonly number[] = Object.freeze([3, 4]);\n\n/** Required on every stored selection and always included (handoff § 2 rule 1; § 6). */\nexport const INFORMATION_SCOPE_SYSTEM_INFO = \"system_info\" as const;\n\n// ─── Row and migration input shapes ─────────────────────────────────────────\n\n/** A kind of other named person (handoff § 1; § 8 `kind_branch`). */\nexport type ScopePersonKind = \"offenders\" | \"family\" | \"others\";\n\n/** Whose record a record is: the client, or another named person's kind (rule 1). */\nexport type ScopeSubjectKind = \"client\" | ScopePersonKind;\n\n/** `kind_branch` (§ 8); `null` on System and Notes rows (blank in the CSV). */\nexport type ScopeKindBranch = ScopeSubjectKind | \"leads\" | null;\n\n/**\n * `row_type` (§ 8). The tree also carries `branch` (`primary_client`,\n * `other_named_persons`) and the LEADS spelling `sub-category`, which § 8's\n * list omits; both are accepted as written.\n */\nexport type ScopeRowType =\n | \"branch\"\n | \"category\"\n | \"subcategory\"\n | \"sub-category\"\n | \"person_type\"\n | \"category_rest\"\n | \"instrument row\";\n\n/** `status` (§ 8). */\nexport type ScopeRowStatus = \"as_today\" | \"new\" | \"retired\";\n\n/** `special_data_type` (§ 8, plus `evidence`, which the tree carries on `case_attachments`). */\nexport type ScopeSpecialDataType =\n | \"none\"\n | \"survivor_confidential\"\n | \"criminal_intelligence\"\n | \"evidence\";\n\n/** The three app-relevance columns (§ 4). */\nexport type ScopeApp = \"pave\" | \"thread\" | \"leads\";\nexport type ScopeApps = Readonly<Record<ScopeApp, boolean>>;\n\n/**\n * One tree row, in the selection-code space (see header). Bind the SOT with\n * `scopeRowsFromSot`. Extra fields on a caller's row type are carried through\n * (`row(code)` returns the caller's row).\n */\nexport interface ScopeRow {\n /** The code a selection stores (canon's spelling: `offenders.risk`). */\n scopeCode: string;\n parentScopeCode: string | null;\n rowType: ScopeRowType;\n kindBranch: ScopeKindBranch;\n /** On a per-kind row (`offenders.risk`): the client row it copies (`risk`). Required there. */\n kindRow?: string;\n /** App relevance (§ 4). Informational: no resolver decision reads it. */\n apps: ScopeApps;\n selectable: boolean;\n /** `shareable_default = on` (rule 4: `false` = off by default). */\n shareableDefault: boolean;\n platformFloor: boolean;\n levelFloor: 1 | 3;\n specialDataType: ScopeSpecialDataType;\n /** A `retired` row is never covered, offered or written. */\n status: ScopeRowStatus;\n replacesV3?: readonly string[];\n}\n\n/** The four migration rules of handoff § 3, plus the pre-v4 retirement reading. */\nexport type ScopeMigrationRule = \"identity\" | \"row\" | \"category\" | \"subtract\" | \"retired before v4\";\n\n/** One from-to line (selection-code space); `to` is empty for \"(nothing)\". */\nexport interface ScopeMigration {\n from: string;\n to: readonly string[];\n rule: ScopeMigrationRule;\n note?: string;\n /** The line reads WIDER than v3 did (SOT `widens: true`). A policy takes it; see `releaseReading`. */\n widens?: boolean;\n /**\n * On every `widens` line (SOT; ruling 2026-10-09, canon SIGNED-GRAIN).\n * `retain` — canon's nine merge folds (`signed_release_grain: keep`): a\n * release or share at scopeVersion 3 keeps the code at its v3 grain instead\n * of reading `to`; requires exactly one `to` and `v3Fields` / `v3Domains`.\n * `successor` — a widening identity line canon leaves unmarked\n * (`immigration_status`): every subject reads `to` (`releaseReadingNote`).\n * Absent: `to` is every subject's reading.\n */\n releaseReading?: \"retain\" | \"successor\";\n /** Why a widening line is read as its successor by a release too. */\n releaseReadingNote?: string;\n /** `successor` (SOT, on every `widens` line): a policy or preset reads `to`. */\n policyReading?: \"successor\";\n /** A `retired before v4` line (ruling 2): a stated reading only a v2-era list can need. */\n informational?: boolean;\n /**\n * On a `retain` line: the fields whose v3 home was the `from` unit (canon\n * field placements `home_unit_today`) — what a retained release delivers,\n * read-only. Field ids (`capture.hiv_status`), not scope codes. Empty = the\n * unit homed no field, so a release retaining it delivers nothing.\n */\n v3Fields?: readonly string[];\n /**\n * On a `retain` line: the distinct `assertion_domain` of `v3Fields`. CATEGORY\n * grain in v3 (`access_accommodations`, `immigration_legal_status` each span\n * every unit of their category): the field family, NOT the unit's membership.\n * Deliver by `v3Fields`.\n */\n v3Domains?: readonly string[];\n /** On a `retain` line: why the membership is what it is (an empty unit; a derivation under veto). */\n v3FieldsNote?: string;\n}\n\n// ─── Output shapes ───────────────────────────────────────────────────────────\n\n/** How one stored code was read. `unknown` = no row, no table line: it includes nothing. */\nexport type ScopeReadingRule = ScopeMigrationRule | \"unknown\";\n\nexport interface ScopeCodeReading {\n readonly from: string;\n readonly rule: ScopeReadingRule;\n /** The v4 codes it reads as; empty for a retained code (see `ScopeReading.retained`). */\n readonly reads: readonly string[];\n /** It read through a line flagged as wider than v3 (never true for a retained code). */\n readonly widens: boolean;\n /** A release or share kept it at its v3 grain (`releaseReading: \"retain\"`). */\n readonly retained: boolean;\n}\n\n/**\n * Whose stored list is being read (handoff § 3; ruling 2026-10-09):\n * - `release` — a signed ROI / release;\n * - `share` — a share, which freezes the list it was sent with AND the\n * `scopeVersion` of the release it was composed under (handoff § 3: \"A\n * share freezes the list it was sent with ... and its version\"), so it\n * reads like a release: a share frozen under a v3 release is a stamp-3\n * list and retains;\n * - `policy` — everything agency-authored: a policy, a PRESET or a PARTNER\n * RULE (canon SIGNED-GRAIN: \"policies / presets / partner rules take the\n * successor whole\"), migrated with a dated version row.\n */\nexport type ScopeReadingSubject = \"release\" | \"share\" | \"policy\";\n\nexport interface ScopeReadOptions {\n subject: ScopeReadingSubject;\n}\n\n/**\n * A stored code a release or share keeps at the grain it was signed at\n * (ruling 2026-10-09): not mapped to `successor`, not in `informationScope`.\n * The builder delivers exactly `v3Fields`, read-only — never offered, never\n * widened, never narrowed — until the survivor re-signs on v4.\n *\n * Only a STAMP-3 list retains. A v4-stamped release or share can only hold\n * live v4 codes (the picker never offers a tombstone); if one nonetheless\n * names a code on a `retain` line, that code is recognised as retired and\n * includes NOTHING (fail closed) — never its successor, and not retained.\n */\nexport interface ScopeRetainedReading {\n readonly code: string;\n /** The fields the code delivered in v3 (field ids). Empty: it delivers nothing (`note`). */\n readonly v3Fields: readonly string[];\n /** Their assertion domains — CATEGORY grain in v3, the field family; deliver by `v3Fields`. */\n readonly v3Domains: readonly string[];\n /** What a policy reads it as, and what a v4 re-signature would name. */\n readonly successor: string;\n /** Present when the membership needs explaining (an empty unit; a derivation under veto). */\n readonly note?: string;\n}\n\n/**\n * The current (v4) reading of a stored list. `stored` and `storedVersion` are\n * the list as signed, copied, never rewritten (§ 3: \"a signed release keeps\n * its list as signed, at the version signed; its current reading is derived\n * through the table at read time\").\n */\nexport interface ScopeReading {\n /** The stamp as stored; `null` when it was absent or not a number. */\n readonly storedVersion: number | null;\n readonly stored: readonly string[];\n readonly version: typeof INFORMATION_SCOPE_VERSION;\n /** The stamp is not in `INFORMATION_SCOPE_READABLE_VERSIONS`: every code reads `unknown`. */\n readonly unsupportedVersion: boolean;\n /**\n * The derived v4 list: unique, in tree order. A selection reading always\n * contains `system_info`; a restriction reading contains only what it restricts.\n */\n readonly informationScope: readonly string[];\n /** One entry per distinct stored code, in stored order. */\n readonly codes: readonly ScopeCodeReading[];\n /** Stored codes that are retired (read by `row`, `subtract` or `retired before v4`). */\n readonly retired: readonly string[];\n /** Stored codes with no live row and no table line; they include nothing. */\n readonly unknown: readonly string[];\n /** Stored codes whose reading is wider than v3's (`widens`): surface, never hide. */\n readonly widened: readonly string[];\n /** `readSelection`'s subject; `null` on a restriction reading. */\n readonly subject: ScopeReadingSubject | null;\n /** Release / share codes kept at v3 grain, in stored order (always empty for a policy). */\n readonly retained: readonly ScopeRetainedReading[];\n /**\n * A policy read across versions (stamp 3) — `readSelection` with subject\n * `policy`, and every `readRestriction` (a restriction is a policy's):\n * handoff § 3 — \"a policy is migrated with a new version row on the record,\n * dated\" — so the app writes that dated row before acting on\n * `informationScope`. `false` otherwise.\n */\n readonly versionRowRequired: boolean;\n /** Says why, when `versionRowRequired`; otherwise `null`. */\n readonly note: string | null;\n}\n\nexport type ScopeShareVerdict =\n | { readonly included: true; readonly reason: \"included\" }\n | { readonly included: false; readonly reason: \"not_covered\" | \"platform_floor\" | \"unknown_code\" }\n | {\n readonly included: false;\n readonly reason: \"off_by_default\";\n /** The off-by-default rows in the chain the account has not enabled. */\n readonly notEnabled: readonly string[];\n };\n\nexport type ScopeShareReason = ScopeShareVerdict[\"reason\"];\n\nexport interface ScopeShareOptions {\n /** The off-by-default rows the account's policy has enabled for sharing (rule 4). */\n enabledOffByDefault?: ReadonlySet<string> | readonly string[];\n}\n\nexport interface CreateInformationScopeResolverInput<R extends ScopeRow> {\n rows: readonly R[];\n migrations?: readonly ScopeMigration[];\n}\n\n/** A stored list as it may arrive from storage (reads are total). */\nexport type StoredScopeList = readonly string[] | null | undefined;\n\nexport interface InformationScopeResolver<R extends ScopeRow = ScopeRow> {\n readonly version: typeof INFORMATION_SCOPE_VERSION;\n /** Every row in input order. */\n readonly rows: readonly R[];\n row(code: string): R | undefined;\n /** The live (non-retired) children of `code`, in input order (a copy). */\n childrenOf(code: string): string[];\n /** `code` first, then its parent, up to the root (a copy). Empty for an unknown code. */\n ancestorsOf(code: string): string[];\n\n /** Rules 2 + 3. */\n isCovered(selection: StoredScopeList, code: string): boolean;\n /** Rules 2–5. */\n isIncludedOnShare(selection: StoredScopeList, code: string, options?: ScopeShareOptions): boolean;\n /** `isIncludedOnShare` with the reason, for \"held back and counted\". */\n shareVerdict(\n selection: StoredScopeList,\n code: string,\n options?: ScopeShareOptions,\n ): ScopeShareVerdict;\n /** Rule 7 (the viewing side). */\n isVisibleAtLevel(level: number, code: string): boolean;\n\n /** Rules 3 + 6: the codes a picker writes when it expands `code` (its live children, rest row included). */\n expandSelectAll(code: string): string[];\n /** Rule 6: select-all at `code` (the code itself is stored; its now-redundant descendants drop). */\n selectAll(selection: readonly string[], code: string): string[];\n /** Rules 3 + 6: de-select one child; every selected ancestor is replaced by its other children. */\n deselectChild(selection: readonly string[], childCode: string): string[];\n\n /**\n * § 3: the current v4 reading of a stored selection, for its `subject`\n * (required; throws when missing or unknown). A release or share keeps a\n * `retain` code at its v3 grain (`retained`); a policy reads the successor.\n */\n readSelection(\n list: StoredScopeList,\n scopeVersion: number | null | undefined,\n options: ScopeReadOptions,\n ): ScopeReading;\n /**\n * § 3 `subtract`: the current v4 reading of a stored RESTRICTION. A\n * restriction is a policy's, so a stamp-3 one sets `versionRowRequired`.\n */\n readRestriction(list: StoredScopeList, scopeVersion: number | null | undefined): ScopeReading;\n\n /** Rule 1: the row a record is included under, given its field's home row and its subject. */\n rowForSubject(homeRow: string, kind: ScopeSubjectKind): string;\n\n /** § 7 row 6: expand every pick that sits above the ceiling's grain into its children. */\n expandBranchPickToGrain(selection: StoredScopeList, ceiling: StoredScopeList): string[];\n /** § 7 row 6: expand, then keep only what the ceiling covers. A sender can never widen. */\n clampToCeiling(selection: StoredScopeList, ceiling: StoredScopeList): string[];\n}\n\n// ─── Pure row guards ─────────────────────────────────────────────────────────\n\n/** A row a picker offers as a choice (§ 8 `selectable`; never a retired row). */\nexport const isSelectableScopeRow = (row: ScopeRow | undefined): boolean =>\n row !== undefined && row.selectable && row.status !== \"retired\";\n\n/**\n * The `category_rest` row (rule 3): it carries the facts filed on its category,\n * and is covered with it. Since canon's re-ruling of 2026-10-18 it is an ORDINARY\n * selectable row (\"Other identifying details\"); the row type is only the marker\n * the send path reads.\n */\nexport const isScopeRestRow = (row: ScopeRow | undefined): boolean =>\n row !== undefined && row.rowType === \"category_rest\";\n\n/** One of the 28 `summary_<x>` / `full_<x>` rows (§ 8 `instrument row`). */\nexport const isScopeInstrumentRow = (row: ScopeRow | undefined): boolean =>\n row !== undefined && row.rowType === \"instrument row\";\n\n// ─── Person kind (rule 1, Phase 3 D5) ───────────────────────────────────────\n\n/**\n * Which kind of other named person someone is (handoff § 2 rule 1; § 8; Phase\n * 3 D5): \"This person caused harm\" wins; \"Eligible family member\" (asserted\n * by the advocate, never derived from the relationship) otherwise; neither →\n * `others`. A person with both switches is listed under `offenders`; the\n * caller keeps the family-member VAWA handling, which rides `efmAsserted` on\n * the person, not the kind.\n */\nexport function kindForPerson(person: {\n causedHarm: boolean;\n efmAsserted: boolean;\n}): ScopePersonKind {\n if (person.causedHarm) return \"offenders\";\n if (person.efmAsserted) return \"family\";\n return \"others\";\n}\n\n// ─── The resolver ────────────────────────────────────────────────────────────\n\nconst PERSON_KINDS: ReadonlySet<string> = new Set<ScopePersonKind>([\"offenders\", \"family\", \"others\"]);\nconst SPECIAL_DATA_TYPES: ReadonlySet<string> = new Set<ScopeSpecialDataType>([\n \"none\",\n \"survivor_confidential\",\n \"criminal_intelligence\",\n \"evidence\",\n]);\nconst MIGRATION_RULES: ReadonlySet<string> = new Set<ScopeMigrationRule>([\n \"identity\",\n \"row\",\n \"category\",\n \"subtract\",\n \"retired before v4\",\n]);\nconst RETIRED_RULES: ReadonlySet<ScopeReadingRule> = new Set<ScopeReadingRule>([\n \"row\",\n \"subtract\",\n \"retired before v4\",\n]);\n\n/** Reading precedence per code (§ 3): a stated category line, then identity, row, pre-v4. */\nconst SELECTION_PRECEDENCE: readonly ScopeMigrationRule[] = [\n \"category\",\n \"identity\",\n \"row\",\n \"retired before v4\",\n];\nconst RESTRICTION_PRECEDENCE: readonly ScopeMigrationRule[] = [\n \"subtract\",\n ...SELECTION_PRECEDENCE,\n];\n\nconst READING_SUBJECTS: ReadonlySet<string> = new Set<ScopeReadingSubject>([\n \"release\",\n \"share\",\n \"policy\",\n]);\n\n/** The `note` on a policy reading across versions (handoff § 3). */\nexport const INFORMATION_SCOPE_POLICY_VERSION_ROW_NOTE =\n \"Handoff § 3: a policy is migrated with a new version row on the record, dated, so a Member \" +\n \"Admin sees a change in history, not a silent rewrite. Write that row before acting on this \" +\n \"reading; the stored list itself is never rewritten.\";\n\nconst asList = (list: StoredScopeList): readonly string[] => (Array.isArray(list) ? list : []);\n\n/**\n * Bind the resolver to one tree (and its migration table). Throws on a\n * malformed tree: a duplicate code, a parent that is not a row, a cycle, no\n * `system_info` row, a live row whose `specialDataType` is missing or not in\n * § 8 (rule 1 routes on it — absence fails closed by refusing to bind), a\n * per-kind row without a `kindRow` that names a row, an unknown migration\n * rule, a migration successor that is not a live row, two different\n * readings for the same code and rule, or a `releaseReading: \"retain\"` line\n * without exactly one successor and its `v3Fields` / `v3Domains`.\n */\nexport function createInformationScopeResolver<R extends ScopeRow>(\n input: CreateInformationScopeResolverInput<R>,\n): InformationScopeResolver<R> {\n const rows = Object.freeze([...input.rows]);\n const byCode = new Map<string, R>();\n const order = new Map<string, number>();\n for (const r of rows) {\n if (byCode.has(r.scopeCode)) {\n throw new Error(`information scope: duplicate code \"${r.scopeCode}\"`);\n }\n byCode.set(r.scopeCode, r);\n order.set(r.scopeCode, order.size);\n }\n const isLive = (code: string): boolean => {\n const r = byCode.get(code);\n return r !== undefined && r.status !== \"retired\";\n };\n const children = new Map<string, string[]>();\n for (const r of rows) {\n if (r.status !== \"retired\" && !SPECIAL_DATA_TYPES.has(r.specialDataType)) {\n throw new Error(\n `information scope: \"${r.scopeCode}\" has specialDataType ${JSON.stringify(r.specialDataType)}`,\n );\n }\n if (r.parentScopeCode === null || r.parentScopeCode === \"\") continue;\n if (!byCode.has(r.parentScopeCode)) {\n throw new Error(\n `information scope: \"${r.scopeCode}\" names unknown parent \"${r.parentScopeCode}\"`,\n );\n }\n if (r.status === \"retired\") continue;\n const list = children.get(r.parentScopeCode) ?? [];\n list.push(r.scopeCode);\n children.set(r.parentScopeCode, list);\n }\n const ancestorCache = new Map<string, readonly string[]>();\n const ancestors = (code: string): readonly string[] => {\n const hit = ancestorCache.get(code);\n if (hit) return hit;\n const out: string[] = [];\n let cur: string | null = code;\n while (cur !== null && cur !== \"\") {\n const r = byCode.get(cur);\n if (!r) break;\n if (out.includes(cur)) throw new Error(`information scope: cycle at \"${cur}\"`);\n out.push(cur);\n cur = r.parentScopeCode;\n }\n ancestorCache.set(code, out);\n return out;\n };\n for (const r of rows) ancestors(r.scopeCode);\n if (!isLive(INFORMATION_SCOPE_SYSTEM_INFO)) {\n throw new Error(`information scope: the tree has no \"${INFORMATION_SCOPE_SYSTEM_INFO}\" row`);\n }\n /** `system_info` and its ancestors (`system`): covered by every selection. */\n const alwaysCovered: ReadonlySet<string> = new Set(ancestors(INFORMATION_SCOPE_SYSTEM_INFO));\n\n const kids = (code: string): readonly string[] => children.get(code) ?? [];\n const descendantsOf = (code: string): string[] => {\n const out: string[] = [];\n const stack = [...kids(code)];\n while (stack.length > 0) {\n const c = stack.pop() as string;\n out.push(c);\n stack.push(...kids(c));\n }\n return out;\n };\n const restRowOf = (code: string): string | undefined =>\n kids(code).find((c) => isScopeRestRow(byCode.get(c)));\n\n // Rule 1 kind rows, read off the tree: each kind's `person_type` root, and\n // each per-kind row by (kind, the client row it copies).\n const kindRoot = new Map<string, string>();\n const perKindRow = new Map<string, string>();\n for (const r of rows) {\n if (r.status === \"retired\" || r.kindBranch === null || !PERSON_KINDS.has(r.kindBranch)) continue;\n if (r.rowType === \"person_type\") {\n kindRoot.set(r.kindBranch, r.scopeCode);\n continue;\n }\n if (r.kindRow === undefined || !isLive(r.kindRow)) {\n throw new Error(\n `information scope: per-kind row \"${r.scopeCode}\" has no live kindRow (${String(r.kindRow)})`,\n );\n }\n perKindRow.set(`${r.kindBranch}\\u0000${r.kindRow}`, r.scopeCode);\n }\n\n // Migration table, indexed by code then rule.\n const migrations = new Map<string, Map<ScopeMigrationRule, ScopeMigration>>();\n for (const m of input.migrations ?? []) {\n if (!MIGRATION_RULES.has(m.rule)) {\n throw new Error(`information scope: unknown migration rule \"${m.rule}\" on \"${m.from}\"`);\n }\n for (const to of m.to) {\n if (!isLive(to)) {\n throw new Error(\n `information scope: migration \"${m.from}\" (${m.rule}) reads as \"${to}\", not a live row`,\n );\n }\n }\n if (\n m.releaseReading !== undefined &&\n m.releaseReading !== \"retain\" &&\n m.releaseReading !== \"successor\"\n ) {\n throw new Error(`information scope: \"${m.from}\" has releaseReading \"${String(m.releaseReading)}\"`);\n }\n if (m.policyReading !== undefined && m.policyReading !== \"successor\") {\n throw new Error(`information scope: \"${m.from}\" has policyReading \"${String(m.policyReading)}\"`);\n }\n if (\n m.releaseReading === \"retain\" &&\n (m.to.length !== 1 || !Array.isArray(m.v3Fields) || !Array.isArray(m.v3Domains))\n ) {\n throw new Error(\n `information scope: retained line \"${m.from}\" needs one successor and its v3Fields / v3Domains`,\n );\n }\n const perCode = migrations.get(m.from) ?? new Map<ScopeMigrationRule, ScopeMigration>();\n const prior = perCode.get(m.rule);\n if (prior && prior.to.join(\" \") !== m.to.join(\" \")) {\n throw new Error(`information scope: two \"${m.rule}\" readings for \"${m.from}\"`);\n }\n // The resolver reads only `to`, `widens` and a `retain` line's v3 membership;\n // the other line fields stay on the caller's `ScopeMigration` / the SOT.\n const retain = m.releaseReading === \"retain\" ? m : prior?.releaseReading === \"retain\" ? prior : null;\n perCode.set(m.rule, {\n from: m.from,\n rule: m.rule,\n to: Object.freeze([...m.to]),\n widens: m.widens === true || prior?.widens === true,\n ...(retain === null\n ? {}\n : {\n releaseReading: \"retain\" as const,\n v3Fields: Object.freeze([...(retain.v3Fields ?? [])]),\n v3Domains: Object.freeze([...(retain.v3Domains ?? [])]),\n ...(retain.v3FieldsNote === undefined ? {} : { v3FieldsNote: retain.v3FieldsNote }),\n }),\n });\n migrations.set(m.from, perCode);\n }\n\n /**\n * Unique, tree order for known codes, unknown codes kept after in first-seen\n * order; a selection always carries `system_info` (a restriction does not).\n */\n const normalize = (codes: Iterable<string>, withSystemInfo = true): string[] => {\n const seen = new Set<string>();\n const known: string[] = [];\n const unknown: string[] = [];\n const all = withSystemInfo ? [INFORMATION_SCOPE_SYSTEM_INFO, ...codes] : [...codes];\n for (const c of all) {\n if (seen.has(c)) continue;\n seen.add(c);\n (byCode.has(c) ? known : unknown).push(c);\n }\n known.sort((a, b) => (order.get(a) as number) - (order.get(b) as number));\n return [...known, ...unknown];\n };\n\n const requirePickable = (code: string, op: string): void => {\n if (!byCode.has(code)) throw new RangeError(`information scope ${op}: unknown code \"${code}\"`);\n if (!isSelectableScopeRow(byCode.get(code))) {\n throw new RangeError(`information scope ${op}: \"${code}\" is not selectable`);\n }\n };\n\n // Rule 2 (self or any ancestor in the flat list) + rule 3 (a record homed on a\n // category is covered when the category OR its rest row is). `system_info` and\n // `system` are always covered (header).\n const isCovered = (selection: StoredScopeList, code: string): boolean => {\n if (!isLive(code)) return false;\n if (alwaysCovered.has(code)) return true;\n const sel = new Set(asList(selection));\n if (ancestors(code).some((a) => sel.has(a))) return true;\n const rest = restRowOf(code);\n return rest !== undefined && sel.has(rest);\n };\n\n const shareVerdict = (\n selection: StoredScopeList,\n code: string,\n options: ScopeShareOptions = {},\n ): ScopeShareVerdict => {\n if (!isLive(code)) return { included: false, reason: \"unknown_code\" };\n if (!isCovered(selection, code)) return { included: false, reason: \"not_covered\" };\n const chain = ancestors(code).map((c) => byCode.get(c) as R);\n // Rule 5: the floor (or a floor ancestor) never leaves, whatever the list says.\n if (chain.some((r) => r.platformFloor)) return { included: false, reason: \"platform_floor\" };\n // Rule 4: every off-by-default row in the chain must be enabled by the account\n // (the reference runner's `included`: enabling an ancestor does not enable an\n // off-by-default child of it).\n const enabled = new Set(options.enabledOffByDefault ?? []);\n const notEnabled = chain\n .filter((r) => !r.shareableDefault && !enabled.has(r.scopeCode))\n .map((r) => r.scopeCode);\n if (notEnabled.length > 0) return { included: false, reason: \"off_by_default\", notEnabled };\n return { included: true, reason: \"included\" };\n };\n\n const expandSelectAll = (code: string): string[] => {\n if (!byCode.has(code)) throw new RangeError(`information scope expand: unknown code \"${code}\"`);\n return [...kids(code)];\n };\n\n const selectAll = (selection: readonly string[], code: string): string[] => {\n requirePickable(code, \"selectAll\");\n const drop = new Set(descendantsOf(code));\n return normalize([...selection.filter((c) => !drop.has(c)), code]);\n };\n\n const deselectChild = (selection: readonly string[], childCode: string): string[] => {\n requirePickable(childCode, \"deselectChild\");\n if (alwaysCovered.has(childCode)) {\n throw new RangeError(`information scope deselectChild: \"${childCode}\" is always included`);\n }\n const sel = new Set(selection);\n const path = ancestors(childCode); // [child, parent, …, root]\n let top = 0;\n for (let i = 1; i < path.length; i += 1) if (sel.has(path[i])) top = i;\n // Replace every selected ancestor by its OTHER children, all the way down the\n // path (rule 3: the rest row is one of those children, so it is written too).\n for (let i = 1; i <= top; i += 1) {\n sel.delete(path[i]);\n for (const c of kids(path[i])) if (c !== path[i - 1]) sel.add(c);\n }\n sel.delete(childCode);\n for (const d of descendantsOf(childCode)) sel.delete(d);\n return normalize(sel);\n };\n\n const readOne = (\n from: string,\n scopeVersion: number,\n precedence: readonly ScopeMigrationRule[],\n keepsGrain: boolean,\n ): ScopeCodeReading => {\n // A v4 list names live codes as written.\n if (scopeVersion === INFORMATION_SCOPE_VERSION && isLive(from)) {\n return { from, rule: \"identity\", reads: [from], widens: false, retained: false };\n }\n // Every other code reads through the table — including a retired code in a\n // v4 list (§ 3 (c): it \"stays recognisable in stored data forever\").\n const lines = migrations.get(from);\n if (lines) {\n for (const rule of precedence) {\n if (scopeVersion === INFORMATION_SCOPE_VERSION && (rule === \"identity\" || rule === \"category\")) {\n continue; // a v4 code that is not live has no identity reading\n }\n const line = lines.get(rule);\n if (!line) continue;\n // Ruling 2026-10-09: a release / share signed at v3 keeps the v3 grain.\n if (keepsGrain && line.releaseReading === \"retain\") {\n // A v4-stamped release / share cannot legitimately hold this tombstone\n // (never offered): recognised as retired, includes nothing — never the\n // successor (see `ScopeRetainedReading`).\n return scopeVersion === 3\n ? { from, rule, reads: [], widens: false, retained: true }\n : { from, rule, reads: [], widens: false, retained: false };\n }\n return { from, rule, reads: [...line.to], widens: line.widens === true, retained: false };\n }\n }\n return { from, rule: \"unknown\", reads: [], widens: false, retained: false };\n };\n\n const retainedOf = (c: ScopeCodeReading): ScopeRetainedReading => {\n const line = migrations.get(c.from)?.get(c.rule as ScopeMigrationRule) as ScopeMigration;\n return {\n code: c.from,\n v3Fields: [...(line.v3Fields ?? [])],\n v3Domains: [...(line.v3Domains ?? [])],\n successor: line.to[0],\n ...(line.v3FieldsNote === undefined ? {} : { note: line.v3FieldsNote }),\n };\n };\n\n const read = (\n list: StoredScopeList,\n scopeVersion: number | null | undefined,\n precedence: readonly ScopeMigrationRule[],\n subject: ScopeReadingSubject | null,\n ): ScopeReading => {\n const isRestriction = subject === null;\n const keepsGrain = subject === \"release\" || subject === \"share\";\n // A restriction is a policy's (handoff § 3 `subtract`: \"a policy that forbids\n // a code\"), so it carries the same dated-version-row signal.\n const isPolicyLike = subject === \"policy\" || isRestriction;\n const stored = [...asList(list)];\n const supported =\n typeof scopeVersion === \"number\" && INFORMATION_SCOPE_READABLE_VERSIONS.includes(scopeVersion);\n const versionRowRequired =\n isPolicyLike && supported && scopeVersion !== INFORMATION_SCOPE_VERSION;\n const codes: ScopeCodeReading[] = [];\n const seen = new Set<string>();\n for (const from of stored) {\n if (seen.has(from)) continue;\n seen.add(from);\n codes.push(\n supported\n ? readOne(from, scopeVersion as number, precedence, keepsGrain)\n : { from, rule: \"unknown\", reads: [], widens: false, retained: false },\n );\n }\n return {\n storedVersion: typeof scopeVersion === \"number\" ? scopeVersion : null,\n stored,\n version: INFORMATION_SCOPE_VERSION,\n unsupportedVersion: !supported,\n informationScope: normalize(\n codes.flatMap((c) => c.reads),\n !isRestriction,\n ),\n codes,\n retired: codes.filter((c) => RETIRED_RULES.has(c.rule)).map((c) => c.from),\n unknown: codes.filter((c) => c.rule === \"unknown\").map((c) => c.from),\n widened: codes.filter((c) => c.widens).map((c) => c.from),\n subject,\n retained: codes.filter((c) => c.retained).map(retainedOf),\n versionRowRequired,\n note: versionRowRequired ? INFORMATION_SCOPE_POLICY_VERSION_ROW_NOTE : null,\n };\n };\n\n const readSelection = (\n list: StoredScopeList,\n scopeVersion: number | null | undefined,\n options: ScopeReadOptions,\n ): ScopeReading => {\n const subject = (options as Partial<ScopeReadOptions> | undefined)?.subject;\n if (subject === undefined || !READING_SUBJECTS.has(subject)) {\n throw new TypeError(\n `information scope readSelection: options.subject must be \"release\", \"share\" or \"policy\" ` +\n `(got ${JSON.stringify(subject)}) — there is no default`,\n );\n }\n return read(list, scopeVersion, SELECTION_PRECEDENCE, subject);\n };\n\n const rowForSubject = (homeRow: string, kind: ScopeSubjectKind): string => {\n const home = byCode.get(homeRow);\n if (!home) throw new RangeError(`information scope rowForSubject: unknown home \"${homeRow}\"`);\n if (kind === \"client\") return homeRow;\n const chain = ancestors(homeRow);\n // System, Notes and the LEADS groups sit under no `branch` row: the record stays home.\n if (byCode.get(chain[chain.length - 1])?.rowType !== \"branch\") return homeRow;\n // A criminal-intelligence row under the client (`derived_risk_signals`) stays home:\n // every per-kind row is survivor_confidential, so re-branching would move CI\n // content across a handling class. The reference keeps it home the same way\n // (`resolve_home` / `leads_codes`).\n if (home.specialDataType === \"criminal_intelligence\") return homeRow;\n const root = kindRoot.get(kind);\n if (!root) throw new RangeError(`information scope rowForSubject: the tree has no \"${kind}\" kind`);\n if (chain.includes(root)) return homeRow;\n // The deepest row the kind defines for the home (D15).\n for (const anc of chain) {\n const perKind = perKindRow.get(`${kind}\\u0000${anc}`);\n if (perKind !== undefined) return perKind;\n }\n return root;\n };\n\n const expandBranchPickToGrain = (\n selection: StoredScopeList,\n ceiling: StoredScopeList,\n ): string[] => {\n const ceil = asList(ceiling);\n const ceilSet = new Set(ceil);\n const isWithin = (c: string): boolean => ancestors(c).some((a) => ceilSet.has(a));\n const isAbove = (c: string): boolean => ceil.some((k) => k !== c && ancestors(k).includes(c));\n const out: string[] = [];\n const stack = [...asList(selection)];\n while (stack.length > 0) {\n const c = stack.pop() as string;\n if (isLive(c) && !isWithin(c) && isAbove(c)) stack.push(...kids(c));\n else out.push(c);\n }\n return normalize(out);\n };\n\n const clampToCeiling = (selection: StoredScopeList, ceiling: StoredScopeList): string[] => {\n const ceil = new Set(asList(ceiling));\n return normalize(\n expandBranchPickToGrain(selection, ceiling).filter(\n (c) => isLive(c) && ancestors(c).some((a) => ceil.has(a)),\n ),\n );\n };\n\n return {\n version: INFORMATION_SCOPE_VERSION,\n rows,\n row: (code) => byCode.get(code),\n childrenOf: (code) => [...kids(code)],\n ancestorsOf: (code) => [...ancestors(code)],\n isCovered,\n isIncludedOnShare: (selection, code, options) =>\n shareVerdict(selection, code, options).included,\n shareVerdict,\n // Rule 7: the lowest internal viewing level that sees the row. Level 2\n // (autocomplete) sees the level-1 stub (§ 5). Sharing ignores this.\n isVisibleAtLevel: (level, code) =>\n typeof level === \"number\" && isLive(code) && level >= (byCode.get(code) as R).levelFloor,\n expandSelectAll,\n selectAll,\n deselectChild,\n readSelection,\n readRestriction: (list, scopeVersion) => read(list, scopeVersion, RESTRICTION_PRECEDENCE, null),\n rowForSubject,\n expandBranchPickToGrain,\n clampToCeiling,\n };\n}\n","/**\n * THE ceiling coverage rule (co-2sx): ONE answer to \"does this ceiling list\n * let this v4 row leave?\", read the same way by the composer's mask\n * ({@link rowsOutsideCeiling} / {@link rowsExpandedByCeiling} /\n * {@link maskSelectionToCeiling}) and by the send door\n * ({@link rowsOverCeiling}), so the list a composer masks to is the list a\n * door accepts (pinned by a property test over every live row × generated\n * ceilings).\n *\n * A row `code` is WITHIN a ceiling list when\n * 1. it or an ANCESTOR is listed — canon's dumb read, `scopeListCovers`\n * (prototype `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7\n * L327953-L327964); or\n * 2. it carries no content of its own (below), has at least one coverage\n * child, and EVERY coverage child is within (recursively) — canon's door\n * expands a branch / kind pick to the grain the ceiling is written at\n * before clamping (`shareItemsWithinCeiling`, L328204-L328230), so a\n * ceiling naming every child of `identifying` but not `identifying`\n * permits the `identifying` pick.\n *\n * OWN CONTENT (ruling, strict rule 2): a row with fields HOMED directly on it\n * (canon's field placements, {@link INFORMATION_SCOPE_FIELD_HOME_ROWS}; a\n * per-kind row also holds every client home rule 1 routes to it — the deepest\n * per-kind row whose `kindRow` is the home or an ancestor of it, so\n * `contact_info` lands on `offenders.contact`) and NO rest row is within ONLY when it or an ancestor is\n * listed — listing its children does not carry its own fields. Examples:\n * `instruments` (`capture.assessment*`) and `commercial_activity`. A row with\n * a rest row (`identifying` + `identifying.other`) keeps rule 2: its own\n * fields are its rest row's.\n *\n * A COVERAGE child is live, not under the platform safety floor (never\n * shared) and not System metadata (always rides). A row is LIVE when it and\n * every row on its ancestor path are non-retired; a code outside the tree, or\n * not live, is never within. Under a bound ceiling a row under the platform\n * floor is within only when the list names it itself, never through a listed\n * ancestor.\n *\n * Deliberately NOT the resolver's `isCovered`, under which a listed rest row\n * (`identifying.other`) would cover its whole category.\n *\n * `allowed`: a list (or set) of v4 row codes; `null` is NO ceiling (canon\n * `if (allowed && …)`), under which every live row is within. Any other value\n * reads as `[]` (fail closed). `effectiveCeiling` never answers `null`.\n *\n * The tree arrives as an information-scope resolver (or anything with its\n * four read methods), so this module carries no SOT and no I/O.\n */\n\nimport {\n INFORMATION_SCOPE_SYSTEM_INFO,\n type InformationScopeResolver,\n} from \"../services/informationScopeResolver.js\";\nimport { INFORMATION_SCOPE_FIELD_HOME_ROWS } from \"./starter.js\";\n\n/** What the coverage rule reads of a tree. */\nexport type SharingCeilingScope = Pick<\n InformationScopeResolver,\n \"rows\" | \"row\" | \"childrenOf\" | \"ancestorsOf\"\n>;\n\n/** A ceiling list as callers hold it; `null` = no ceiling. */\nexport type SharingCeilingAllowed = readonly string[] | ReadonlySet<string> | null;\n\ninterface TreeFacts {\n readonly isLive: (code: string) => boolean;\n readonly isSystem: (code: string) => boolean;\n readonly underFloor: (code: string) => boolean;\n readonly isCoverageRow: (code: string) => boolean;\n readonly coverageChildren: (code: string) => readonly string[];\n readonly hasOwnContent: (code: string) => boolean;\n}\n\nconst factsCache = new WeakMap<object, TreeFacts>();\n\nfunction memoize<V>(fn: (code: string) => V): (code: string) => V {\n const memo = new Map<string, V>();\n return (code) => {\n if (memo.has(code)) return memo.get(code) as V;\n const out = fn(code);\n memo.set(code, out);\n return out;\n };\n}\n\nfunction treeFacts(scope: SharingCeilingScope): TreeFacts {\n const hit = factsCache.get(scope);\n if (hit) return hit;\n const systemPath = scope.ancestorsOf(INFORMATION_SCOPE_SYSTEM_INFO);\n const systemRoot = systemPath.length > 0 ? systemPath[systemPath.length - 1] : undefined;\n const isLive = memoize(\n (code) =>\n scope.row(code) !== undefined &&\n scope.ancestorsOf(code).every((c) => scope.row(c)?.status !== \"retired\"),\n );\n const isSystem = memoize(\n (code) => systemRoot !== undefined && scope.ancestorsOf(code).includes(systemRoot),\n );\n const underFloor = memoize((code) =>\n scope.ancestorsOf(code).some((c) => scope.row(c)?.platformFloor === true),\n );\n const isCoverageRow = memoize((code) => isLive(code) && !isSystem(code) && !underFloor(code));\n const coverageChildren = memoize((code) =>\n Object.freeze(scope.childrenOf(code).filter(isCoverageRow)),\n );\n // Rule 1, read the way canon's share builder reads it (prototype\n // `HTI-LEADS-PAVE-Thread-prototype.html` @ 72d045ab `resolveHome`; the\n // resolver's `rowForSubject`): a field homed on a client row rides, for\n // another person, the DEEPEST per-kind row whose `kindRow` is that home or\n // one of its ancestors. So `contact_info` (another person's phones, emails,\n // contact log — fields.csv `capture.contact_link_role`, rule 1) rides\n // `offenders.contact`, whose `kindRow` is `contact`, not `contact_info`.\n const kindHomed = kindHomedRows(scope);\n const hasOwnContent = memoize((code) => {\n const row = scope.row(code);\n if (row === undefined) return false;\n const homed = INFORMATION_SCOPE_FIELD_HOME_ROWS.has(code) || kindHomed.has(code);\n if (!homed) return false;\n // A rest row stands for the row's own fields; then rule 2 still applies.\n return !scope\n .childrenOf(code)\n .some((c) => scope.row(c)?.rowType === \"category_rest\" && isLive(c));\n });\n const facts: TreeFacts = {\n isLive,\n isSystem,\n underFloor,\n isCoverageRow,\n coverageChildren,\n hasOwnContent,\n };\n factsCache.set(scope, facts);\n return facts;\n}\n\n/**\n * The per-kind rows a client-row field home resolves to (rule 1). Mirrors the\n * resolver's `rowForSubject`: a home outside the client branch, under a kind\n * already, or holding criminal intelligence stays home; otherwise each kind\n * takes the deepest per-kind row whose `kindRow` is the home or an ancestor\n * of it. Retired rows are skipped.\n */\nfunction kindHomedRows(scope: SharingCeilingScope): ReadonlySet<string> {\n const perKind = new Map<string, string>(); // `${kind}\\u0000${kindRow}` → code\n const kinds = new Map<string, string>(); // kind → person_type root\n for (const r of scope.rows) {\n if (r.status === \"retired\" || r.kindBranch === null) continue;\n if (r.rowType === \"person_type\") kinds.set(r.kindBranch, r.scopeCode);\n else if (r.kindRow !== undefined) perKind.set(`${r.kindBranch}\\u0000${r.kindRow}`, r.scopeCode);\n }\n const out = new Set<string>();\n for (const home of INFORMATION_SCOPE_FIELD_HOME_ROWS) {\n const row = scope.row(home);\n if (row === undefined || row.specialDataType === \"criminal_intelligence\") continue;\n const chain = scope.ancestorsOf(home);\n if (scope.row(chain[chain.length - 1] as string)?.rowType !== \"branch\") continue;\n for (const [kind, root] of kinds) {\n if (chain.includes(root)) continue;\n const hit = chain.map((c) => perKind.get(`${kind}\\u0000${c}`)).find((c) => c !== undefined);\n if (hit !== undefined) out.add(hit);\n }\n }\n return out;\n}\n\nfunction asCeilingSet(allowed: unknown): ReadonlySet<string> | null {\n if (allowed === null) return null;\n if (allowed instanceof Set) return allowed as ReadonlySet<string>;\n if (Array.isArray(allowed)) {\n return new Set(allowed.filter((c): c is string => typeof c === \"string\"));\n }\n return new Set(); // malformed: covers nothing\n}\n\n/**\n * Does the coverage rule require `code` for its parent to be covered? Live,\n * not under the platform floor, not System metadata.\n */\nexport function isCeilingCoverageRow(scope: SharingCeilingScope, code: string): boolean {\n return treeFacts(scope).isCoverageRow(code);\n}\n\n/**\n * Does `code` carry content of its own that children-only coverage cannot\n * carry (fields homed directly on it, no rest row)? See the module header.\n */\nexport function hasOwnScopeContent(scope: SharingCeilingScope, code: string): boolean {\n return treeFacts(scope).hasOwnContent(code);\n}\n\n/**\n * The coverage of ONE ceiling list, memoised per row — build it once and ask\n * it about many rows. See the module header for the rule.\n */\nexport function ceilingCoverage(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n): (code: string) => boolean {\n const facts = treeFacts(scope);\n const set = asCeilingSet(allowed);\n const memo = new Map<string, boolean>();\n const within = (code: string): boolean => {\n const hit = memo.get(code);\n if (hit !== undefined) return hit;\n let out: boolean;\n if (!facts.isLive(code)) out = false;\n else if (set === null) out = true;\n // A row under the platform safety floor never leaves on a bound ceiling,\n // even when an ancestor is listed (a per-kind Contact & safety row is\n // listed whole for its own fields; its safe locations stay home).\n else if (facts.underFloor(code)) out = set.has(code);\n else if (scope.ancestorsOf(code).some((c) => set.has(c))) out = true;\n else if (facts.hasOwnContent(code)) out = false;\n else {\n const kids = facts.coverageChildren(code);\n out = kids.length > 0 && kids.every(within);\n }\n memo.set(code, out);\n return out;\n };\n return within;\n}\n\n/** THE coverage rule for one row (see the module header). */\nexport function scopeRowWithinCeiling(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n code: string,\n): boolean {\n return ceilingCoverage(scope, allowed)(code);\n}\n\n/**\n * The DOOR reader: the codes of a declared list the ceiling does not let\n * leave, in list order, each once. `system_info` and every System-metadata\n * row ride regardless (canon L327974), and rows under the platform floor are\n * never included on any share, so neither is reported. A code outside the\n * tree, or not live, is reported (fail closed).\n */\nexport function rowsOverCeiling(\n scope: SharingCeilingScope,\n declared: readonly string[] | null | undefined,\n allowed: SharingCeilingAllowed,\n): string[] {\n const facts = treeFacts(scope);\n const within = ceilingCoverage(scope, allowed);\n const out: string[] = [];\n for (const code of new Set(Array.isArray(declared) ? declared : [])) {\n if (code === INFORMATION_SCOPE_SYSTEM_INFO) continue;\n if (!facts.isLive(code)) {\n out.push(code);\n continue;\n }\n if (facts.isSystem(code) || facts.underFloor(code)) continue;\n if (!within(code)) out.push(code);\n }\n return out;\n}\n\ninterface CeilingWalk {\n /** Rows wholly outside the ceiling, each at its highest such grain. */\n readonly outside: string[];\n /** Own-content rows not within that hold within rows: a pick of one is its children. */\n readonly expanded: string[];\n}\n\n/** One top-down walk of the live tree against a ceiling (System metadata skipped). */\nfunction walkCeiling(scope: SharingCeilingScope, allowed: SharingCeilingAllowed): CeilingWalk {\n const facts = treeFacts(scope);\n if (asCeilingSet(allowed) === null) return { outside: [], expanded: [] };\n const within = ceilingCoverage(scope, allowed);\n const holdsMemo = new Map<string, boolean>();\n const holdsWithin = (code: string): boolean => {\n const hit = holdsMemo.get(code);\n if (hit !== undefined) return hit;\n // Only a coverage row counts as content held beneath: a listed FLOOR row\n // (never included) does not make its parent partly permitted.\n const out = scope\n .childrenOf(code)\n .some((c) => (facts.isCoverageRow(c) && within(c)) || holdsWithin(c));\n holdsMemo.set(code, out);\n return out;\n };\n const outside: string[] = [];\n const expanded: string[] = [];\n const visit = (code: string): void => {\n if (!facts.isLive(code) || within(code)) return;\n if (!holdsWithin(code)) {\n outside.push(code);\n return;\n }\n if (facts.hasOwnContent(code)) expanded.push(code);\n for (const child of scope.childrenOf(code)) visit(child);\n };\n for (const r of scope.rows) {\n if (r.parentScopeCode !== null && r.parentScopeCode !== \"\") continue;\n if (facts.isSystem(r.scopeCode)) continue;\n visit(r.scopeCode);\n }\n return { outside, expanded };\n}\n\n/**\n * The COMPOSER-MASK reader: the rows a ceiling restricts, each at the\n * highest grain that is wholly outside it — a row not within and holding no\n * within coverage row beneath. A row that is not within but holds one that\n * is, is not restricted itself; its children are walked. System metadata is\n * never restricted. `null` (no ceiling) restricts nothing.\n */\nexport function rowsOutsideCeiling(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n): string[] {\n return walkCeiling(scope, allowed).outside;\n}\n\n/**\n * The rows with content of their own (strict rule 2) that are not within the\n * ceiling but hold rows that are: the row itself cannot be sent, so a pick of\n * it reads as a pick of its children (then masked). Top-down order.\n */\nexport function rowsExpandedByCeiling(\n scope: SharingCeilingScope,\n allowed: SharingCeilingAllowed,\n): string[] {\n return walkCeiling(scope, allowed).expanded;\n}\n\n/** `system_info` first, then each code once, in order. */\nfunction withSystemInfo(codes: readonly string[]): string[] {\n return [...new Set([INFORMATION_SCOPE_SYSTEM_INFO, ...codes])];\n}\n\n/**\n * Take one row out of a selection at its own grain: drop it and everything\n * beneath it, and replace each selected ancestor by its other children, all\n * the way down the path (a category's rest row is one of those children, so\n * it is written too).\n */\nfunction subtractRow(\n scope: SharingCeilingScope,\n selection: readonly string[],\n code: string,\n): string[] {\n const path = scope.ancestorsOf(code); // code first, then up to the root\n let sel = selection.filter((c) => !scope.ancestorsOf(c).includes(code));\n for (;;) {\n const coverAt = path.findIndex((c, i) => i > 0 && sel.includes(c));\n if (coverAt === -1) break;\n sel = sel.filter((c) => c !== path[coverAt]);\n for (let i = coverAt; i >= 1; i -= 1) {\n const parent = path[i] as string;\n const onPath = path[i - 1];\n for (const child of scope.childrenOf(parent)) {\n if (child !== onPath && !sel.includes(child)) sel.push(child);\n }\n }\n }\n return sel;\n}\n\n/**\n * The COMPOSER MASK: a selection with every row the ceiling restricts taken\n * out at its own grain. First each covered own-content row the ceiling does\n * not permit ({@link rowsExpandedByCeiling}) is replaced by its children,\n * then every row wholly outside ({@link rowsOutsideCeiling}) is subtracted.\n * Only live rows survive (plus `system_info`, always first). A row within\n * the ceiling is never removed, and {@link rowsOverCeiling} accepts every\n * result.\n */\nexport function maskSelectionToCeiling(\n scope: SharingCeilingScope,\n selection: readonly string[] | null | undefined,\n allowed: SharingCeilingAllowed,\n): string[] {\n const facts = treeFacts(scope);\n const { outside, expanded } = walkCeiling(scope, allowed);\n let sel = (Array.isArray(selection) ? selection : []).filter(\n (c): c is string => typeof c === \"string\" && facts.isLive(c),\n );\n for (const code of expanded) {\n if (!scope.ancestorsOf(code).some((c) => sel.includes(c))) continue;\n sel = subtractRow(scope, sel, code);\n for (const child of scope.childrenOf(code)) if (!sel.includes(child)) sel.push(child);\n }\n for (const code of outside) sel = subtractRow(scope, sel, code);\n // A floor row named in the selection never stays, even beneath a listed\n // ancestor (`offenders.safe_locations` under a listed `offenders.contact`).\n if (asCeilingSet(allowed) !== null) {\n const within = ceilingCoverage(scope, allowed);\n sel = sel.filter((c) => !facts.underFloor(c) || within(c));\n }\n // Siblings put back by subtractRow / the expansion come from childrenOf,\n // which a caller's tree may populate with retired rows: keep live ones only.\n return withSystemInfo(sel.filter((c) => facts.isLive(c)));\n}\n\n// ─── Two readers of the coverage rule, lifted from Thread ───────────────────\n//\n// Lifted unchanged from Thread `@thread/shared` `sharingCeiling.ts`\n// L432-L480 @ thread develop f021be2. The one change is the tree: Thread\n// bound its own `INFORMATION_SCOPE_RESOLVER`; here the caller passes it as\n// `scope`, the first argument, like every other reader in this file (this\n// subpath carries no SOT). Thread keeps its two-argument names as wrappers\n// that bind its resolver; PAVE's twin `intersectSharingCeilingLists`\n// (pave-2.0 `packages/domain/src/sharingScopeCeiling.ts`) does the same.\n\n/**\n * The part of a ceiling a scope check reads: the v4 rows that may leave, or\n * `null` when no ceiling binds.\n */\nexport interface SharingScopeCeiling {\n readonly allowed: ReadonlySet<string> | readonly string[] | null;\n}\n\n/**\n * Whether the ceiling permits one v4 ROW — the coverage rule\n * ({@link scopeRowWithinCeiling}).\n *\n * - `null` ceiling or `allowed: null` ⇒ permitted (no ceiling binds).\n * - System metadata (any row under `system`) ⇒ permitted (GDR 5.17\n * clause 5 — provenance rides).\n * - A code outside the tree ⇒ NOT permitted (fail closed).\n */\nexport function isPermittedByCeiling(\n scope: SharingCeilingScope,\n ceiling: SharingScopeCeiling | null,\n code: string,\n): boolean {\n if (ceiling === null || ceiling.allowed === null) return true;\n if (scope.ancestorsOf(code).includes(\"system\")) {\n return true;\n }\n if (scope.row(code) === undefined) return false;\n return scopeRowWithinCeiling(scope, ceiling.allowed, code);\n}\n\n/**\n * What BOTH of two ceiling lists permit: a row of either list that is within\n * the other (the coverage rule). A composer intersects its selected\n * recipients' ceilings with this — one selection serves every recipient, so\n * the narrowest wins.\n */\nexport function intersectSharingCeilingLists(\n scope: SharingCeilingScope,\n a: ReadonlySet<string> | readonly string[],\n b: ReadonlySet<string> | readonly string[],\n): string[] {\n const left = [...a];\n const right = [...b];\n const within = (list: readonly string[], code: string): boolean =>\n scopeRowWithinCeiling(scope, list, code);\n return [\n ...new Set([\n ...left.filter((code) => within(right, code)),\n ...right.filter((code) => within(left, code)),\n ]),\n ];\n}\n","/**\n * The account's per-purpose DEFAULT share scope (C12b) — the prototype's\n * `shareDefaultScopeFor`: the v4 rows a share of one purpose carries by the\n * ACCOUNT's rule, before any recipient is named. The account's own\n * `__default__` cell for the purpose, else the platform starter's\n * `scopeByPurpose[purpose]`; `[]` when the purpose is off.\n *\n * Lifted unchanged from Thread `@thread/shared` `sharingCeiling.ts`\n * L383-L427 @ thread develop f021be2 (`accountSharePurposePolicy`), so Thread\n * and PAVE compute it once. Exported under the prototype's name\n * {@link shareDefaultScopeFor}; {@link accountSharePurposePolicy} is the same\n * function, kept so Thread's call sites do not change.\n *\n * It is the chain's `account_default` → `platform_default` tail\n * (`effectiveCeiling`, ./chain.ts) — what every recipient without a partner\n * rule is held to: the composer's and the release wizard's \"your account's\n * default for <purpose>\" preset. Canon: prototype\n * `HTI-LEADS-PAVE-Thread-prototype.html` @ d85f05b7 `shareEffectiveCeiling`\n * L327966-L328090 (the chain's tail L328053-L328058); the off reading is\n * clamp 1 (platform-prototype `src/data.js` @ a6f1f3a L51352-L51354).\n *\n * Pure: no mongoose, no I/O, no SOT import.\n */\n\nimport {\n SHARING_CEILING_DEFAULT_ROW_KEY,\n isSharingPurposeDisabled,\n type SharingScopeEdits,\n} from \"./chain.js\";\nimport {\n HTI_SHARE_PLATFORM_STARTER,\n type SharingPlatformStarter,\n} from \"./starter.js\";\n\n/**\n * The account's standing on ONE share purpose, before any recipient is named\n * — what the composer's purpose card shows beside each pill:\n *\n * - `off`: the purpose is switched off for the account (canon's clamp 1 —\n * the platform row's `enabled: false`, or the account's own Share\n * Purposes switch once the platform writes one; `isSharingPurposeDisabled`\n * is the package's one test). An off purpose binds `[]` at every door, so\n * the card renders it DISABLED-WITH-REASON (Terry ruling 2026-08-12:\n * policy exclusions on this surface stay visible).\n * - `accountDefault`: the v4 rows a share of that purpose carries by the\n * ACCOUNT'S rule — the `__default__` cell the account authored, else the\n * platform default (`starter.scopeByPurpose`); `[]` when off.\n *\n * `edits === null` (the store could not be read) → `[]` for every purpose,\n * fail closed, like the ceiling itself.\n */\nexport interface AccountSharePurposePolicy {\n readonly off: boolean;\n readonly accountDefault: readonly string[];\n}\n\n/** The options {@link shareDefaultScopeFor} reads. */\nexport interface ShareDefaultScopeOptions {\n readonly starter?: SharingPlatformStarter;\n /** The account's Share Purposes switches, when the platform writes them. */\n readonly purposeOverrides?: Readonly<\n Record<string, boolean | undefined>\n > | null;\n}\n\n/**\n * The account's default scope for `purpose` (see the module note). Total:\n * never throws; a non-string entry in a stored list is dropped.\n */\nexport function shareDefaultScopeFor(\n edits: SharingScopeEdits | null | undefined,\n purpose: string,\n opts: ShareDefaultScopeOptions = {},\n): AccountSharePurposePolicy {\n const off = isSharingPurposeDisabled(purpose, opts.purposeOverrides ?? null);\n if (off || edits === null || edits === undefined) {\n return { off, accountDefault: [] };\n }\n const starter = opts.starter ?? HTI_SHARE_PLATFORM_STARTER;\n const authored = (\n edits as Readonly<Record<string, Readonly<Record<string, unknown>>>>\n )[SHARING_CEILING_DEFAULT_ROW_KEY]?.[purpose];\n if (Array.isArray(authored)) {\n return {\n off,\n accountDefault: authored.filter(\n (v): v is string => typeof v === \"string\",\n ),\n };\n }\n const platform = (\n starter.scopeByPurpose as Readonly<Record<string, unknown>>\n )[purpose];\n return {\n off,\n accountDefault: Array.isArray(platform)\n ? platform.filter((v): v is string => typeof v === \"string\")\n : [],\n };\n}\n\n/**\n * Thread's name for {@link shareDefaultScopeFor} — the SAME function (not a\n * wrapper), kept so `@thread/shared` call sites do not change.\n */\nexport const accountSharePurposePolicy = shareDefaultScopeFor;\n","/**\n * THE share resolver (Kickoff 13, GDR § 5.79 \"ONE resolver per runtime\"): the\n * one pure read Thread and PAVE call to learn, for one sender (account +\n * team) × one recipient × one purpose, which POLICY governs and at which\n * level, the posture, whether the share is excluded as a whole, and which\n * information-scope categories may leave — with the sending team's own policy\n * as a CEILING, the Platform default read as the FOUR STATES, and reports\n * never blocked at the policy or partner layer. Every answer names policy ·\n * version · level (CAM invariant 17).\n *\n * Contract of record: platform-prototype `src/data.js` @ becfab4 (K13-18) —\n * - `governingPolicyFor` L54533ff: the team row, `hit()` (one policy =\n * one purpose; a policy that ANSWERS shares received never governs a\n * send), the ladder (pair row → [inside: account default for inside →\n * the platform's inside starter] → relationship → account default →\n * Platform default), `done()` (the sending team's own policy rides as a\n * ceiling on every rung's answer when it is not itself the governing one);\n * - `effectiveCeiling` L54879ff: the posture composition (L54977-L54994;\n * `POSTURE_RANK` L53645), the whole-share exclusion, which list binds\n * (K13-12, L55121-L55130) and the per-category clamps 0 · 4 · 4a · 4b · 5 ·\n * 5b · 5c · 5d · the group flip (L55140ff; 4 at L55165, 4b at L55185);\n * - `platformStarterScope` / `starterDerivedState` L53708-L53760: the\n * Platform default as the four CVC-133 states (`SHARE_STATE_KEYS` L53697,\n * `SCOPE_LOCK_LABEL` L53698);\n * - `scopeListCovers` L54696-L54706 (HANDOFF K13-14: a stored list may name\n * a category, a kind above it or a row of it — never read it with a flat\n * `indexOf`).\n * Behavioural specs: `tools/smoke/flows/one-resolver-k13.js` (A–G) and\n * `sharing-four-state-k13.js` (A–C); the test suite beside this file carries\n * their vectors.\n *\n * The `byPurpose` virtual fork (since 0.61.0; data.js `governingPolicyFor` @ aa2c63a\n * L55006-L55028, \"An authored byPurpose sub-row with no explicit attachment is the\n * ruled fork-with-one-attachment\"): when no policy is attached to the relationship\n * for the purpose but the account has AUTHORED a purpose-specific rule for the\n * partner (`partnerPurposeRule`), the governing policy is NAMED as that rule —\n * `pol-bp-<partner>-<purpose>`, level `relationship`, `virtual: true`. As in data.js\n * (`effectiveCeiling` L55376: \"The virtual byPurpose fork adds NAMING only\"), the\n * ladder names ONE policy, so the account default beneath it is not consulted for posture\n * (data.js L55391 skips a virtual policy) and its list does not bind as 5b (L55539). Whenever\n * a rule is present the posture STARTS from the rule (L55342 — `relationshipPosture` is then\n * ignored), whatever the ladder named. SCOPE under the fork is clamp 5's (L55504): the legacy\n * cell chain (`legacyCeiling`), else an EDITED account default's category list (data.js\n * projects it into `sharingScopeEdits[__default__]`, `projectScopeEdits` L55163-L55164), else\n * the Platform default's starting scope; that default's field groups (`infoScopeItems`) bind\n * too — deliberately narrower than data.js, whose 5c (L55658) drops them under the fork. When\n * the rule itself blocked, the share reads data.js's sentences (L55436-L55448); when an\n * attached policy blocked, the policy is named (a deliberate correction — data.js names the\n * rule there). A rule for `__external__` is ignored (L55333: scope-only).\n *\n * Deliberately NOT here (prototype storage artefacts or relationship-row\n * facts the caller holds): the legacy\n * `sharingPolicies` narrowing rows (#451 moved them onto cards), the partner\n * row's direction / team-scoped gates and item `restrictions`, deconfliction /\n * viewing / release / routing species. The legacy cell chain (`sharingScopeEdits`\n * → `effectiveCeiling` in chain.ts) arrives as `legacyCeiling` and is applied\n * exactly where data.js applies it (clamp 5; review M6: seeded partner rules\n * stay a ceiling even over an authored policy).\n *\n * Fail-closed conventions (this module's, stricter than canon where noted):\n * - an unknown purpose (no Platform default supplied) governs nothing —\n * `governing: null`, every category withheld, `excluded` says why (canon's\n * `governingPolicyFor` returns null and the read leaks unrestricted; the\n * prototype masks it upstream with `purposeIsLive`);\n * - a document's `infoScope: null` OR an absent `infoScope` is \"no category\n * list\" and is honoured, exactly as data.js reads it\n * (`Array.isArray(gp.policy.infoScope) ? … : null`, L54979 / L55124 —\n * the inside starter and a field-limits-only team ceiling are written\n * that way, flow G); an explicit `[]` binds an empty list (canon too);\n * a value that is present but is not a list of strings reads as `[]`\n * (stricter than canon, which reads it as no list);\n * - the account's Information Scope (clamps 4 / 4b) starts from the codebook:\n * a CVC-236 heightened category or row (`shareableDefault: false` —\n * immigration & legal status, the full instrument narratives) stays OFF\n * until the account turns it on (`accountScope.categoriesOn` / `rowsOn`),\n * exactly as data.js reads `cg ? cg.shareable : seedG.shareable` and\n * `saved4b ? saved4b.shareable : it.shareable` — a caller that passes no\n * `accountScope` gets the codebook's defaults, never everything;\n * - an assignment whose `scope` is not one of the five kinds is skipped; two live\n * documents on one cell — a store's key forbids it — resolve to the LATER one in\n * `policies` (deterministic), and a duplicated id to the later document;\n * - a tree with no System-metadata category has nothing Required by itself, and an\n * excluded share then lets nothing through at all.\n *\n * Pure: no I/O, no SOT import, copies never live references.\n */\n\nimport type { EffectiveSharingCeiling } from \"./chain.js\";\nimport { hasOwnScopeContent, type SharingCeilingScope } from \"./coverage.js\";\nimport {\n HTI_SHARE_PLATFORM_STARTER,\n type SharingPlatformStarter,\n} from \"./starter.js\";\n\n// ─── Vocabulary ──────────────────────────────────────────────────────────────\n\n/** The purposes that are REPORTS (data.js `REPORTING_PURPOSES`, L53354) — derived from the purpose, never a caller flag. */\nexport const SHARE_REPORTING_PURPOSES: ReadonlySet<string> = new Set([\n \"mandatory_reporting\",\n \"authority_reporting\",\n]);\n\nexport type SharePosture = \"open\" | \"approval\" | \"blocked\";\n\n/** data.js `POSTURE_RANK` L53645 — stricter is higher; a policy can only RAISE the posture. */\nexport const SHARE_POSTURE_RANK: Readonly<Record<SharePosture, number>> =\n Object.freeze({\n open: 0,\n approval: 1,\n blocked: 2,\n });\n\n/** The four states of the Platform default (CVC-133 keys; data.js `SHARE_STATE_KEYS` L53697). */\nexport type SharePlatformState =\n \"always\" | \"default_on\" | \"default_off\" | \"never\";\n\n/** The words a person reads for each state (data.js `SCOPE_LOCK_LABEL` L53698). */\nexport const SHARE_PLATFORM_STATE_LABEL: Readonly<\n Record<SharePlatformState, string>\n> = Object.freeze({\n always: \"Required\",\n default_on: \"Default On\",\n default_off: \"Default Off\",\n never: \"Blocked\",\n});\n\n/** Where on the ladder the governing policy was found (data.js `ATTACH_LEVEL_LABEL` keys, L53646ff). */\nexport type ShareLevel =\n | \"team_row\"\n | \"account_internal\"\n | \"inside_starter\"\n | \"relationship\"\n | \"agency_default\"\n | \"platform_starter\";\n\nexport const SHARE_LEVEL_LABEL: Readonly<Record<ShareLevel | \"team\", string>> =\n Object.freeze({\n team_row: \"attached on the team-to-team row\",\n relationship: \"attached to this relationship\",\n agency_default: \"your account's default for this purpose\",\n account_internal:\n \"your account's default for sharing between its own teams\",\n team: \"your account's rule for this team\",\n platform_starter: \"Platform default\",\n inside_starter: \"the platform's default for sharing inside your account\",\n });\n\n// ─── Inputs ──────────────────────────────────────────────────────────────────\n\n/** One link of a policy to where it governs — a Relationship record (K13-3; data.js L53577-L53587). */\nexport type SharePolicyAssignment =\n | { readonly scope: \"account\" }\n | { readonly scope: \"account_internal\" }\n | { readonly scope: \"account_partner\"; readonly partnerId: string }\n | { readonly scope: \"team\"; readonly teamId: string }\n | {\n readonly scope: \"team_pair\";\n readonly teamRowId: string;\n readonly teamId?: string;\n readonly partnerId?: string | null;\n /**\n * The other end of the row, as the Admin Hub stores it on the link\n * (data.js `policyRecord`): `{ type: \"team\", id }` names a receiving\n * team — one of the account's own (no `partnerId`) or the partner's.\n * The ladder does not read it (the row decides); `fireShareEvent` does.\n */\n readonly with?: {\n readonly type?: string;\n readonly id?: string;\n } | null;\n };\n\n/** A policy document as the Admin Hub stores it (data.js `policyRecord` L53540ff). */\nexport interface SharePolicyDoc {\n readonly id: string;\n readonly familyId?: string;\n /** Un-ledgered = v1 (`parseInt(p.version, 10) || 1`). */\n readonly version?: number | string;\n readonly name?: string;\n /** ONE CVC-84 purpose (invariant 3). */\n readonly purpose: string;\n readonly species?: string;\n readonly posture?: SharePosture | null;\n readonly narrowOnly?: boolean;\n /** v4 codes (categories, kinds, rows). `null` = no category list (no restriction at category grain). */\n readonly infoScope?: readonly string[] | null;\n /** Field-group grain: category → the rows of it that may leave (K13-5c). */\n readonly infoScopeItems?: Readonly<Record<string, readonly string[]>> | null;\n readonly assignments?: readonly SharePolicyAssignment[];\n readonly origin?: {\n readonly kind?: string;\n readonly parentId?: string;\n } | null;\n /** `false` = still synced to the Platform default (K13-11): its list does not bind, the default's does. */\n readonly edited?: boolean;\n /** `false` = retired: never governs. */\n readonly active?: boolean;\n /**\n * `answers: \"received\"` (K13-9b): a share-back policy never governs a share you start.\n * `on` (K13-9a): the CVC-285 event names a LISTENER fires on — read by\n * `fireShareEvent`, never by the ladder.\n */\n readonly trigger?: {\n readonly answers?: string;\n readonly on?: readonly string[];\n } | null;\n /** CVC-85 cadences the policy grants; `ongoing` + a trigger makes it a listener (K13-9a). */\n readonly cadences?: {\n readonly ongoing?: boolean;\n readonly automatic?: boolean;\n } | null;\n}\n\n/** The Platform default for one purpose, as the four states (data.js `platformStarterScope` L53719ff). */\nexport interface SharePlatformDefault {\n readonly purpose: string;\n /** The versioned tier document `pol-starter-<purpose>` (un-ledgered = 1). */\n readonly version: number;\n /** The STARTING scope — the lists `raw` as data.js keeps it: Required categories and `system` included, Blocked ones out. */\n readonly raw: readonly string[];\n /** category → state. */\n readonly states: Readonly<Record<string, SharePlatformState>>;\n /** Categories whose state is `always` (`system` not listed). */\n readonly required: readonly string[];\n /** Categories whose state is `never`. */\n readonly blocked: readonly string[];\n readonly edited?: boolean;\n}\n\nexport type ShareRecipient =\n | { readonly kind: \"partner\"; readonly id: string }\n | { readonly kind: \"external\" }\n | { readonly kind: \"sibling_team\"; readonly teamId: string };\n\nexport interface ShareResolveInput {\n /** The v4 tree (an information-scope resolver, or anything with its four read methods). */\n readonly scope: SharingCeilingScope;\n /** Every policy document of the SENDING account (retired ones are skipped). */\n readonly policies: readonly SharePolicyDoc[];\n /** The Platform default for `purpose`; `null` = the purpose is unknown to the platform (fails closed). */\n readonly platformDefault: SharePlatformDefault | null;\n /** The sender: the account and, when the share is a team's, its team (`null` = a team-blind read: no pair row, no ceiling). */\n /**\n * The sender: its team when the share is a team's (`null` = a team-blind read: no pair row, no\n * ceiling — the account's answer, not a team's). `accountId` is informational: `policies` must\n * already be the SENDING account's documents (the resolver does not filter by account).\n */\n readonly sender: {\n readonly accountId?: string;\n readonly teamId: string | null;\n };\n /** The purpose's label for the Platform-default document names people read (`purpose` when absent). */\n readonly purposeLabel?: string;\n readonly recipient: ShareRecipient;\n readonly purpose: string;\n /** The matched team-to-team row (`matchTeamRow`), when the sender's team has one for this recipient. */\n readonly teamRowId?: string | null;\n /** Clamp 1: the purpose is switched off for the account (`isSharingPurposeDisabled` in chain.ts). Blocks reports too (flow M1). */\n readonly purposeOff?: boolean;\n /**\n * The partner row's own posture, which a policy can only raise (data.js `effectiveCeiling`). Default `open`.\n * IGNORED when a `partnerPurposeRule` is present: the posture then starts from the rule\n * (data.js L55342: `bp.sharingPosture || over.sharingPosture || …` — the rule first).\n */\n readonly relationshipPosture?: SharePosture | null;\n /**\n * The account's AUTHORED purpose-specific rule for this partner and purpose — data.js\n * `policies.partnerOverrides[partner].byPurpose[purpose]` when it carries a `sharingPosture`\n * (the Share Partners \"purpose-specific rule\"). When no policy is attached to the relationship\n * for the purpose, the answer NAMES it as the governing policy (the virtual fork\n * `pol-bp-<partner>-<purpose>`, \"<purpose label> — <partner name> variant\", level\n * `relationship`, `virtual: true`; data.js `governingPolicyFor` L55006-L55028).\n * - Posture: STARTS from `posture` whenever a rule is present, whatever the ladder named\n * (L55342; `relationshipPosture` is ignored); policies and the team ceiling can only raise\n * it. Under the fork the account default is not consulted for posture (L55391).\n * - Scope under the fork: clamp 5 (L55504) — `legacyCeiling` (a rule's category list, if the\n * caller still carries one, goes there), else an EDITED account default's list (data.js's\n * projected `sharingScopeEdits[__default__]`, L55163-L55164), else the Platform default's\n * starting scope; the default's list does not bind as 5b (L55539). The edited default's\n * field groups (`infoScopeItems`) still bind — deliberately narrower than data.js (L55658).\n * - When the rule itself blocked: \"Partner is blocked for this purpose by your account's\n * sharing policy\" (L55447-L55448), or for a report the carve-out \"Partner is blocked for\n * ordinary sharing — reachable for reports\" (L55436-L55446). When a policy blocked, the\n * policy is named (deliberate correction: data.js names the rule even when it is open).\n * Ignored inside the account and for an `__external__` recipient (L55333: scope-only); not\n * named as the fork when a pair row or a relationship policy governs or for an unknown\n * purpose; a `posture` that is not open / approval / blocked is no rule. `null` / absent = no\n * rule (the answer is the one 0.60.0 gave).\n */\n readonly partnerPurposeRule?: {\n readonly posture: SharePosture;\n /** The partner's display name for the fork's name (the recipient id when absent). */\n readonly partnerName?: string | null;\n } | null;\n /**\n * The legacy cell chain for callers still carrying `sharingScopeEdits`: pass `effectiveCeiling(...)`'s\n * ANSWER (its `platform_default` rung is then ignored — the resolver reads that document itself;\n * K13-12), or a plain list that binds as given; `null` / absent = none.\n */\n readonly legacyCeiling?: readonly string[] | EffectiveSharingCeiling | null;\n /**\n * The account's Information Scope (clamp 4 / 4b) as EXPLICIT choices over the codebook's\n * defaults: `categoriesOff` / `rowsOff` = switched off; `categoriesOn` / `rowsOn` = a heightened\n * (`shareableDefault: false`, CVC-236) category or row the account has turned ON. A code in\n * neither list reads the codebook default — so heightened information stays off when this is\n * absent (data.js `effectiveCeiling` clamps 4 / 4b). A code in both lists is off.\n */\n readonly accountScope?: {\n readonly categoriesOff?: readonly string[];\n readonly rowsOff?: readonly string[];\n readonly categoriesOn?: readonly string[];\n readonly rowsOn?: readonly string[];\n } | null;\n}\n\n// ─── Output ──────────────────────────────────────────────────────────────────\n\nexport interface ShareNamedPolicy {\n readonly id: string;\n readonly familyId: string;\n readonly name: string;\n readonly version: number;\n readonly level: ShareLevel | \"team\";\n readonly levelLabel: string;\n readonly posture: SharePosture | null;\n readonly infoScope: string[] | null;\n /** Field-group grain, when the document carries it (a copy). */\n readonly infoScopeItems: Record<string, string[]> | null;\n readonly edited: boolean;\n readonly origin: string | null;\n readonly rulePath: string;\n /**\n * `true` only on the virtual `byPurpose` fork (`partnerPurposeRule`): a NAME for the authored\n * purpose-specific rule, not a stored document — it binds nothing itself.\n */\n readonly virtual?: true;\n}\n\nexport interface ShareCategoryEntry {\n readonly allowed: boolean;\n readonly reason: string;\n readonly rulePath: string;\n /** Set when the Platform default marks the category Required (`always`): nothing account-grain removes it. */\n readonly platformRequired: { readonly rulePath: string } | null;\n /** Rows under the platform safety floor — never leave. */\n readonly floorItems: string[];\n /**\n * Rows the governing list / the account's heightened toggles / the ceiling leave out. A code is\n * withheld when it OR AN ANCESTOR is listed here. Since 0.42.1 a grouping is listed only when\n * nothing beneath it is covered — when a list names some of its rows, the grouping is NOT listed\n * and its uncovered rows are listed one by one instead. So a grouping code's absence here does\n * not mean the whole grouping may leave: for a send decision read `shareRowCeiling` +\n * `rowsOverCeiling`, never a grouping-code check against `excludedItems` alone.\n */\n readonly excludedItems: string[];\n readonly excludedReason: string | null;\n /** Rows the sending team's own policy leaves out (5d). Same shape and same caveat as `excludedItems`. */\n readonly teamExcludedItems: string[];\n readonly teamExcludedReason: string | null;\n}\n\nexport interface ShareResolution {\n /** `false` = the share as a whole is excluded (`excluded` says why). */\n readonly allowed: boolean;\n readonly posture: SharePosture;\n readonly postureSource: \"relationship\" | \"policy\" | \"team_ceiling\";\n readonly excluded: {\n readonly reason: string;\n readonly rulePath: string;\n } | null;\n /** A reporting purpose under a `blocked` posture: never excluded; the note names what blocks ordinary sharing. */\n readonly reportCarveOut: {\n readonly note: string;\n readonly rulePath: string;\n } | null;\n /** The policy that governs; `null` only for an unknown purpose (fails closed). */\n readonly governing: ShareNamedPolicy | null;\n /** The sending team's own policy for the purpose, when it is not itself the governing one. */\n readonly teamCeiling: ShareNamedPolicy | null;\n /** A share to a sibling team of the same account. */\n readonly inside: boolean;\n /** Every live category of the tree, in tree order. */\n readonly scope: Readonly<Record<string, ShareCategoryEntry>>;\n /** The categories with `allowed === true`, tree order — the list the coverage readers take. */\n readonly allowedCategories: string[];\n readonly rulePath: string;\n}\n\n// ─── Helpers ─────────────────────────────────────────────────────────────────\n\nconst own = <V>(record: unknown, key: string): V | undefined =>\n record !== null &&\n typeof record === \"object\" &&\n Object.prototype.hasOwnProperty.call(record, key)\n ? ((record as Record<string, V>)[key] as V)\n : undefined;\n\nconst isStringList = (v: unknown): v is readonly string[] =>\n Array.isArray(v) && v.every((c) => typeof c === \"string\");\n\nconst versionOf = (v: unknown): number => {\n const n = typeof v === \"number\" ? v : parseInt(String(v), 10);\n return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 1;\n};\n\n/**\n * `infoScope` as the resolver reads it: `null` or absent = no list (data.js reads every\n * non-array as \"no list\", L54979 / L55124); a list of strings = that list (`[]` binds an empty\n * list, as in canon); any other present value = `[]` (fail closed; stricter than canon).\n */\nconst docList = (v: unknown): string[] | null =>\n v === null || v === undefined ? null : isStringList(v) ? [...v] : [];\n\n/**\n * data.js `scopeListCovers` (L54696-L54706), on the v4 tree: a non-array list\n * covers everything; a category is covered when the list names it or an\n * ANCESTOR (a kind such as `family`, a branch); with a row `it`, the row is\n * covered when it or an ancestor is named; without one, a category is also\n * covered when the list names any DESCENDANT of it (a row or grouping).\n */\nexport function scopeListCovers(\n scope: SharingCeilingScope,\n list: readonly string[] | null | undefined,\n categoryCode: string,\n rowCode?: string,\n): boolean {\n if (!Array.isArray(list)) return true;\n const set = new Set(list);\n if (scope.ancestorsOf(categoryCode).some((c) => set.has(c))) return true;\n if (rowCode !== undefined)\n return scope.ancestorsOf(rowCode).some((c) => set.has(c));\n return list.some((id) =>\n scope.ancestorsOf(id).slice(1).includes(categoryCode),\n );\n}\n\n/** `scopeStrictCovers` (L54710ff): the list names the category or an ancestor — never a descendant. */\nexport function scopeListStrictlyCovers(\n scope: SharingCeilingScope,\n list: readonly string[] | null | undefined,\n categoryCode: string,\n): boolean {\n if (!Array.isArray(list)) return true;\n const set = new Set(list);\n return scope.ancestorsOf(categoryCode).some((c) => set.has(c));\n}\n\n/** The attachment index the ladder reads (data.js `effectiveAttachmentIndex` L53558ff), built from `assignments` only. */\nexport interface ShareAttachmentIndex {\n readonly agencyDefaults: Readonly<Record<string, string>>;\n readonly internalDefaults: Readonly<Record<string, string>>;\n readonly relationships: Readonly<\n Record<string, Readonly<Record<string, string>>>\n >;\n readonly teamRows: Readonly<Record<string, Readonly<Record<string, string>>>>;\n readonly teams: Readonly<Record<string, Readonly<Record<string, string>>>>;\n}\n\nconst isLiveDoc = (p: SharePolicyDoc | null | undefined): p is SharePolicyDoc =>\n p !== null &&\n typeof p === \"object\" &&\n typeof p.id === \"string\" &&\n p.id !== \"\" &&\n typeof p.purpose === \"string\" &&\n p.active !== false;\n\nexport function attachmentIndexFromPolicies(\n policies: readonly SharePolicyDoc[] | null | undefined,\n): ShareAttachmentIndex {\n // Null-prototype maps: a key such as `__proto__` is a key, never the prototype. Two live\n // documents on one cell: the LATER one in `policies` wins (deterministic; a store's key forbids it).\n const nullMap = <V>(): Record<string, V> =>\n Object.create(null) as Record<string, V>;\n const agencyDefaults = nullMap<string>();\n const internalDefaults = nullMap<string>();\n const relationships = nullMap<Record<string, string>>();\n const teamRows = nullMap<Record<string, string>>();\n const teams = nullMap<Record<string, string>>();\n const put = (\n map: Record<string, Record<string, string>>,\n key: string,\n purpose: string,\n id: string,\n ): void => {\n const row = Object.prototype.hasOwnProperty.call(map, key)\n ? map[key]\n : (map[key] = nullMap<string>());\n row[purpose] = id;\n };\n for (const p of Array.isArray(policies) ? policies : []) {\n if (!isLiveDoc(p)) continue;\n for (const a of Array.isArray(p.assignments) ? p.assignments : []) {\n if (a === null || typeof a !== \"object\") continue;\n switch (a.scope) {\n case \"account\":\n agencyDefaults[p.purpose] = p.id;\n break;\n case \"account_internal\":\n internalDefaults[p.purpose] = p.id;\n break;\n case \"account_partner\":\n if (typeof a.partnerId === \"string\" && a.partnerId !== \"\")\n put(relationships, a.partnerId, p.purpose, p.id);\n break;\n case \"team\":\n if (typeof a.teamId === \"string\" && a.teamId !== \"\")\n put(teams, a.teamId, p.purpose, p.id);\n break;\n case \"team_pair\":\n if (typeof a.teamRowId === \"string\" && a.teamRowId !== \"\")\n put(teamRows, a.teamRowId, p.purpose, p.id);\n break;\n default:\n break; // an unknown scope governs nowhere\n }\n }\n }\n return { agencyDefaults, internalDefaults, relationships, teamRows, teams };\n}\n\n/** A team-to-team row as the account stores it (data.js `teamRows` / `teamPairs`, L53493-L53514). */\nexport interface ShareTeamRowLike {\n readonly id: string;\n readonly myTeamId?: string | null;\n readonly their?: { readonly type?: string; readonly id?: string } | null;\n}\n\n/**\n * The row the first rung reads (data.js `internalPairRow` / `partnerTeamRow`,\n * L53493-L53514). `rows` is ONE store, as the prototype keeps them: for a\n * sibling team, the account's internal pairs (`policies.teamPairs`); for a\n * partner, THAT partner's team rows (`partnerOverrides[partner].teamRows`, or\n * the seeded rows) — never a flat list across partners. A sibling team's row\n * is the one whose `their` is that team (direction matters — the sender\n * first); a partner's row under a team-scoped relationship is the team's\n * FIRST row, under an all-teams relationship the row whose `their` is absent,\n * not a team, or this very partner. Rows that carry only share-back\n * (answers-received) policies are dropped first. An external recipient has\n * no row.\n */\nexport function matchTeamRow(\n rows: readonly ShareTeamRowLike[] | null | undefined,\n teamId: string | null | undefined,\n recipient: ShareRecipient,\n options: {\n readonly scopeMode?: \"team_scoped\" | \"all_teams\";\n readonly shareBackOnlyRowIds?: readonly string[];\n } = {},\n): string | null {\n if (typeof teamId !== \"string\" || teamId === \"\" || !Array.isArray(rows))\n return null;\n const drop = new Set(options.shareBackOnlyRowIds ?? []);\n const live = rows.filter(\n (r): r is ShareTeamRowLike =>\n r !== null &&\n typeof r === \"object\" &&\n typeof r.id === \"string\" &&\n !drop.has(r.id),\n );\n if (recipient.kind === \"sibling_team\") {\n // data.js `internalPairRow` (L53509-L53514): every row of the internal-pairs store is a\n // team-to-team row (`teamRowIndex` L53481 types it `team`), so it matches on `their.id`\n // alone — a stored pair row without `their.type` still governs.\n return (\n live.find(\n (r) => r.myTeamId === teamId && r.their?.id === recipient.teamId,\n )?.id ?? null\n );\n }\n if (recipient.kind === \"external\") return null;\n if (options.scopeMode === \"team_scoped\")\n return live.find((r) => r.myTeamId === teamId)?.id ?? null;\n return (\n live.find(\n (r) =>\n r.myTeamId === teamId &&\n (!r.their || r.their.type !== \"team\" || r.their.id === recipient.id),\n )?.id ?? null\n );\n}\n\n// ─── The four states ─────────────────────────────────────────────────────────\n\n/**\n * Derive one purpose's Platform default as the four states (data.js\n * `starterDerivedState` L53708 + `platformStarterScope` L53719ff),\n * for every live CATEGORY of the tree, in this order — the first rule wins:\n * System metadata → `always`; a category the platform requires for the\n * purpose → `always`; off-by-default (heightened) → `never`; the seed list\n * covers it (itself, an ancestor, or any row of it) → `default_on`, else\n * `default_off`. An explicit bound overrides it for every category but\n * `system`. `raw` is the starting scope: the seed's codes whose category is\n * not Blocked or bound off, plus every bound-on and Required category, plus\n * `system`.\n */\nexport function derivePlatformDefault(\n scope: SharingCeilingScope,\n purpose: string,\n seedList: readonly string[] | null | undefined,\n options: {\n readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;\n readonly required?: readonly string[] | null;\n readonly version?: number | string;\n readonly edited?: boolean;\n } = {},\n): SharePlatformDefault {\n const seed = isStringList(seedList) ? [...seedList] : [];\n const req = new Set(options.required ?? []);\n const states: Record<string, SharePlatformState> = {};\n const required: string[] = [];\n const blocked: string[] = [];\n const systemCode = systemCategoryOf(scope);\n for (const g of liveCategories(scope)) {\n let state: SharePlatformState;\n if (g === systemCode) state = \"always\";\n else if (req.has(g)) state = \"always\";\n else if (scope.row(g)?.shareableDefault === false) state = \"never\";\n else state = scopeListCovers(scope, seed, g) ? \"default_on\" : \"default_off\";\n const bound = own<unknown>(options.bounds, g);\n if (\n g !== systemCode &&\n (bound === \"always\" ||\n bound === \"default_on\" ||\n bound === \"default_off\" ||\n bound === \"never\")\n )\n state = bound;\n states[g] = state;\n if (state === \"always\" && g !== systemCode) required.push(g);\n if (state === \"never\") blocked.push(g);\n }\n const categoryOf = (code: string): string | undefined =>\n scope.ancestorsOf(code).find((c) => scope.row(c)?.rowType === \"category\");\n const raw: string[] = [];\n const push = (c: string): void => {\n if (!raw.includes(c)) raw.push(c);\n };\n for (const code of seed) {\n const g = categoryOf(code);\n if (g === undefined) {\n // A kind or a branch: it stands for its categories — keep the ones that are on, by name,\n // so a category bound off beneath it is not covered by the kind (review r1 #4).\n for (const [cat, st] of Object.entries(states)) {\n if (\n (st === \"always\" || st === \"default_on\") &&\n scope.ancestorsOf(cat).includes(code)\n )\n push(cat);\n }\n continue;\n }\n const st = states[g];\n if (st === \"never\" || st === \"default_off\") continue;\n push(code);\n }\n for (const [g, st] of Object.entries(states)) {\n if (\n (st === \"always\" || st === \"default_on\") &&\n !scopeListCovers(scope, raw, g)\n )\n push(g);\n }\n if (systemCode !== undefined) push(systemCode);\n return {\n purpose,\n version: versionOf(options.version),\n raw,\n states,\n required,\n blocked,\n edited: options.edited === true,\n };\n}\n\n// ─── Tree reads ──────────────────────────────────────────────────────────────\n\nconst treeCache = new WeakMap<\n object,\n {\n categories: string[];\n system: string | undefined;\n leaves: Map<string, string[]>;\n descendants: Map<string, string[]>;\n }\n>();\n\nfunction treeIndex(scope: SharingCeilingScope) {\n const hit = treeCache.get(scope);\n if (hit) return hit;\n const live = (code: string): boolean =>\n scope.row(code) !== undefined &&\n scope.ancestorsOf(code).every((c) => scope.row(c)?.status !== \"retired\");\n const categories = scope.rows\n .filter((r) => r.rowType === \"category\" && live(r.scopeCode))\n .map((r) => r.scopeCode);\n const systemInfoPath =\n scope.row(\"system_info\") !== undefined\n ? scope.ancestorsOf(\"system_info\")\n : [];\n const system =\n systemInfoPath.find((c) => categories.includes(c)) ??\n categories.find((g) => g === \"system\");\n const descendants = new Map<string, string[]>();\n const leaves = new Map<string, string[]>();\n for (const g of categories) {\n const all: string[] = [];\n const walk = (code: string): void => {\n for (const c of scope.childrenOf(code)) {\n if (!live(c)) continue;\n all.push(c);\n walk(c);\n }\n };\n walk(g);\n descendants.set(g, all);\n leaves.set(\n g,\n all.filter((c) => !scope.childrenOf(c).some(live)),\n );\n }\n const out = { categories, system, leaves, descendants };\n treeCache.set(scope, out);\n return out;\n}\n\n/** The live categories of the tree, in tree order. */\nexport function liveCategories(scope: SharingCeilingScope): string[] {\n return [...treeIndex(scope).categories];\n}\n\n/** The System-metadata category (`system`, the parent of `system_info`). */\nexport function systemCategoryOf(\n scope: SharingCeilingScope,\n): string | undefined {\n return treeIndex(scope).system;\n}\n\n/**\n * The legacy cell chain's list as clamp 5 reads it: a plain list binds as given; an\n * `effectiveCeiling` answer binds only when an ACCOUNT rule answered (`partner_rule`,\n * `seeded_partner_rule`, `account_default`) — its `platform_default` rung is the same document\n * the resolver already reads as the Platform default (passing it as a legacy list would clamp\n * every authored policy to the starter and undo K13-12), and `purpose_disabled` / `none` are\n * carried by `purposeOff` / the missing Platform default.\n */\nfunction legacyCeilingList(\n v: ShareResolveInput[\"legacyCeiling\"],\n): string[] | null {\n if (v === null || v === undefined) return null;\n if (isStringList(v)) return [...v];\n if (typeof v === \"object\" && \"rung\" in v) {\n const r = (v as EffectiveSharingCeiling).rung;\n if (\n r === \"partner_rule\" ||\n r === \"seeded_partner_rule\" ||\n r === \"account_default\"\n ) {\n return isStringList(v.allowed) ? [...v.allowed] : [];\n }\n return null;\n }\n return null;\n}\n\n/**\n * The categories the platform REQUIRES for a purpose (data.js `scopeRequiredByPurpose`,\n * L40836-L40839): Identifying information on every report. Read by `platformDefaultFor`.\n */\nexport const HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE: Readonly<\n Record<string, readonly string[]>\n> = Object.freeze({\n mandatory_reporting: Object.freeze([\"identifying\"]),\n authority_reporting: Object.freeze([\"identifying\"]),\n});\n\n/**\n * The Platform default for one purpose from the PUBLISHED starter (the day-one tier document,\n * version 1, no bounds): `derivePlatformDefault` over `HTI_SHARE_PLATFORM_STARTER.scopeByPurpose`\n * and {@link HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE}. `null` for a purpose the starter has no row\n * for (the resolver then fails closed). Once the platform stores `pol-starter-<purpose>` as a\n * versioned document, pass ITS list, bounds and version instead.\n */\nexport function platformDefaultFor(\n scope: SharingCeilingScope,\n purpose: string,\n options: {\n readonly starter?: SharingPlatformStarter;\n readonly bounds?: Readonly<Record<string, SharePlatformState>> | null;\n readonly version?: number | string;\n readonly edited?: boolean;\n } = {},\n): SharePlatformDefault | null {\n const starter = options.starter ?? HTI_SHARE_PLATFORM_STARTER;\n const seed = own<readonly string[]>(starter.scopeByPurpose, purpose);\n if (!isStringList(seed)) return null;\n return derivePlatformDefault(scope, purpose, seed, {\n required:\n own<readonly string[]>(HTI_SHARE_PLATFORM_REQUIRED_BY_PURPOSE, purpose) ??\n [],\n bounds: options.bounds ?? null,\n version: options.version ?? 1,\n edited: options.edited === true,\n });\n}\n\n/**\n * The ROW-grain ceiling one resolution amounts to — the list the item-grain readers take\n * (`maskSelectionToCeiling` for the composer, `rowsOverCeiling` for the send door): each\n * allowed category by its own code when no row of it is withheld (or, for a category with\n * fields of its own, when only floor rows are), else its live rows minus the withheld ones\n * (the governing list's, the account's heightened rows, the field-group limits, the team's).\n * Rows under the platform floor are never listed, and never leave on a listed ancestor (the\n * readers never let them through). `[]` for an excluded share — only System metadata rides.\n */\nexport function shareRowCeiling(\n resolution: Pick<ShareResolution, \"allowed\" | \"scope\" | \"allowedCategories\">,\n scope: SharingCeilingScope,\n): string[] {\n if (!resolution.allowed) return [];\n const out: string[] = [];\n for (const g of resolution.allowedCategories) {\n const e = own<ShareCategoryEntry>(resolution.scope, g);\n if (e === undefined) continue;\n const withheld = new Set([\n ...e.excludedItems,\n ...e.teamExcludedItems,\n ...e.floorItems,\n ]);\n // A category with fields of its own that has nothing withheld but floor rows is listed\n // itself: listing only its children would drop its own fields (coverage rule 2), and a\n // floor row never leaves on a listed ancestor (`ceilingCoverage`). The per-kind\n // \"Contact & safety\" rows (another person's phones, emails, contact log) are this shape.\n const onlyFloorWithheld = [...withheld].every((r) => e.floorItems.includes(r));\n if (withheld.size === 0 || (onlyFloorWithheld && hasOwnScopeContent(scope, g))) {\n out.push(g);\n continue;\n }\n // walk down from the category: a row stands at its own grain when nothing beneath it is\n // withheld; else its surviving children stand in for it; a withheld row (and all beneath)\n // is dropped — so `instrument_full` with every full row off is not listed at all.\n const live = (c: string): boolean =>\n scope.row(c) !== undefined &&\n scope.ancestorsOf(c).every((a) => scope.row(a)?.status !== \"retired\");\n const anyWithheldBeneath = (c: string): boolean =>\n scope\n .childrenOf(c)\n .some((k) => live(k) && (withheld.has(k) || anyWithheldBeneath(k)));\n const visit = (c: string): void => {\n if (withheld.has(c) || !live(c)) return;\n if (!anyWithheldBeneath(c)) {\n out.push(c);\n return;\n }\n for (const k of scope.childrenOf(c)) visit(k);\n };\n for (const k of scope.childrenOf(g)) visit(k);\n }\n return out;\n}\n\n// ─── The resolver ────────────────────────────────────────────────────────────\n\ninterface Hit {\n readonly policy: SharePolicyDoc;\n readonly level: ShareLevel | \"team\";\n readonly version: number;\n readonly rulePath: string;\n}\n\nfunction named(h: Hit): ShareNamedPolicy {\n const p = h.policy;\n return {\n id: p.id,\n familyId:\n typeof p.familyId === \"string\" && p.familyId !== \"\" ? p.familyId : p.id,\n name: typeof p.name === \"string\" ? p.name : p.id,\n version: h.version,\n level: h.level,\n levelLabel: SHARE_LEVEL_LABEL[h.level],\n posture:\n p.posture === \"open\" ||\n p.posture === \"approval\" ||\n p.posture === \"blocked\"\n ? p.posture\n : null,\n infoScope: docList(p.infoScope),\n infoScopeItems: copyItems(p.infoScopeItems),\n edited: p.edited === true,\n origin: typeof p.origin?.kind === \"string\" ? p.origin.kind : null,\n rulePath: h.rulePath,\n };\n}\n\nconst uniq = (list: readonly string[]): string[] => [...new Set(list)];\n\nconst copyItems = (v: unknown): Record<string, string[]> | null => {\n if (v === null || typeof v !== \"object\") return null;\n const out: Record<string, string[]> = {};\n for (const [k, rows] of Object.entries(v as Record<string, unknown>)) {\n if (isStringList(rows)) out[k] = [...rows];\n }\n return out;\n};\n\n/**\n * THE read. See the module header; the algorithm, step by step:\n * 1. the ladder (`governingPolicyFor`): pair row → [inside: the account's\n * inside default → the platform's inside starter, stop] → relationship\n * (the partner id, or `__external__`) → [the account's authored\n * purpose-specific rule for the partner (`partnerPurposeRule`), NAMED as\n * its virtual fork — posture from the rule, scope from clamp 5] → the\n * account default → the Platform default (a versioned document,\n * `pol-starter-<purpose>`);\n * 2. the sending team's own policy for the purpose rides as a CEILING when\n * it is not the governing one (inside the account too);\n * 3. posture: the relationship's, raised (never lowered) by the governing\n * policy, then by the ceiling — stricter wins;\n * 4. the whole share: the purpose switch excludes it (reports too); a\n * `blocked` posture excludes a discretionary share and CARVES OUT a\n * report (never blocked at the policy / partner layer);\n * 5. per category: Required (`system`, or the Platform default's `always`)\n * bypasses every account-grain clamp; else the account's toggle (4), the\n * Platform default's Blocked (4a, not inside), the binding list (5: the\n * legacy cell chain's list or the Platform default's starting scope — the\n * governing policy's own list when it is authored (5b); K13-12), the\n * team ceiling's list (5d); rows: the floor, heightened rows off (4b),\n * field-group limits (5c), and a category every row of which is withheld\n * is withheld (the group flip).\n */\nexport function resolveShare(input: ShareResolveInput): ShareResolution {\n const { scope, purpose, recipient } = input;\n if (typeof purpose !== \"string\" || purpose === \"\")\n throw new TypeError(\"resolveShare: purpose must be a share purpose code\");\n const teamId =\n typeof input.sender?.teamId === \"string\" && input.sender.teamId !== \"\"\n ? input.sender.teamId\n : null;\n const inside = recipient.kind === \"sibling_team\";\n const recipientKey =\n recipient.kind === \"partner\"\n ? recipient.id\n : recipient.kind === \"external\"\n ? \"__external__\"\n : null;\n if (\n recipient.kind === \"partner\" &&\n (typeof recipient.id !== \"string\" || recipient.id === \"\")\n ) {\n throw new TypeError(\"resolveShare: a partner recipient needs an id\");\n }\n const report = SHARE_REPORTING_PURPOSES.has(purpose);\n const pd = input.platformDefault ?? null;\n const purposeLabel =\n typeof input.purposeLabel === \"string\" && input.purposeLabel !== \"\"\n ? input.purposeLabel\n : purpose;\n const pdRaw = pd === null ? [] : isStringList(pd.raw) ? [...pd.raw] : [];\n const pdRequired =\n pd === null ? [] : isStringList(pd.required) ? [...pd.required] : [];\n const pdBlocked =\n pd === null ? [] : isStringList(pd.blocked) ? [...pd.blocked] : [];\n const policies = (Array.isArray(input.policies) ? input.policies : []).filter(\n isLiveDoc,\n );\n const byId = new Map<string, SharePolicyDoc>();\n for (const p of policies) byId.set(p.id, p);\n const att = attachmentIndexFromPolicies(policies);\n const tree = treeIndex(scope);\n const systemCode = tree.system;\n\n // 1. the ladder\n const hit = (\n id: string | undefined,\n level: ShareLevel | \"team\",\n ): Hit | null => {\n const p = id === undefined ? undefined : byId.get(id);\n if (p === undefined || p.purpose !== purpose) return null;\n if (p.trigger?.answers === \"received\") return null;\n const v = versionOf(p.version);\n const name = typeof p.name === \"string\" ? p.name : p.id;\n return {\n policy: p,\n level,\n version: v,\n rulePath: `sharingPurposePolicies[${p.id}] v${v} (policy “${name}” — ${SHARE_LEVEL_LABEL[level]})`,\n };\n };\n const cell = (\n map: Record<string, Readonly<Record<string, string>>>,\n key: string,\n ) => own<string>(own<Readonly<Record<string, string>>>(map, key), purpose);\n let gov: Hit | null = null;\n // An unknown purpose (no Platform default) governs nothing — the ladder is not read at all\n // (review r1 #1: a policy linked under it must not leak its own list).\n const purposeKnown = pd !== null;\n const teamRowId =\n purposeKnown &&\n teamId !== null &&\n recipient.kind !== \"external\" &&\n typeof input.teamRowId === \"string\" &&\n input.teamRowId !== \"\"\n ? input.teamRowId\n : null;\n if (teamRowId !== null) gov = hit(cell(att.teamRows, teamRowId), \"team_row\");\n if (gov === null && inside && purposeKnown) {\n gov = hit(own<string>(att.internalDefaults, purpose), \"account_internal\");\n if (gov === null && pd !== null) {\n const starter: SharePolicyDoc = {\n id: `pol-inside-starter-${purpose}`,\n name: `${purposeLabel} — Inside your account (platform default)`,\n purpose,\n infoScope: null,\n posture: \"open\",\n version: 1,\n origin: { kind: \"starter\" },\n };\n gov = {\n policy: starter,\n level: \"inside_starter\",\n version: 1,\n rulePath: `${starter.id} v1 (${SHARE_LEVEL_LABEL.inside_starter} — the full record, open)`,\n };\n }\n }\n // The virtual byPurpose fork (data.js L55006-L55028): governs between the relationship\n // rung and the account default.\n let fork: Hit | null = null;\n if (gov === null && !inside && purposeKnown && recipientKey !== null) {\n gov = hit(cell(att.relationships, recipientKey), \"relationship\");\n const rule = input.partnerPurposeRule;\n const rulePosture = rule?.posture;\n if (\n gov === null &&\n recipient.kind === \"partner\" && // `__external__` stays scope-only (data.js L55333)\n (rulePosture === \"open\" ||\n rulePosture === \"approval\" ||\n rulePosture === \"blocked\")\n ) {\n const partnerName =\n typeof rule?.partnerName === \"string\" && rule.partnerName !== \"\"\n ? rule.partnerName\n : recipientKey;\n fork = {\n policy: {\n id: `pol-bp-${recipientKey}-${purpose}`,\n name: `${purposeLabel} — ${partnerName} variant`,\n purpose,\n posture: rulePosture,\n infoScope: null,\n cadences: null,\n version: 1,\n origin: { kind: \"fork\" },\n edited: true,\n },\n level: \"relationship\",\n version: 1,\n rulePath: `policies.partnerOverrides[${recipientKey}].byPurpose[${purpose}] (purpose-specific rule, reported as its fork)`,\n };\n }\n if (gov === null)\n gov = hit(own<string>(att.agencyDefaults, purpose), \"agency_default\");\n if (gov === null && pd !== null) {\n const starter: SharePolicyDoc = {\n id: `pol-starter-${purpose}`,\n name: `${purposeLabel} — Platform default`,\n purpose,\n infoScope: pdRaw.filter((c) => c !== systemCode),\n posture: \"open\",\n version: pd.version,\n origin: { kind: \"platform_starter\" },\n edited: false,\n };\n gov = {\n policy: starter,\n level: \"platform_starter\",\n version: pd.version,\n rulePath: `${starter.id} v${pd.version} (${SHARE_LEVEL_LABEL.platform_starter})`,\n };\n }\n }\n // Under the fork the account default is not consulted for posture or as 5b; an EDITED\n // account default's list still binds scope as clamp 5's ceiling, as data.js's projection\n // `sharingScopeEdits[__default__]` (projectScopeEdits L55163-L55164; read L55501, L55504).\n // Its FIELD GROUPS (`infoScopeItems`) bind too — DELIBERATELY NARROWER than data.js, whose 5c\n // (L55658) reads only the governing policy and so drops them under the fork while it keeps\n // the same default's category list: a posture-only partner rule must not release field\n // groups the admin withheld (pending the owner's word). Likewise its category list binds even\n // when `legacyCeiling` is passed (data.js would read the legacy partner rule INSTEAD of it,\n // L55504) — the 0.60.0 answer bound both, and a posture-only rule must not widen scope.\n let defaultProjection: string[] | null = null;\n let defaultItems: {\n readonly rows: Record<string, string[]>;\n readonly name: string;\n } | null = null;\n if (fork !== null) {\n if (\n gov !== null &&\n gov.level === \"agency_default\" &&\n gov.policy.edited === true\n ) {\n if (isStringList(gov.policy.infoScope))\n defaultProjection = [...gov.policy.infoScope];\n const items = copyItems(gov.policy.infoScopeItems);\n if (items !== null)\n defaultItems = {\n rows: items,\n name:\n typeof gov.policy.name === \"string\" ? gov.policy.name : gov.policy.id,\n };\n }\n gov = fork;\n }\n // data.js `postureByPurpose` (L55343): an authored purpose-specific rule for this partner\n // and purpose. Its posture is where the posture STARTS whatever the ladder named (L55342:\n // `bp.sharingPosture || over.sharingPosture || …` — the rule first). `__external__` stays\n // scope-only (L55333): a rule passed for it is ignored.\n const rulePosture = input.partnerPurposeRule?.posture;\n const ruleAuthored =\n !inside &&\n recipient.kind === \"partner\" &&\n (rulePosture === \"open\" ||\n rulePosture === \"approval\" ||\n rulePosture === \"blocked\");\n\n // 2. the team ceiling (data.js `done()` composes it over every rung's answer, the fork's too)\n let tc: Hit | null = null;\n if (teamId !== null && gov !== null) {\n const t = hit(cell(att.teams, teamId), \"team\");\n if (t !== null && t.policy.id !== gov.policy.id) tc = t;\n }\n const govNamed: ShareNamedPolicy | null =\n gov === null\n ? null\n : fork !== null\n ? { ...named(gov), virtual: true }\n : named(gov);\n const tcNamed = tc === null ? null : named(tc);\n const rulePath =\n gov === null\n ? `no Platform default for purpose “${purpose}” — nothing governs (fails closed)`\n : tc === null\n ? gov.rulePath\n : `${gov.rulePath} ∩ ${tc.rulePath} (the sending team's own policy is a ceiling — only what both allow)`;\n\n // 3. posture — the rule's when one is present (`relationshipPosture` is then ignored), else\n // the relationship row's\n let posture: SharePosture =\n ruleAuthored && rulePosture !== undefined\n ? rulePosture\n : input.relationshipPosture === \"approval\" ||\n input.relationshipPosture === \"blocked\"\n ? input.relationshipPosture\n : \"open\";\n let postureSource: ShareResolution[\"postureSource\"] = \"relationship\";\n let posturePol: ShareNamedPolicy | null = null;\n if (\n fork === null && // data.js L55391: a virtual policy's posture is never applied\n govNamed?.posture &&\n SHARE_POSTURE_RANK[govNamed.posture] > SHARE_POSTURE_RANK[posture]\n ) {\n posture = govNamed.posture;\n postureSource = \"policy\";\n posturePol = govNamed;\n }\n if (\n tcNamed?.posture &&\n SHARE_POSTURE_RANK[tcNamed.posture] > SHARE_POSTURE_RANK[posture]\n ) {\n posture = tcNamed.posture;\n postureSource = \"team_ceiling\";\n posturePol = tcNamed;\n }\n\n // 4. the whole share\n let excluded: ShareResolution[\"excluded\"] = null;\n let reportCarveOut: ShareResolution[\"reportCarveOut\"] = null;\n if (gov === null) {\n excluded = {\n reason: `No Platform default for purpose “${purpose}” — nothing may leave under it`,\n rulePath,\n };\n } else if (input.purposeOff === true) {\n excluded = {\n reason: \"Share purpose disabled by your account's sharing policy\",\n rulePath: `purposeOverrides[${purpose}] = false`,\n };\n } else if (posture === \"blocked\") {\n const pol = posturePol; // null = the relationship's own posture blocks (review r1 #3)\n const path =\n pol === null\n ? \"relationship posture = blocked\"\n : `sharingPurposePolicies[${pol.id}].posture=blocked (policy “${pol.name}” — ${pol.levelLabel})`;\n // The rule itself is what blocked (data.js `!byCeiling && postureByPurpose`, L55436 /\n // L55447). DELIBERATE CORRECTION of data.js: there the purpose-rule sentence and path also\n // stand when the rule is open and an attached policy blocked, naming a cause that is false;\n // here they stand only when the rule blocked — the decision is unchanged, the audit record\n // names the true cause.\n const byRule = ruleAuthored && postureSource === \"relationship\";\n if (report && byRule) {\n // data.js L55436-L55446\n reportCarveOut = {\n note: \"Partner is blocked for ordinary sharing — reachable for reports\",\n rulePath: `reports-never-blocked-at-partner-layer (Crysta ruling 2026-08-23; policies.partnerOverrides[${recipientKey}].byPurpose[${purpose}].sharingPosture=blocked does not bind a legal duty — who may send is a role/function question)`,\n };\n } else if (report) {\n reportCarveOut = {\n note:\n pol === null\n ? \"Blocked for ordinary sharing — reachable for reports (nothing at the partner layer extinguishes the duty)\"\n : `The “${pol.name}” policy blocks ordinary sharing — reachable for reports`,\n rulePath: path,\n };\n } else if (byRule) {\n // data.js L55447-L55448\n excluded = {\n reason:\n \"Partner is blocked for this purpose by your account's sharing policy\",\n rulePath: `policies.partnerOverrides[${recipientKey}].byPurpose[${purpose}].sharingPosture=blocked (Share Partners — purpose-specific rule)`,\n };\n } else {\n excluded = {\n reason:\n pol === null\n ? \"Blocked for this purpose by the relationship\"\n : `Blocked for this purpose by your account's “${pol.name}” policy`,\n rulePath: path,\n };\n }\n }\n const excludedAll = excluded !== null;\n\n // 5. which list binds (K13-12)\n const level = gov?.level ?? null;\n const govList = govNamed?.infoScope ?? null;\n const polScopeBinds =\n gov !== null &&\n Array.isArray(govList) &&\n (level === \"team_row\" ||\n level === \"relationship\" ||\n level === \"account_internal\" ||\n level === \"inside_starter\" ||\n (level === \"agency_default\" && gov.policy.edited === true));\n const legacy = legacyCeilingList(input.legacyCeiling);\n // data.js L55504-L55505: cpEdit || seedOverride || defEdit || the starting scope\n const projectionPath = `policies.sharingScopeEdits[__default__][${purpose}] (projected from your account default policy)`;\n const projOverLegacy: string[] | null =\n legacy !== null ? defaultProjection : null;\n const ceilingIsStarter = legacy === null && defaultProjection === null;\n let groupCeiling: string[] | null = legacy ?? defaultProjection ?? pdRaw;\n let ceilingPath =\n legacy !== null\n ? \"sharingScopeEdits (the account's partner / default rule — the legacy cell chain)\"\n : defaultProjection !== null\n ? projectionPath\n : pd === null\n ? \"no Platform default\"\n : `pol-starter-${purpose} v${pd.version} (Platform default — the starting scope for this purpose)`;\n if (ceilingIsStarter && polScopeBinds) {\n groupCeiling = null;\n ceilingPath = \"\";\n }\n if (inside) {\n groupCeiling = null;\n ceilingPath = \"\";\n }\n const tcScope = tcNamed?.infoScope ?? null;\n const tcItems = tc?.policy.infoScopeItems ?? null;\n const govItems = gov?.policy.infoScopeItems ?? null;\n const required = (g: string): boolean =>\n g === systemCode || (!inside && pd !== null && pdRequired.includes(g));\n const blockedSet = new Set(pdBlocked);\n const asSet = (v: unknown): Set<string> => new Set(isStringList(v) ? v : []);\n const categoriesOff = asSet(input.accountScope?.categoriesOff);\n const rowsOff = asSet(input.accountScope?.rowsOff);\n const categoriesOn = asSet(input.accountScope?.categoriesOn);\n const rowsOn = asSet(input.accountScope?.rowsOn);\n const underFloor = (code: string): boolean =>\n scope.ancestorsOf(code).some((c) => scope.row(c)?.platformFloor === true);\n // Clamp 4 (data.js L55165-L55170): the account's explicit choice wins both ways; else the\n // codebook's `shareableDefault` — a heightened category is off until the account turns it on.\n const categoryOffByDefault = (g: string): boolean =>\n !categoriesOn.has(g) && scope.row(g)?.shareableDefault === false;\n // Clamp 4b (L55185-L55196): a row is off when the account switched it (or a grouping above it)\n // off, or when it — or a grouping between it and its category — is heightened by default and\n // the account has not turned that one on (`shareVerdict`'s rule: turning a grouping on does not\n // turn on an off-by-default row beneath it).\n const heightenedOff = (code: string, g: string): boolean => {\n const chain = scope.ancestorsOf(code);\n if (chain.some((c) => rowsOff.has(c))) return true;\n const below = chain.slice(0, Math.max(chain.indexOf(g), 0));\n return below.some(\n (c) => !rowsOn.has(c) && scope.row(c)?.shareableDefault === false,\n );\n };\n\n const out: Record<string, ShareCategoryEntry> = {};\n const allowedCategories: string[] = [];\n const govName = govNamed?.name ?? \"\";\n for (const g of tree.categories) {\n const items = tree.descendants.get(g) ?? [];\n const leaves = tree.leaves.get(g) ?? [];\n const platformRequired =\n !inside && pd !== null && pdRequired.includes(g)\n ? {\n rulePath: `pol-starter-${purpose} v${pd.version} · ${g} = Required (Platform default — set by the Platform Admin)`,\n }\n : null;\n const req = required(g);\n let allowed = true;\n let reason = excluded !== null ? excluded.reason : \"Allowed\";\n let path = excluded !== null ? excluded.rulePath : rulePath;\n const floorItems = items.filter(underFloor);\n const excludedItems: string[] = [];\n let excludedReason: string | null = null;\n const teamExcludedItems: string[] = [];\n let teamExcludedReason: string | null = null;\n // A row is OUTSIDE a list only when neither it nor anything beneath it is covered: a grouping\n // whose rows the list names by name (`instrument_summary` named only through `summary_lap`)\n // is not withheld as a unit — its uncovered rows are, each at its own grain (0.42.1; the\n // Thread inside-ceiling adoption found the whole grouping dropped with its named rows).\n // Latent gap: a grouping that carries its OWN fields (INFORMATION_SCOPE_FIELD_HOME_ROWS) and\n // whose children are all named, but not itself, is not withheld here — its own fields would\n // then leave, contrary to coverage rule 2 (`ceilingCoverage`, hasOwnContent → false). No live\n // grouping has own content today; whoever adds a field-homed grouping must handle it here.\n const outside = (covered: (r: string) => boolean): string[] =>\n items.filter(\n (r) =>\n !covered(r) &&\n !items.some(\n (d) => d !== r && covered(d) && scope.ancestorsOf(d).includes(r),\n ),\n );\n const addExcluded = (rows: readonly string[], why: string): void => {\n for (const r of rows)\n if (!floorItems.includes(r) && !excludedItems.includes(r))\n excludedItems.push(r);\n if (rows.length > 0 && excludedReason === null) excludedReason = why;\n };\n if (gov === null) {\n allowed = false; // an unknown purpose: nothing leaves, System metadata included\n } else if ((!req || platformRequired !== null) && excludedAll) {\n allowed = false;\n } else if (excludedAll) {\n reason = \"Allowed\";\n path = rulePath;\n }\n if (allowed && !req && (categoriesOff.has(g) || categoryOffByDefault(g))) {\n allowed = false;\n reason = \"Excluded by your account's Information Scope policy\";\n path = categoriesOff.has(g)\n ? `policies.scopeCatalog[${g}].shareable = false`\n : `policies.scopeCatalog[${g}] not turned on — codebook core-information_scope shareableDefault = false (CVC-236 heightened protection: off until the account turns it on)`;\n }\n if (allowed && !req && !inside && blockedSet.has(g)) {\n allowed = false;\n reason =\n \"Blocked for this purpose by the Platform default — no account can share it under this purpose\";\n path = `pol-starter-${purpose} v${pd?.version ?? 1} · ${g} = Blocked (Platform default — CVC-236 heightened protection | set by the Platform Admin)`;\n }\n // 4b heightened rows off in the account (every category but System metadata, Required included)\n addExcluded(\n g === systemCode\n ? []\n : items.filter((r) => !underFloor(r) && heightenedOff(r, g)),\n \"Heightened protection (CVC-236) — off in your account's Information Scope until the account turns it on\",\n );\n if (\n allowed &&\n !req &&\n groupCeiling !== null &&\n !scopeListCovers(scope, groupCeiling, g)\n ) {\n allowed = false;\n reason = \"Outside the payload for this purpose\";\n path = ceilingPath;\n }\n if (\n allowed &&\n !req &&\n groupCeiling !== null &&\n !scopeListStrictlyCovers(scope, groupCeiling, g)\n ) {\n addExcluded(\n outside((r) => scopeListCovers(scope, groupCeiling, g, r)),\n \"Outside the payload for this purpose\",\n );\n }\n if (\n allowed &&\n !req &&\n polScopeBinds &&\n !scopeListCovers(scope, govList, g)\n ) {\n allowed = false;\n reason = `Outside what the “${govName}” policy allows for this purpose`;\n path = `sharingPurposePolicies[${gov?.policy.id}].infoScope (policy “${govName}” — ${govNamed?.levelLabel})`;\n }\n if (\n allowed &&\n !req &&\n polScopeBinds &&\n !scopeListStrictlyCovers(scope, govList, g)\n ) {\n addExcluded(\n outside((r) => scopeListCovers(scope, govList, g, r)),\n `Outside what the “${govName}” policy allows for this purpose`,\n );\n }\n // Under the fork with `legacyCeiling` passed: the edited account default's list binds too.\n if (\n allowed &&\n !req &&\n projOverLegacy !== null &&\n !scopeListCovers(scope, projOverLegacy, g)\n ) {\n allowed = false;\n reason = \"Outside the payload for this purpose\";\n path = projectionPath;\n }\n if (\n allowed &&\n !req &&\n projOverLegacy !== null &&\n !scopeListStrictlyCovers(scope, projOverLegacy, g)\n ) {\n addExcluded(\n outside((r) => scopeListCovers(scope, projOverLegacy, g, r)),\n \"Outside the payload for this purpose\",\n );\n }\n const govRows = polScopeBinds ? own<unknown>(govItems, g) : undefined;\n if (allowed && !req && isStringList(govRows)) {\n const keep = new Set(govRows);\n const kept = (r: string): boolean =>\n keep.has(r) || scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));\n addExcluded(\n outside(kept),\n `Outside what the “${govName}” policy allows for this purpose`,\n );\n }\n // Under the fork: the edited account default's field groups still bind (see above).\n const defRows =\n defaultItems === null ? undefined : own<unknown>(defaultItems.rows, g);\n if (allowed && !req && isStringList(defRows)) {\n const keep = new Set(defRows);\n const kept = (r: string): boolean =>\n keep.has(r) || scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));\n addExcluded(\n outside(kept),\n `Outside what the “${defaultItems?.name ?? \"\"}” policy allows for this purpose`,\n );\n }\n if (\n allowed &&\n !req &&\n tcScope !== null &&\n !scopeListCovers(scope, tcScope, g)\n ) {\n allowed = false;\n reason = `Outside what your team's “${tcNamed?.name}” policy allows`;\n path = `sharingPurposePolicies[${tc?.policy.id}].infoScope (policy “${tcNamed?.name}” — ${SHARE_LEVEL_LABEL.team}; a ceiling over “${govName}”)`;\n }\n if (allowed && !req && tc !== null) {\n const why = `Outside what your team's “${tcNamed?.name}” policy allows`;\n const outRows = new Set<string>();\n if (tcScope !== null && !scopeListStrictlyCovers(scope, tcScope, g)) {\n for (const r of outside((x) => scopeListCovers(scope, tcScope, g, x)))\n outRows.add(r);\n }\n const tcRows = own<unknown>(tcItems, g);\n if (isStringList(tcRows)) {\n const keep = new Set(tcRows);\n const kept = (r: string): boolean =>\n keep.has(r) ||\n scope.ancestorsOf(r).some((a) => a !== g && keep.has(a));\n for (const r of outside(kept)) outRows.add(r);\n }\n for (const r of outRows)\n if (!floorItems.includes(r) && !excludedItems.includes(r))\n teamExcludedItems.push(r);\n if (teamExcludedItems.length > 0) teamExcludedReason = why;\n }\n // the group flip: every leaf row withheld → the category is withheld. A category that\n // carries fields of its own (`hasOwnScopeContent`) and whose every leaf is under the\n // platform floor is not flipped: the floor withholds those rows only, and the category's\n // own fields still go. The three per-kind \"Contact & safety\" rows have that shape — their\n // one child is the safe-locations floor, while another person's phones, emails and contact\n // log ride the category itself (rule 1: `contact_info` → `<kind>.contact`; the prototype's\n // share builder `resolveHome`, and its composer catalog, which lists no floor row, so the\n // prototype never withholds the category for it — prototype @ 72d045ab\n // `HTI_SHARE_SCOPE_GROUPS` `offenders.contact` items: []).\n const floorOnlyOwnContent =\n leaves.length > 0 &&\n leaves.every((r) => floorItems.includes(r)) &&\n hasOwnScopeContent(scope, g);\n if (\n allowed &&\n (!req || platformRequired !== null) &&\n leaves.length > 0 &&\n !floorOnlyOwnContent\n ) {\n const gone = new Set(\n [...floorItems, ...excludedItems, ...teamExcludedItems].filter((r) =>\n leaves.includes(r),\n ),\n );\n if (gone.size >= leaves.length) {\n allowed = false;\n if (leaves.every((r) => floorItems.includes(r))) {\n reason = \"Never shared — under the platform safety floor\";\n path = \"HTI_PLATFORM_SAFETY_FLOOR\";\n } else if (leaves.some((r) => excludedItems.includes(r))) {\n reason = excludedReason ?? reason;\n } else {\n reason = teamExcludedReason ?? reason;\n }\n }\n }\n out[g] = {\n allowed,\n reason,\n rulePath: path,\n platformRequired,\n floorItems: uniq(floorItems),\n excludedItems: uniq(excludedItems),\n excludedReason,\n teamExcludedItems: uniq(teamExcludedItems),\n teamExcludedReason,\n };\n if (allowed) allowedCategories.push(g);\n }\n\n return {\n allowed: !excludedAll,\n posture,\n postureSource,\n excluded,\n reportCarveOut,\n governing: govNamed,\n teamCeiling: tcNamed,\n inside,\n scope: out,\n allowedCategories,\n rulePath,\n };\n}\n","/**\n * EVENT-DRIVEN SHARING — which listeners an event fires (Kickoff 13 build\n * item 9a; Crysta 2026-10-19 14:26 \"enabling vs firing\"; home ruled\n * 2026-11-01: platform-common exports `ShareEvent` + `fireShareEvent(policies,\n * event)` as a pure function, and each app calls it after commit at session\n * submit and case close).\n *\n * Contract of record: platform-prototype `src/data.js` — `TRIGGER_EVENTS`,\n * `policyIsListener`, `listenersFor`, `fireShareEvent` (K13-9a\n * EVENT-LISTENER 2026-10-22).\n *\n * ENABLING is a Policy with the `ongoing` cadence and a trigger, linked team\n * → team or team → partner: standing permission, authored by the Member\n * Admin. FIRING writes an ORDINARY share — the policy's purpose and version\n * on it — down the normal notify → review → claim path; only the author\n * differs.\n *\n * This module answers ONE question and decides nothing else: given the\n * sending account's policy documents and an event raised by a team, which\n * listeners fire, and to whom. Everything a manual share of that purpose\n * would be held to still applies and stays where it lives — the app sends\n * each answer through its own send door: `resolveShare` for what may leave\n * (and the policy's posture — `approval` waits, `blocked` holds), the release\n * for a partner (one that covers the `ongoing` cadence), the account's\n * catalog, the floor. A fired share is never a way around a rule.\n *\n * THE CALLER'S TWO DUTIES. (1) A link is read from the policy document's own\n * `assignments`; pass the account's team rows as `options.teamRows` (or check\n * `teamRowId` against your row store before sending) so a link whose row was\n * deleted, or no longer says what the document says, fires nothing. (2) An\n * event that can happen more than once on one subject (a note, a service, a\n * status change) needs its own `ref`, or the second is taken for the first.\n *\n * Pure: no I/O, no clock, no randomness. The same input gives the same\n * output, so a caller can run it twice and compare `key`s to fire each\n * listener ONCE per event per subject (pass the keys already written as\n * `alreadyFired`).\n */\n\nimport {\n attachmentIndexFromPolicies,\n type SharePolicyAssignment,\n type SharePolicyDoc,\n type ShareRecipient,\n type ShareTeamRowLike,\n} from \"./resolve.js\";\n\n/**\n * The events a listener may name. A trigger is a flag over EXISTING codes —\n * the CVC-285 event names the platform already emits — and mints no new CVC\n * (open point 5's default). The subset a case or a share can raise, in the\n * prototype's order and words.\n */\nexport const SHARE_TRIGGER_EVENTS = Object.freeze([\n { code: \"sessionSubmitted\", label: \"Session submitted\", group: \"case\" },\n { code: \"caseOpened\", label: \"Case opened\", group: \"case\" },\n { code: \"caseStatusChanged\", label: \"Case status changed\", group: \"case\" },\n { code: \"caseCloseRuled\", label: \"Case closed\", group: \"case\" },\n {\n code: \"determinationIssued\",\n label: \"Determination issued\",\n group: \"case\",\n },\n { code: \"serviceLogged\", label: \"Service logged\", group: \"case\" },\n { code: \"noteAdded\", label: \"Note added\", group: \"case\" },\n { code: \"shareClaimed\", label: \"Share you sent claimed\", group: \"share\" },\n {\n code: \"referralClaimed\",\n label: \"Referral you sent claimed\",\n group: \"share\",\n },\n {\n code: \"shareAcknowledged\",\n label: \"Share you sent acknowledged\",\n group: \"share\",\n },\n] as const);\n\nexport type ShareTriggerEventCode =\n (typeof SHARE_TRIGGER_EVENTS)[number][\"code\"];\n\n/** The two events the apps raise today (session submit · case close). */\nexport const SHARE_EVENT = Object.freeze({\n SESSION_SUBMITTED: \"sessionSubmitted\",\n CASE_CLOSED: \"caseCloseRuled\",\n} as const satisfies Record<string, ShareTriggerEventCode>);\n\n/** The words a person reads for a trigger code (the code itself when unknown). */\nexport function shareTriggerLabel(code: string): string {\n return SHARE_TRIGGER_EVENTS.find((t) => t.code === code)?.label ?? code;\n}\n\n/** Something that happened on a case or a session, raised by the team that did it. */\nexport interface ShareEvent {\n /** The CVC-285 event name (`SHARE_EVENT`, `SHARE_TRIGGER_EVENTS`). */\n readonly event: string;\n /**\n * The ACTING team — a listener is a link FROM a team, so an event with no\n * team fires nothing.\n */\n readonly teamId: string | null | undefined;\n /** Informational: `policies` must already be the sending account's documents. */\n readonly accountId?: string | null;\n readonly caseId?: string | null;\n readonly sessionId?: string | null;\n /**\n * What the event is about, for the once-only key. Default: the session id\n * for `sessionSubmitted`; for every other event the case id, else the\n * session id; else none (every such event shares one key). Pass it\n * explicitly for an event that can repeat on one case.\n */\n readonly ref?: string | null;\n}\n\n/** One listener: a policy with the `ongoing` cadence and a trigger, on one team link. */\nexport interface ShareListener {\n readonly policy: {\n readonly id: string;\n readonly familyId: string;\n readonly name: string;\n readonly version: number;\n };\n readonly purpose: string;\n readonly fromTeamId: string;\n /** The link's row — what `resolveShare` takes as `teamRowId`. */\n readonly teamRowId: string;\n /** Who it sends to, in the resolver's own vocabulary. */\n readonly recipient: Extract<\n ShareRecipient,\n { kind: \"partner\" } | { kind: \"sibling_team\" }\n >;\n /** A team → partner-team link names the partner's team; else `null`. */\n readonly partnerTeamId: string | null;\n /** The events it listens for. */\n readonly events: readonly string[];\n}\n\n/** One listener an event raised — the share the app is to write. */\nexport interface FiredShare extends ShareListener {\n readonly event: string;\n readonly ref: string | null;\n /**\n * Stable for one event × subject × policy × sending team × recipient: the\n * same event on the same case fires each listener ONCE. Opaque — compare\n * it, never parse it.\n */\n readonly key: string;\n}\n\nconst str = (v: unknown): v is string => typeof v === \"string\" && v !== \"\";\n\n/**\n * A policy that listens: live, `ongoing` cadence, at least one trigger event\n * (data.js `policyIsListener`) — and NOT a share-back policy\n * (`trigger.answers === \"received\"`, K13-9b), which answers a share received\n * and never fires on a case event.\n */\nexport function policyIsShareListener(\n p: SharePolicyDoc | null | undefined,\n): boolean {\n if (p === null || p === undefined || typeof p !== \"object\") return false;\n if (p.active === false) return false;\n // strictly `true` (the prototype accepts any truthy value; a stored `1` or\n // `\"true\"` does not listen here — fail closed)\n if (p.cadences?.ongoing !== true) return false;\n const on = p.trigger?.on;\n if (!Array.isArray(on) || !on.some(str)) return false;\n return p.trigger?.answers !== \"received\";\n}\n\ntype PairLink = Extract<SharePolicyAssignment, { scope: \"team_pair\" }>;\n\n/**\n * Where a team link sends, or `null` when the link does not say (never\n * guessed) — data.js `listenersFor`: a row with no partner whose `with` is a\n * team is a team → team link; with a partner, `with` (a team) names the\n * partner's team.\n */\nfunction linkTarget(\n a: PairLink,\n): Pick<ShareListener, \"recipient\" | \"partnerTeamId\"> | null {\n const withTeam =\n a.with !== null &&\n typeof a.with === \"object\" &&\n a.with.type === \"team\" &&\n str(a.with.id)\n ? a.with.id\n : null;\n if (str(a.partnerId)) {\n return {\n recipient: { kind: \"partner\", id: a.partnerId },\n partnerTeamId: withTeam,\n };\n }\n if (withTeam !== null) {\n return {\n recipient: { kind: \"sibling_team\", teamId: withTeam },\n partnerTeamId: null,\n };\n }\n return null;\n}\n\n/** Collision-free whatever the ids contain. */\nconst targetKey = (\n l: Pick<ShareListener, \"recipient\" | \"partnerTeamId\">,\n): readonly (string | null)[] =>\n l.recipient.kind === \"partner\"\n ? [\"partner\", l.recipient.id, l.partnerTeamId]\n : [\"team\", l.recipient.teamId, null];\n\n/** Does the account's row store still say what the link says? */\nfunction rowAgrees(\n rows: readonly ShareTeamRowLike[],\n a: PairLink,\n target: Pick<ShareListener, \"recipient\" | \"partnerTeamId\">,\n): boolean {\n const row = rows.find(\n (r) => r !== null && typeof r === \"object\" && r.id === a.teamRowId,\n );\n if (row === undefined || row.myTeamId !== a.teamId) return false;\n const theirTeam =\n row.their?.type === \"team\" && str(row.their.id) ? row.their.id : null;\n return target.recipient.kind === \"sibling_team\"\n ? theirTeam === target.recipient.teamId\n : theirTeam === target.partnerTeamId;\n}\n\n/**\n * The listeners linked FROM one team (data.js `listenersFor`): each listening\n * policy × each of its team → team / team → partner links whose sending team\n * is `teamId`. A link that names no sending team, a different team, or no\n * target is not a listener for this team. The policy must also be the one\n * that HOLDS the row's cell for its purpose (`attachmentIndexFromPolicies` —\n * two live documents on one cell: the later wins, exactly as the ladder\n * reads it), so the share a listener fires is governed by that same policy.\n * Two links of one policy to the same place are one listener (the first, in\n * document order). `options.event` keeps only the policies listening for\n * that event; `options.teamRows`, when given, drops a link whose row is gone\n * or disagrees with it.\n */\nexport function shareListenersFor(\n policies: readonly SharePolicyDoc[] | null | undefined,\n teamId: string | null | undefined,\n options: {\n readonly event?: string | null;\n readonly teamRows?: readonly ShareTeamRowLike[] | null;\n } = {},\n): ShareListener[] {\n if (!Array.isArray(policies) || !str(teamId)) return [];\n const cells = attachmentIndexFromPolicies(policies).teamRows;\n const rows = Array.isArray(options.teamRows) ? options.teamRows : null;\n const out: ShareListener[] = [];\n const seen = new Set<string>();\n for (const p of policies) {\n if (!policyIsShareListener(p) || !str(p.id) || !str(p.purpose)) continue;\n const events = (p.trigger?.on ?? []).filter(str);\n if (str(options.event) && !events.includes(options.event)) continue;\n for (const a of Array.isArray(p.assignments) ? p.assignments : []) {\n if (a === null || typeof a !== \"object\" || a.scope !== \"team_pair\")\n continue;\n if (!str(a.teamRowId) || a.teamId !== teamId) continue;\n // the cell's holder listens; a document another one displaced does not\n if (cells[a.teamRowId]?.[p.purpose] !== p.id) continue;\n const target = linkTarget(a);\n if (target === null) continue;\n if (rows !== null && !rowAgrees(rows, a, target)) continue;\n // a team never listens to itself\n if (\n target.recipient.kind === \"sibling_team\" &&\n target.recipient.teamId === teamId\n )\n continue;\n const dedupe = JSON.stringify([p.id, ...targetKey(target)]);\n if (seen.has(dedupe)) continue;\n seen.add(dedupe);\n out.push({\n policy: {\n id: p.id,\n familyId: str(p.familyId) ? p.familyId : p.id,\n name: str(p.name) ? p.name : p.id,\n version: parseInt(String(p.version), 10) || 1,\n },\n purpose: p.purpose,\n fromTeamId: teamId,\n teamRowId: a.teamRowId,\n ...target,\n events,\n });\n }\n }\n return out;\n}\n\n/** The once-only key of one fired share (see `FiredShare.key`). */\nexport function firedShareKey(\n event: string,\n ref: string | null,\n listener: Pick<\n ShareListener,\n \"policy\" | \"fromTeamId\" | \"recipient\" | \"partnerTeamId\"\n >,\n): string {\n return JSON.stringify([\n event,\n ref,\n listener.policy.id,\n listener.fromTeamId,\n ...targetKey(listener),\n ]);\n}\n\n/**\n * FIRING (data.js `fireShareEvent`, the pure half): the listeners linked from\n * the acting team that listen for this event, each as the share to write.\n * Call it AFTER the event's own write commits. `[]` when the event names no\n * team or no event, when nothing listens — and for every listener whose key\n * is in `alreadyFired` (what the app has written for this event before).\n *\n * The app then sends each one as an ordinary share of `purpose` to\n * `recipient` from `fromTeamId` on `teamRowId`, stamped with `policy`, through\n * its own send door. This function never decides what leaves or whether it\n * may.\n */\nexport function fireShareEvent(\n policies: readonly SharePolicyDoc[] | null | undefined,\n event: ShareEvent | null | undefined,\n options: {\n readonly alreadyFired?: Iterable<string> | null;\n readonly teamRows?: readonly ShareTeamRowLike[] | null;\n } = {},\n): FiredShare[] {\n if (event === null || event === undefined || !str(event.event)) return [];\n const session = str(event.sessionId) ? event.sessionId : null;\n const kase = str(event.caseId) ? event.caseId : null;\n const ref = str(event.ref)\n ? event.ref\n : event.event === SHARE_EVENT.SESSION_SUBMITTED\n ? (session ?? kase)\n : (kase ?? session);\n const done = new Set(options.alreadyFired ?? []);\n const fired: FiredShare[] = [];\n for (const l of shareListenersFor(policies, event.teamId, {\n event: event.event,\n teamRows: options.teamRows ?? null,\n })) {\n const key = firedShareKey(event.event, ref, l);\n if (done.has(key)) continue;\n fired.push({ ...l, event: event.event, ref, key });\n }\n return fired;\n}\n","/**\n * Reading a STORED SHARING POLICY's information-scope list — once, for every\n * app (CVC-236 `core-information_scope`, the version-4 tree).\n *\n * WHAT THIS IS FOR. Every sharing policy the Admin Hub has stored is the old\n * category names with NO version mark (`scopeVersion` absent). PAVE and Thread\n * each read that unmarked list their own way, and the two readings differed\n * (Thread's left out the instrument Summary rows). {@link readStoredPolicyScope}\n * is the one reading both call, so they cannot differ.\n *\n * THE RULE (PAVE pave-2.0 #2358, merge 38b1008a6 —\n * `storedPolicyScopeReadingV4` + `migrateUnstampedPolicySeedToV3` + `termV4`;\n * ADR-CONTRACT-policy-ceiling-shared-resolver § 13; reproduced here exactly):\n *\n * - A list MARKED version 3 or 4 is read at its mark, as it is. A marked\n * list never gains the rows the table below adds.\n * - An UNMARKED list (an array, with `scopeVersion` absent or `null`) is\n * carried forward through the codebook's published old → new conversion,\n * oldest step first: canon's v2 → v3 CATEGORY lines\n * ({@link UNMARKED_POLICY_CATEGORY_LINES}), then the resolver's own\n * v3 → v4 policy reading (`readSelection(…, 3, { subject: \"policy\" })`,\n * the SOT's `migrations.table`). A code that is not one of the old\n * category names is not guessed at: it includes nothing and is reported\n * in `unknown`.\n * - A mark that is not the number 3 or 4 (the string \"3\", the number 2)\n * cannot be read: the list includes nothing. Nothing is guessed.\n * - A list that names nothing permits NOTHING (`permits` is `[]`) — never\n * \"metadata only\", although every reading contains `system_info`.\n * Metadata only is an answer only when the list itself names the metadata\n * row. \"Names nothing\" is judged on the rows the CALLING APP carries, so\n * the app is a required argument: a list naming only categories that app\n * never carries permits nothing there.\n *\n * POLICY LISTS ONLY. This applies to a sharing policy's `infoScope` and to\n * nothing else. A share, a release, a preset, a restriction and a viewing\n * list keep the developers' rule of 2026-10-10: an unmarked list includes\n * nothing (the resolver's `readSelection` / `readRestriction` with no stamp).\n * Do not call this for them.\n *\n * THE TABLE. {@link UNMARKED_POLICY_CATEGORY_LINES} is canon's, verbatim:\n * `data/cvcs/core_information_scope.yaml` `migrations.categories`, L559-L564\n * @ htilabstech/prototype 00179edc — the v2 → v3 table the SOT's\n * `migrations.unstamped` and `migrations.readAt` point at (\"L539-565 @\n * 00179edc\"). They are the same three lines PAVE transcribed; PAVE deletes its\n * copy when it adopts this call, and until then there are two. This one is\n * held to canon by a pin: `src/__sot__/informationScopeV2V3Categories.pin.json`\n * (derived by `scripts/sot-pins.ts` from the yaml's `migrations_history`), and\n * a test fails when the constant and the pin differ. It is not a second\n * v3 → v4 table and not a codebook.\n *\n * Pure: no I/O, no SOT import — pass the bound v4 tree, as every reader in\n * this module takes it.\n */\nimport {\n INFORMATION_SCOPE_SYSTEM_INFO,\n type InformationScopeResolver,\n type ScopeApp,\n} from \"../services/informationScopeResolver.js\";\n\n/** The tree as this reader needs it. */\nexport type StoredPolicyScopeTree = Pick<InformationScopeResolver, \"readSelection\" | \"row\">;\n\n/**\n * The old category names an unmarked policy list may carry: the eight a policy\n * is authored in, and the four LEADS-only categories (recognised so they read\n * as themselves; an app that never carries them drops them by `app`).\n */\nexport const UNMARKED_POLICY_CATEGORY_CODES = [\n \"identifying\",\n \"risk\",\n \"contact\",\n \"services\",\n \"notes\",\n \"health_accommodation\",\n \"immigration_legal_status\",\n \"system\",\n \"network_associations\",\n \"commercial_activity\",\n \"investigative_work_product\",\n \"object_identifiers\",\n] as const;\n\n/**\n * Canon's v2 → v3 CATEGORY lines, verbatim (see the module header). A line\n * fires when EVERY `allOf` name is in the list and ADDS `to`. \"Every Full row\n * stays off.\"\n */\nexport const UNMARKED_POLICY_CATEGORY_LINES: readonly {\n readonly to: readonly string[];\n readonly allOf: readonly string[];\n}[] = [\n {\n to: [\n \"summary_initial_screen\",\n \"summary_lap\",\n \"summary_danger_assessment\",\n \"summary_stalking_assessment\",\n \"summary_injury_and_strangulation\",\n \"summary_ae_intake\",\n \"summary_tra\",\n ],\n allOf: [\"risk\"],\n },\n {\n to: [\n \"summary_mental_health_screen\",\n \"summary_behavioral_health_intake\",\n \"summary_trauma_and_coping_screen\",\n ],\n allOf: [\"risk\", \"health_accommodation\"],\n },\n { to: [\"summary_needs_assessment\"], allOf: [\"services\"] },\n];\n\n/** The version an unmarked list is read at once the category lines are applied. */\nexport const UNMARKED_POLICY_CARRY_VERSION = 3 as const;\n\nconst CATEGORY_CODES: ReadonlySet<string> = new Set(UNMARKED_POLICY_CATEGORY_CODES);\n\nconst strings = (list: unknown): string[] =>\n Array.isArray(list) ? list.filter((c): c is string => typeof c === \"string\") : [];\n\n/**\n * The first step for an unmarked policy list: the list it reads as at version\n * 3 (its category names plus the rows the category lines add), and the codes\n * that are not old category names (`refused` — they include nothing).\n */\nexport function carryUnmarkedPolicyList(list: unknown): { list: string[]; refused: string[] } {\n const stored = strings(list);\n const categories = stored.filter((c) => CATEGORY_CODES.has(c));\n const refused = stored.filter((c) => !CATEGORY_CODES.has(c));\n const named = new Set(categories);\n const added = UNMARKED_POLICY_CATEGORY_LINES.filter((line) =>\n line.allOf.every((c) => named.has(c)),\n ).flatMap((line) => line.to);\n return { list: [...new Set([...categories, ...added])], refused };\n}\n\n/**\n * What the reader did:\n * - `marked` — the list carried a readable mark and was read at it;\n * - `carried` — the list had no mark and was carried forward (above);\n * - `empty` — the list permits nothing (it names nothing `options.app`\n * carries, or its mark cannot be read).\n */\nexport type StoredPolicyScopeOutcome = \"marked\" | \"carried\" | \"empty\";\n\nexport interface StoredPolicyScopeReading {\n readonly outcome: StoredPolicyScopeOutcome;\n /** The list had no version mark (an array with `scopeVersion` absent or `null`). */\n readonly unmarked: boolean;\n /** The mark as stored when it is a number; otherwise `null`. Never inferred. */\n readonly storedVersion: number | null;\n /** The list as stored (its string codes) — never rewritten. */\n readonly stored: readonly string[];\n /**\n * The list as read on the current tree: unique, tree order, always\n * containing `system_info` (the resolver's reading). Use `permits` to decide\n * what the policy allows.\n */\n readonly informationScope: readonly string[];\n /**\n * What the policy permits: `informationScope`, or `[]` when the list names\n * nothing (\"an empty term stays empty\").\n */\n readonly permits: readonly string[];\n /** Stored codes whose reading is wider than at version 3 (surface, never hide). */\n readonly widened: readonly string[];\n /** Stored codes that are retired and read through the table. */\n readonly retired: readonly string[];\n /** Stored codes with no reading; they include nothing. */\n readonly unknown: readonly string[];\n /** The mark is present and is not the number 3 or 4, or a non-list had no mark. */\n readonly unsupportedVersion: boolean;\n /**\n * The app writes a dated version row before acting on this reading: true\n * for a version-3 list and for an unmarked list carried forward.\n */\n readonly versionRowRequired: boolean;\n}\n\nexport interface ReadStoredPolicyScopeOptions {\n /**\n * REQUIRED — the app that is reading. \"Names nothing\" is judged on the rows\n * this app carries (the row's `apps` flag): a list naming only categories\n * the app never carries permits nothing. PAVE passes `\"pave\"`, Thread\n * `\"thread\"`. There is no default and no \"every row\" value: leaving the app\n * out would be the widest answer, and could allow what PAVE refuses.\n */\n readonly app: ScopeApp;\n}\n\nconst APPS: ReadonlySet<string> = new Set<ScopeApp>([\"pave\", \"thread\", \"leads\"]);\n\n/**\n * Read one stored sharing-policy `infoScope` list on the current tree. Total\n * on stored data (`list`, `versionMark`): never throws on it. Throws a\n * `RangeError` when `options.app` is missing or not an app — a caller's\n * mistake, never a stored value. See the module header for the rule; POLICY\n * lists only.\n *\n * @param scope the bound CVC-236 v4 tree\n * @param list the stored `infoScope`\n * @param versionMark the stored `scopeVersion` (`undefined` / `null` = unmarked)\n * @param options `{ app }` — the app that is reading (required)\n */\nexport function readStoredPolicyScope(\n scope: StoredPolicyScopeTree,\n list: unknown,\n versionMark: unknown,\n options: ReadStoredPolicyScopeOptions,\n): StoredPolicyScopeReading {\n const app = (options as ReadStoredPolicyScopeOptions | undefined)?.app;\n if (typeof app !== \"string\" || !APPS.has(app)) {\n throw new RangeError(\n 'readStoredPolicyScope: options.app must be \"pave\", \"thread\" or \"leads\" (the app that is reading)',\n );\n }\n const stored = strings(list);\n const unmarked = Array.isArray(list) && (versionMark === undefined || versionMark === null);\n const stamp = typeof versionMark === \"number\" ? versionMark : null;\n\n const forward = unmarked ? carryUnmarkedPolicyList(stored) : null;\n const read = forward\n ? scope.readSelection(forward.list, UNMARKED_POLICY_CARRY_VERSION, { subject: \"policy\" })\n : scope.readSelection(stored, stamp, { subject: \"policy\" });\n const unknown = forward ? [...new Set([...read.unknown, ...forward.refused])] : read.unknown;\n\n // \"An empty term stays empty\": the reader adds `system_info` to every\n // reading, which must not turn \"names nothing\" into \"metadata only\".\n const counted = read.informationScope.filter((c) => scope.row(c)?.apps[app] === true);\n const namesARow = counted.some((c) => c !== INFORMATION_SCOPE_SYSTEM_INFO);\n // The list names the metadata row only when the reading ACCEPTED that code:\n // an unmarked list is category names, so `system` counts and the row code\n // `system_info` is refused (reported `unknown`).\n const namesMetadata = stored.some(\n (c) => (c === \"system\" || c === INFORMATION_SCOPE_SYSTEM_INFO) && !unknown.includes(c),\n );\n const permits = namesARow || namesMetadata ? read.informationScope : [];\n\n return {\n outcome: permits.length === 0 ? \"empty\" : unmarked ? \"carried\" : \"marked\",\n unmarked,\n storedVersion: unmarked ? null : stamp,\n stored,\n informationScope: read.informationScope,\n permits,\n widened: read.widened,\n retired: read.retired,\n unknown,\n unsupportedVersion: read.unsupportedVersion,\n versionRowRequired: read.versionRowRequired,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;AC8BO,IAAM,kCAAkC;AAAA,EAC7C,YAAY;AAAA,IACV,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,SAAS;AAAA,MACP;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,IACP,gBAAgB;AAAA,MACd;AAAA,MACA;AAAA,IACF;AAAA,IACA,gBAAgB;AAAA,MACd;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA,EACA,mBAAmB;AAAA,IACjB,QAAQ;AAAA,IACR,QAAQ;AAAA,IACR,OAAO;AAAA,EACT;AACF;AAGO,IAAM,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