@htilabs/platform-common-models 0.85.0 → 0.86.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.
- package/README.md +12 -0
- package/dist/index.cjs +12 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +12 -1
- package/dist/index.js.map +1 -1
- package/dist/org-directory/index.cjs +8 -2
- package/dist/org-directory/index.cjs.map +1 -1
- package/dist/org-directory/index.d.cts +11 -2
- package/dist/org-directory/index.d.ts +11 -2
- package/dist/org-directory/index.js +8 -2
- package/dist/org-directory/index.js.map +1 -1
- package/dist/org-merge/index.cjs +8 -2
- package/dist/org-merge/index.cjs.map +1 -1
- package/dist/org-merge/index.js +8 -2
- package/dist/org-merge/index.js.map +1 -1
- package/dist/points-of-contact/index.cjs +8 -2
- package/dist/points-of-contact/index.cjs.map +1 -1
- package/dist/points-of-contact/index.js +8 -2
- package/dist/points-of-contact/index.js.map +1 -1
- package/dist/schemas/index.cjs +12 -1
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +32 -2
- package/dist/schemas/index.d.ts +32 -2
- package/dist/schemas/index.js +12 -1
- package/dist/schemas/index.js.map +1 -1
- package/package.json +1 -1
- package/src/orgDirectory/__tests__/programDetails.test.ts +2 -1
- package/src/orgDirectory/__tests__/programTeamLink.test.ts +107 -0
- package/src/orgDirectory/schemas.ts +8 -1
- package/src/schemas/organization-program.ts +25 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/pointsOfContact/index.ts","../../src/cvcs/preferredContactMethod.v1.1.0.json","../../src/pointsOfContact/vocabulary.ts","../../src/pointsOfContact/schemas.ts","../../src/pointsOfContact/readRules.ts","../../src/pointsOfContact/reader.ts","../../src/pointsOfContact/writer.ts","../../src/orgDirectory/schemas.ts","../../src/orgDirectory/vocabulary.ts","../../src/orgDirectory/orgRecord.ts","../../src/orgDirectory/programDetails.ts","../../src/orgDirectory/rules.ts","../../src/orgDirectory/read.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models/points-of-contact\n *\n * The Point of contact contract (pl-3r8): the platform-db `pointsofcontact`\n * collection's vocabularies, Zod schemas, stored and view types, read rules\n * (network vs owner view, confidential exclusion, the Referrals (magic link)\n * partner rollup with its confidential-holder count and send-only\n * `resolveMagicLinkRecipients` / `ConfidentialReferralRecipients`, pl-iza)\n * and raw-driver reads, plus the ONE shared writer every app\n * runs: the in-app partner add (`mintPartnerContact`, pl-bt1) and the index\n * set it relies on (`ensurePocIndexes`). Pure TypeScript, no mongoose, no\n * driver import. The platform app owns every other write (its own Admin Hub,\n * survey, edits, confirm, seed: `platform lib/points-of-contact/`); Thread,\n * PAVE and LEADS read through this module and write a pending in-app add\n * through it directly, without an HTTP hop. Subpath only (not re-exported from\n * the package root).\n */\n\nexport * from \"./vocabulary.js\";\nexport * from \"./schemas.js\";\nexport * from \"./readRules.js\";\nexport * from \"./reader.js\";\nexport * from \"./writer.js\";\n","{\n \"domain\": \"preferred_contact_method\",\n \"name\": \"Core Preferred Contact Method\",\n \"version\": \"1.1.0\",\n \"_status\": \"CANONICAL -- Notion CVC-185 `core-preferred_contact_method` v1.1 (IC-2 Contact Info). Page Status in the canon capture at generation: 'Active'; yaml mirror `vocab_status: canonical`. Exported from prototype canon @ a5ecd452. WHAT IT IS: the PERSON-level routing preference -- which channel a person prefers to be reached on, when it is safe. A preference is not permission: it never overrides a contact entry's safety flags. The Agency Hub reuses a declared subset (Email, Call, Text) for an agency contact's time-sensitive channels. TWO LABEL REGISTERS per entry, both from canon: `title` is the word the apps render (yaml `display_name`); `codebookLabel` is the Notion codebook Label (yaml `codebook_label`). Where they differ the divergence is declared in canon. Show `title` in UI. STORAGE: the package key and the positional code are FROZEN at first publication (2026-04-22) because apps store them; `canonicalCode` is canon's UPPER_SNAKE code. APP keeps the key `messaging_app_dm` (its pre-2026-09-01 code name, which canon keeps as a legacy alias). `legacyValueMap` maps an inbound spelling (lower-cased) to the canonical code. LEVEL 0 NOT MIRRORED: canon also defines UNK, ANON and DNC; no picker offers them (UNK and ANON arrive through decline affordances, DNC is system-stamped) and they are left out of this version so no consumer key tuple changes. Wording is verbatim from the Notion codebook capture and the yaml mirror. Generated by scripts/gen-preferred-contact-method.py -- do not hand-edit.\",\n \"_source\": \"htilabstech/prototype/data/cvcs/core_preferred_contact_method.yaml @ a5ecd452 (read from origin/main) + htilabstech/prototype/Final CVCs/Contact Info (IC-2)/core-preferred_contact_method — codebook.csv + htilabstech/prototype/Final CVCs/Contact Info (IC-2)/core-preferred_contact_method.md @ a5ecd452 (CVC-185 v1.1)\",\n \"levels\": {\n \"1\": \"Contact method\"\n },\n \"legacyValueMap\": {\n \"app\": \"APP\",\n \"call\": \"CALL\",\n \"email\": \"EMAIL\",\n \"messaging_app_dm\": \"APP\",\n \"text\": \"TEXT\"\n },\n \"pickers\": {\n \"pave_contact_info_prefs_bar\": [\n \"TEXT\",\n \"CALL\",\n \"EMAIL\",\n \"APP\"\n ],\n \"leads_contact_info_prefs_bar\": [\n \"TEXT\",\n \"CALL\",\n \"EMAIL\",\n \"APP\"\n ],\n \"platform_agency_hub_urgent_methods\": [\n \"EMAIL\",\n \"CALL\",\n \"TEXT\"\n ]\n },\n \"pickerExclusions\": {\n \"platform_agency_hub_urgent_methods\": {\n \"APP\": \"An agency contact is reached at work, through channels the agency controls and can hand over when someone leaves. A personal messaging-app or social DM is neither, so the Agency Hub does not offer it. Excluded deliberately at the 2026-09-01 transition, not an oversight — if an agency ever asks for it, add APP here rather than minting an agency-side code.\"\n }\n },\n \"entries\": [\n {\n \"code\": \"185-001-000-000-000-000-000\",\n \"key\": \"call\",\n \"title\": \"Call\",\n \"codebookLabel\": \"Call (voice)\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be contacted by phone call when safe and appropriate.\",\n \"canonicalCode\": \"CALL\",\n \"guidance\": \"Person-level preference only. Requires at least one phone entry that is safe to contact by call (and, if applicable, voicemail rules captured at entry level).\",\n \"logicNotes\": \"If no safe phone entry exists, warn and prompt to add/update a safe phone method or remove this preference.\\n\\nThe CALL warning is phone-only and requires safe_to_call: a non-phone entry never satisfies it, whatever its safety flags. safe_to_call is canonical-by-CVC despite IC-2 § 2 enumerating only safe_to_text + safe_to_leave_voicemail (Data-2 codification, 2026-05-26) — do not retire it to \\\"align to the IC\\\".\\n\\nCode canonicalized to UPPERCASE CALL on 2026-09-01 (CVC185-AUDIT). Legacy lowercase call normalizes to CALL on read.\"\n },\n {\n \"code\": \"185-002-000-000-000-000-000\",\n \"key\": \"text\",\n \"title\": \"Text\",\n \"codebookLabel\": \"Text (SMS)\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be contacted via text message (SMS) when safe and appropriate.\",\n \"canonicalCode\": \"TEXT\",\n \"guidance\": \"Requires a phone/contact entry that explicitly supports safe-to-text. Do not infer texting safety from general ‘safe to contact’.\",\n \"logicNotes\": \"If selected but no contact entry has safe_to_text=true, warn and offer quick fix: remove preference or update contact method safety flags.\\n\\nCode canonicalized to UPPERCASE TEXT on 2026-09-01 (CVC185-AUDIT). Both PAVE and LEADS have stored the UPPERCASE form since 2026-05-26; the lowercase form on this page had never been consumed by either app. Legacy lowercase text is accepted on read by canonicalizePrefMethod (monolith) and normalizes to TEXT.\"\n },\n {\n \"code\": \"185-003-000-000-000-000-000\",\n \"key\": \"email\",\n \"title\": \"Email\",\n \"codebookLabel\": \"Email\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be contacted via email when safe and appropriate.\",\n \"canonicalCode\": \"EMAIL\",\n \"guidance\": \"Use as a person-level routing preference (not an instruction to use an unsafe email address). Pair with contact-entry safety flags; if no safe email exists, prompt user to update contact info or adjust preference.\",\n \"logicNotes\": \"Does not override entry-level safety constraints. If selected but no safe email entry exists, warn: \\\"No safe contact method supports 'Email'.\\\"\\n\\nCode canonicalized to UPPERCASE EMAIL on 2026-09-01 (CVC185-AUDIT). Legacy lowercase email normalizes to EMAIL on read.\"\n },\n {\n \"code\": \"185-004-000-000-000-000-000\",\n \"key\": \"messaging_app_dm\",\n \"title\": \"Messaging app\",\n \"codebookLabel\": \"Messaging app DM\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be reached by direct message on an app or platform — messaging apps (WhatsApp, Signal, Telegram, Kik) AND social-media DMs (Instagram, Snapchat, Facebook, X) alike — when safe and appropriate.\",\n \"canonicalCode\": \"APP\",\n \"guidance\": \"ONE routing bucket for \\\"DM me somewhere\\\", not a per-brand choice. Requires at least one app OR social-media contact entry that is safe to use. The specific platform is captured at the contact-entry level (type + domain), never here.\\n\\nRULING R2 (Ava, 2026-09-01, CVC185-AUDIT): an Instagram / Snapchat / Facebook DM satisfies this preference exactly as WhatsApp or Signal does. The contact-TYPE taxonomy (CVC-149) keeps App and Social Media as separate kinds; this person-level ROUTING preference deliberately collapses both. Do not split this into two values, and do not narrow it to messaging apps only — the routing question is the channel, not the brand.\",\n \"logicNotes\": \"Warning fires when no entry on file has type IN (app, social) AND safety=safe AND NOT do_not_contact. Both shipped implementations already test the union — monolith renderPrefBar and leads-app prefWarnings — so R2 documents shipped behaviour rather than changing it.\\n\\nCode canonicalized to APP on 2026-09-01 (CVC185-AUDIT), replacing messaging_app_dm. Two reasons: both apps have stored APP since 2026-05-26 and nothing has ever stored messaging_app_dm; and under R2 the value covers social-media DMs too, which the old code name contradicted on its face. Legacy messaging_app_dm and lowercase app both normalize to APP on read.\\n\\nAPP LABEL DIVERGENCE (declared, not drift): this codebook and IC-2 § III.3 render the label \\\"Messaging app DM\\\"; both apps render the chip as \\\"Messaging app\\\". The stored code is identical; only the presentational string differs.\"\n }\n ]\n}\n","/**\n * Point of contact vocabularies (pl-3r8): subject types, purposes, urgent\n * methods, review status and writers. Defined once here; every reader and the\n * platform writer import them.\n *\n * ## Purposes are a declared list, NOT a CVC (a CVC is owed)\n *\n * No `core-contact_purpose` CVC exists in this package. The eight codes below\n * are copied verbatim from the prototype's declared list,\n * `data/contact_purposes.yaml` @ prototype 6c2db859 (L11-L33), which states\n * \"NOT YET A CVC — minting `core-contact_purpose` is an open line for\n * Crysta\". The Notion profile (UDD — Objects \"Point of Contact Data Object\",\n * 3ec1ef14abcd81dc9a47ec37e217adc3, § 6 q2) leaves it a list \"until the sharing\n * work says whether anything routes on a purpose\". `REFERRALS_MAGIC_LINK` now\n * routes (Crysta 2026-10-14, Slack D0811D2R6QN p1792036474007189), so the mint\n * question is live. When the CVC lands, this list is replaced by it.\n *\n * The first five are the agency purposes (Crysta 2026-08-23: one contacts\n * list; Compliance · Training · Referrals (magic link) · Billing · Data &\n * reporting). The last three are program-level (Crysta 2026-10-14: \"plus\n * Program contact · Referral contact · Program Director at program level\").\n *\n * ## Urgent methods are CVC-185\n *\n * `urgent_methods` stores CVC-185 `preferred_contact_method` CODES, restricted\n * to the Agency Hub subset (email · call · text). Canon: platform-prototype\n * `src/agencyhub.jsx` @ 0fa04c1 L7937-L7963 (the declared\n * `platform_agency_hub_urgent_methods` subset omits the messaging-app DM) and\n * the prototype generator's gate (`tools/build_platform_directory.py` @\n * 6c2db859 L2577-L2580). Codes are read from the package SOT, never typed, and\n * a code the SOT marks `selectable: false` is refused.\n */\n\nimport preferredContactMethodSot from \"../cvcs/preferredContactMethod.v1.1.0.json\" with { type: \"json\" };\nimport type { PreferredContactMethodKey } from \"../generated/cvc-enums.js\";\n\n// ─── Subjects ────────────────────────────────────────────────────────\n\n/**\n * What a contact is FOR. Crysta 2026-10-14: \"a reachable person for a subject\n * (agency, program, team, site)\". `org` is added (decision D2, veto-able) for\n * a partner that exists only as an organization: Crysta's ruling that an\n * in-app add \"creates the organization and a contact\", canon `hubSavePocs`\n * stamping an empty `agency_id` when it has none (platform-prototype\n * `src/agencyhub.jsx` @ 0fa04c1 L411), and the Notion draft's proposed `org`\n * subject (§ 5). `account` is not accepted.\n *\n * ## `location` is stored; \"Site\" is displayed (pl-f4c, 0.30.0)\n *\n * The UDD names the object Site (since 2026-10-04), but its stored names, ids\n * and columns stay `location`: the schema of record is hti-features\n * `udd-schemas/location/Location.v1.json`, and the POC draft enum is\n * `agency | program | location | team`. Canon stores `location` everywhere:\n * the POC directory columns (prototype\n * `docs/leads-platform/ORG_STACK_DATA_OBJECTS_2026-10-01.md` @ fa0fd0b0 L236,\n * \"subject_type (agency · program · location · team)\"), the registry kind\n * (`leads-app/server/models/RegistryEntities.mjs` @ fa0fd0b0 L105-L117) and\n * the object-log subject enum (`leads-app/server/models/ObjectDirectoryEntry.mjs`\n * @ fa0fd0b0 L51). So the stored value is `location` and the display word is\n * {@link pocSubjectTypeLabel}'s \"Site\". 0.28.0 stored `site`; there is no prod\n * data, so `site` is simply refused (no legacy acceptance, no migration).\n *\n * `service` is a Service Listing's contact (Crysta's kickoff D4, prototype\n * `KICKOFF_SERVICE_LISTING_AND_PARTNER_CONTACT_BUILD_2026-10-14.md` @ c6380f73\n * L15: \"the listing contact is a Point of contact row (`subject_type:\n * service`, profile § 6 q3, confirmed)\"); `subject_id` is the listing id.\n *\n * An in-app add's contact sits on the partner's agency when the org has one\n * (kickoff D1, L12: \"`subject_type: agency` when the org has an agency row,\n * else the org\"); the platform writer rewrites an `org` subject whose org\n * genuinely mirrors an agency to that agency.\n */\nexport const POC_SUBJECT_TYPES = [\"agency\", \"org\", \"program\", \"team\", \"location\", \"service\"] as const;\nexport type PocSubjectType = (typeof POC_SUBJECT_TYPES)[number];\n\n/**\n * The display word for each subject type: the object names of prototype\n * `docs/leads-platform/ORG_STACK_DATA_OBJECTS_2026-10-01.md` @ fa0fd0b0 § 1\n * (L60-L68: Org · Agency · Program / department · Team · Service listing),\n * with `location` shown as \"Site\", the UDD's object name since 2026-10-04\n * (pl-f4c). Store the code, render the label.\n */\nexport const POC_SUBJECT_TYPE_LABELS: Readonly<Record<PocSubjectType, string>> = {\n agency: \"Agency\",\n org: \"Org\",\n program: \"Program\",\n team: \"Team\",\n location: \"Site\",\n service: \"Service listing\",\n};\n\n/** The display word of a subject type; an unknown type reads as itself. */\nexport function pocSubjectTypeLabel(type: string): string {\n return Object.hasOwn(POC_SUBJECT_TYPE_LABELS, type)\n ? POC_SUBJECT_TYPE_LABELS[type as PocSubjectType]\n : type;\n}\n\n// ─── Purposes ────────────────────────────────────────────────────────\n\n/** The declared purpose codes (prototype `data/contact_purposes.yaml` @ 6c2db859 L11-L33). */\nexport const CONTACT_PURPOSE_CODES = [\n \"COMPLIANCE\",\n \"TRAINING\",\n \"REFERRALS_MAGIC_LINK\",\n \"BILLING\",\n \"DATA_REPORTING\",\n \"PROGRAM_CONTACT\",\n \"REFERRAL_CONTACT\",\n \"DIRECTOR\",\n] as const;\nexport type ContactPurposeCode = (typeof CONTACT_PURPOSE_CODES)[number];\n\nexport interface ContactPurpose {\n readonly code: ContactPurposeCode;\n readonly label: string;\n /**\n * Where the prototype offers it: the agency contacts list, or a program's\n * contact slots (Crysta 2026-10-14: \"at program level\"). Informational: no\n * subject is refused a purpose (canon does not enforce it; open question).\n */\n readonly level: \"agency\" | \"program\";\n}\n\n/** The declared purpose list with labels. */\nexport const CONTACT_PURPOSES: readonly ContactPurpose[] = [\n { code: \"COMPLIANCE\", label: \"Compliance\", level: \"agency\" },\n { code: \"TRAINING\", label: \"Training\", level: \"agency\" },\n { code: \"REFERRALS_MAGIC_LINK\", label: \"Referrals (magic link)\", level: \"agency\" },\n { code: \"BILLING\", label: \"Billing\", level: \"agency\" },\n { code: \"DATA_REPORTING\", label: \"Data & reporting\", level: \"agency\" },\n { code: \"PROGRAM_CONTACT\", label: \"Program contact\", level: \"program\" },\n { code: \"REFERRAL_CONTACT\", label: \"Referral contact\", level: \"program\" },\n { code: \"DIRECTOR\", label: \"Program Director\", level: \"program\" },\n];\n\n/**\n * The magic-link purpose. A magic link goes to EVERY contact on the partner\n * carrying it (Crysta 2026-08-23, restated 2026-10-14), and a contact carrying\n * it must have an email (Crysta 2026-10-14, the Admin Hub editor rule). CVC-338\n * (prototype `data/cvcs/core_contact_purpose.yaml` @ 184893b6 L95): \"A\n * confidential holder still receives it; the sender never sees the address.\"\n * (pl-iza: `resolveMagicLinkRecipients`, `ConfidentialReferralRecipients`.)\n */\nexport const REFERRALS_MAGIC_LINK_PURPOSE: ContactPurposeCode = \"REFERRALS_MAGIC_LINK\";\n\nconst PURPOSE_BY_CODE = new Map<string, ContactPurpose>(CONTACT_PURPOSES.map((p) => [p.code, p]));\n\nexport function isContactPurposeCode(code: unknown): code is ContactPurposeCode {\n return typeof code === \"string\" && (CONTACT_PURPOSE_CODES as readonly string[]).includes(code);\n}\n\n/** The display label of a purpose code; an unknown code reads as itself. */\nexport function contactPurposeLabel(code: string): string {\n return PURPOSE_BY_CODE.get(code)?.label ?? code;\n}\n\n// ─── Urgent methods (CVC-185 subset) ─────────────────────────────────\n\n/** The Agency Hub subset of CVC-185, by key. */\nexport const POC_URGENT_METHOD_KEYS = [\"email\", \"call\", \"text\"] as const satisfies readonly PreferredContactMethodKey[];\n\nconst CVC185_ENTRIES = preferredContactMethodSot.entries;\n\nfunction cvc185Entry(key: string): (typeof CVC185_ENTRIES)[number] {\n const e = CVC185_ENTRIES.find((x) => x.key === key);\n // A re-mirror that drops one of the subset's keys must fail loudly at load,\n // never silently shrink the vocabulary.\n if (!e) throw new Error(`points-of-contact: CVC-185 preferred_contact_method has no key \"${key}\"`);\n return e;\n}\n\n/** The subset's CVC-185 entries, SOT order preserved by the subset's own order. */\nexport interface PocUrgentMethod {\n key: string;\n code: string;\n title: string;\n selectable: boolean;\n}\n\nexport const POC_URGENT_METHODS: readonly PocUrgentMethod[] =\n POC_URGENT_METHOD_KEYS.map((k) => {\n const e = cvc185Entry(k);\n return { key: e.key, code: e.code, title: e.title, selectable: e.selectable !== false };\n });\n\nconst URGENT_BY_CODE = new Map(POC_URGENT_METHODS.map((m) => [m.code, m]));\n\n/** True for a CVC-185 code in the Agency Hub subset that the SOT marks selectable. */\nexport function isPocUrgentMethodCode(code: unknown): code is string {\n return typeof code === \"string\" && URGENT_BY_CODE.get(code)?.selectable === true;\n}\n\n/** The CVC-185 code for a subset key (`email` · `call` · `text`), else null. */\nexport function pocUrgentMethodCode(key: string): string | null {\n return POC_URGENT_METHODS.find((m) => m.key === key)?.code ?? null;\n}\n\n// ─── Review status, writers ──────────────────────────────────────────\n\n/**\n * `confirmed` = visible platform-wide; `pending` = held for HTI Labs (the\n * steward). Decision D3 (veto-able), from Crysta 2026-10-14: only writer 3,\n * the in-app / steward add, is \"pending … available platform-wide after HTI\n * Labs confirms it\". The survey's Q2 contacts and the agency's own Admin Hub\n * list carry no review gate (canon `hubSavePocs` has no status), so they land\n * `confirmed` with no steward stamp. See {@link pocInitialStatus}.\n */\nexport const POC_STATUSES = [\"pending\", \"confirmed\"] as const;\nexport type PocStatus = (typeof POC_STATUSES)[number];\n\n/**\n * Who wrote the contact. Stored on the row. `steward_seed` is the reviewed\n * import of the prototype directory sheet (pl-cbu).\n */\nexport const POC_ORIGINS = [\"survey\", \"admin_hub\", \"in_app\", \"steward_seed\"] as const;\nexport type PocOrigin = (typeof POC_ORIGINS)[number];\n\n/** Where the contact was entered (null on a seed row). */\nexport const POC_ADDED_IN_APPS = [\"pave\", \"thread\", \"leads\", \"platform\"] as const;\nexport type PocAddedInApp = (typeof POC_ADDED_IN_APPS)[number];\n\n/** The status a writer's new contact starts in (D3). */\nexport function pocInitialStatus(origin: PocOrigin): PocStatus {\n return origin === \"survey\" || origin === \"admin_hub\" ? \"confirmed\" : \"pending\";\n}\n","/**\n * Point of contact schemas and stored types (pl-3r8).\n *\n * A **Point of contact** is a reachable person FOR a subject (agency, org,\n * program, team, location (shown \"Site\"), service listing), for one or more\n * purposes. It is a platform-wide record on platform-db, not something\n * created at first login (Crysta 2026-10-14,\n * Slack D0811D2R6QN p1792036474007189). Columns follow the prototype directory\n * (`Org + Personnel Registry/HTI_POINT_OF_CONTACT_DIRECTORY.csv` @ prototype\n * 6c2db859 L1): `poc_id · subject_type · subject_id · user_id | person_id ·\n * display_name · email · phone · purposes · urgent_methods · is_primary ·\n * is_confidential · active · notes`. `poc_id` is stored as `id` (the\n * hti-features schema's name).\n *\n * ## Emails and phones are lists (pl-e98, 0.30.0)\n *\n * The sheet's single `email` / `phone` columns became `emails[]` / `phones[]`\n * of {@link PocContactEntry} `{ value, is_preferred }`, Crysta's 2026-08-24\n * multi-entry correction. Canon's Admin Hub ledger keeps \"every active email\n * and phone as its own row, one preferred per type\" (platform-prototype\n * `src/agencyhub.jsx` @ 6f428116 L8096-L8106) and stores each as `{type,\n * value, preferred}` (`methodsFor` L8107-L8132, the save L8181); on a Point of\n * contact the type is the list the entry sits in. The flag is named after the\n * CONTACT rail's `is_preferred` (prototype\n * `leads-app/server/models/ObjectDirectoryEntry.mjs` @ fa0fd0b0 L52); the\n * contact-level `is_primary` (the subject's primary contact) is unrelated and\n * unchanged. No per-entry use label: CVC-154 `contact_info_use_type` is\n * investigative-only and offered by no Platform, PAVE or Thread picker\n * (prototype `data/cvcs/core_contact_info_use_type.yaml` @ fa0fd0b0 L93-L97).\n *\n * The single fields are GONE from the stored row and from every writer body\n * (no prod data, clean cut; no read shim for stored single fields). Read the\n * preferred address through {@link preferredEmail} / {@link preferredPhone};\n * every view also carries read-only `email` / `phone` projections of the\n * preferred entries, as canon's card does (L8195-L8202).\n *\n * The preferred rule. A WRITER list ({@link PocEmailListSchema} /\n * {@link PocPhoneListSchema}) holds at most one entry marked `is_preferred`\n * and is normalized to exactly one: the marked entry, else the FIRST (canon\n * L8126-L8129). It refuses the same email twice or the same phone line twice\n * (by digits, canon's `phoneDigits`, prototype\n * `leads-app/server/objectStructuresEngine.generated.mjs` @ fa0fd0b0\n * L282-L286), and a phone with no digit. A phone is stored AS TYPED, trimmed,\n * as this object's canon writer, the Admin Hub ledger, stores it\n * (`agencyhub.jsx` @ 6f428116 L8124-L8125, L8173, L8511-L8518). An extension\n * makes a distinct line: `402-677-3902 x5` and `402-677-3902` differ by\n * digits, so both may sit on one contact. {@link formatPocPhone} is a\n * DISPLAY-only helper readers apply (canon calls `formatPhone` \"display\n * only\", L229-L245). A list in an edit replaces the stored list; `[]` clears\n * it, `null` is refused.\n *\n * A STORED list is READ leniently ({@link PointOfContactDocSchema}): the same\n * normalization repairs it (emails trimmed and lowercased, empty and duplicate\n * entries dropped, a missing or null `is_preferred` read as false, no\n * preferred → the first, several → the first marked), so one row's list\n * never takes down a partner's whole read. Only structurally invalid data\n * (not an array, a non-object entry, a non-string value, a non-boolean flag)\n * throws.\n *\n * ## Known deviations (0.30.0)\n *\n * - A seat-linked contact still reads ONE email and ONE phone from `users`\n * until a person Contact log exists (pl-9h4). Canon's motivating case\n * (Crysta's own seat-linked contact) is therefore not yet met.\n * - An entry is removed, not retired: canon's write-in ledger keeps retired\n * entries stamped `retiredOn` (retire-not-remove, L8181-L8185); this list\n * keeps only the live ones.\n * - The write-in identity key uses the preferred email only\n * ({@link pocIdentityKey}, as canon's `hubSavePocs` L382-L384 uses the card's flat\n * email): changing the preferred email changes `identity_key`, and a\n * secondary email shared with another row is not deduplicated. The writer\n * maps an identity unique-index collision to a domain error (the\n * platform's job).\n *\n * ## Shapes and trust levels\n *\n * - {@link PocOwnerSchema}: WHOSE contact it is. Resolved by the platform\n * route, never read from a request body.\n * - {@link PocDetailsSchema}: what the subject's own writers (survey, Admin\n * Hub) may say about the person. `.strict()`: a body carrying `status`,\n * `origin`, `id`, `active`, a stamp or an owner key is refused.\n * - {@link PocInAppSchema}: what an advocate adding a partner may say: a\n * write-in with a name and an email, no primary / confidential / notes.\n * - {@link PocSeedSchema}: the details plus the sheet's `poc-*` id.\n * - {@link PocPatchSchema}: an edit. Identity (`user_id`, `person_id`) is\n * fixed at mint; a different person is a different contact.\n *\n * ## Whole-contact rules ({@link pocRuleViolations})\n *\n * Checked on a mint and on the MERGED document of an edit:\n * 1. `user_id` XOR `person_id` (prototype generator\n * `tools/build_platform_directory.py` @ 6c2db859 L2556-L2557).\n * 2. A seat-linked contact stores no emails or phones of its own (both\n * lists empty); they resolve from the seat (L2561-L2563; Notion profile\n * § 3 \"A contact's phone and email belong to the person\").\n * 3. A contact that is not seat-linked carries a `display_name` (L2571-L2572).\n * 4. A contact tagged Referrals (magic link) has an email (Crysta\n * 2026-10-14); the magic link goes to its preferred email. For a\n * seat-linked contact the seat must have one; the writer checks the seat.\n */\n\nimport { z } from \"zod\";\n\nimport {\n CONTACT_PURPOSE_CODES,\n POC_ADDED_IN_APPS,\n POC_ORIGINS,\n POC_STATUSES,\n POC_SUBJECT_TYPES,\n REFERRALS_MAGIC_LINK_PURPOSE,\n isPocUrgentMethodCode,\n} from \"./vocabulary.js\";\n\n/**\n * The platform-db collection. The platform writes it; the one exception is the\n * in-app partner add, which every app writes through the shared\n * `mintPartnerContact` (`./writer.ts`).\n */\nexport const POINTS_OF_CONTACT_COLLECTION = \"pointsofcontact\";\n\n/**\n * Index names. `ensurePocIndexes` (`./writer.ts`) creates them, with the\n * in-app pending and review-queue indexes; readers rely on them.\n */\nexport const POINT_OF_CONTACT_INDEXES = {\n /** `{id}` unique. */\n id: \"pointsofcontact_id_unique\",\n /** `{subject_type, subject_id, active}`: contacts for a subject. */\n subject: \"pointsofcontact_subject\",\n /** `{agency_id, purposes, active}`: the partner rollup by agency. */\n agencyPurpose: \"pointsofcontact_agency_purpose\",\n /** `{org_id, purposes, active}`: the partner rollup by org. */\n orgPurpose: \"pointsofcontact_org_purpose\",\n /** `{status}`: the steward's review queue. */\n status: \"pointsofcontact_status\",\n /**\n * `{agency_id, subject_type, subject_id, identity_key}` unique where `active` and\n * `confirmed`: no twin of one person among a subject's visible contacts.\n * Pending duplicates are the steward's call, so a stranger's pending add\n * never blocks the owner's own.\n */\n identity: \"pointsofcontact_identity_unique\",\n /**\n * `{agency_id, subject_type, subject_id}` unique where `is_primary`, `active` and\n * `confirmed`: at most one VISIBLE primary per subject, so a stranger's\n * pending add can never hold the slot.\n */\n primary: \"pointsofcontact_primary_unique\",\n /**\n * `{agency_id, subject_type, subject_id, identity_key, createdBy}` unique\n * where {@link POC_IN_APP_PENDING_INDEX_FILTER}: one outstanding in-app add\n * per adder, subject and IDENTITY ({@link pocIdentityKey}: name + preferred\n * email). See `POC_IN_APP_PENDING_INDEX`.\n */\n inAppPending: \"pointsofcontact_inapp_pending_unique\",\n /** `{status, createdAt, id}`: the steward's review queue, paged oldest first. */\n pendingQueue: \"pointsofcontact_pending_queue\",\n} as const;\n\n/** The partial filter of {@link POINT_OF_CONTACT_INDEXES.identity}. */\nexport const POC_IDENTITY_INDEX_FILTER = { active: true, status: \"confirmed\" } as const;\n\n/** The partial filter of {@link POINT_OF_CONTACT_INDEXES.primary}. */\nexport const POC_PRIMARY_INDEX_FILTER = { is_primary: true, active: true, status: \"confirmed\" } as const;\n\n/** The partial filter of {@link POINT_OF_CONTACT_INDEXES.inAppPending}: an outstanding in-app add. */\nexport const POC_IN_APP_PENDING_INDEX_FILTER = { status: \"pending\", origin: \"in_app\", active: true } as const;\n\n/**\n * The key of {@link POINT_OF_CONTACT_INDEXES.inAppPending}: the stored scalar\n * `identity_key`. Never an email list: two people may share a mailbox\n * (`intake@`), and an email-list key would merge them.\n */\nexport const POC_IN_APP_PENDING_INDEX_KEY = {\n agency_id: 1,\n subject_type: 1,\n subject_id: 1,\n identity_key: 1,\n createdBy: 1,\n} as const;\n\n/** A caller-chosen id (seed path only): the hti-features `^poc-[a-z0-9_-]+$` pattern. */\nexport const POC_ID_PATTERN = /^poc-[a-z0-9_-]+$/;\n\nconst HEX_24 = /^[0-9a-fA-F]{24}$/;\n\nconst idString = z.string().trim().min(1).max(200);\nconst text = (max: number) => z.string().trim().min(1).max(max);\n\n/** A seat or person id. A 24-hex id is lowercased so one seat has one spelling. */\nexport const PocLinkIdSchema = idString.transform((v) => (HEX_24.test(v) ? v.toLowerCase() : v));\n\n/** A lowercased, trimmed email address. */\nexport const PocEmailSchema = z.string().trim().toLowerCase().email(\"Not an email address.\").max(254);\n\nconst PurposesSchema = z\n .array(z.enum(CONTACT_PURPOSE_CODES))\n .max(CONTACT_PURPOSE_CODES.length)\n .transform((list) => [...new Set(list)]);\n\nconst UrgentMethodsSchema = z\n .array(\n z.string().refine(isPocUrgentMethodCode, {\n message:\n \"urgent_methods holds selectable CVC-185 preferred_contact_method codes from the Agency Hub subset (email · call · text).\",\n }),\n )\n .max(3)\n .transform((list) => [...new Set(list)]);\n\n// ─── Email / phone entries ───────────────────────────────────────────\n\n/** At most this many emails, and this many phones, on one contact. */\nexport const POC_MAX_CONTACT_ENTRIES = 10;\n\n/** One stored email or phone entry. The single source of {@link PocContactEntry}. */\nexport const StoredContactEntrySchema = z.object({\n /** An email (lowercased) or a phone as typed (trimmed). */\n value: z.string(),\n /** Exactly one entry of a non-empty list is the preferred one. */\n is_preferred: z.boolean(),\n});\n/** One email or phone on a contact (pl-e98). */\nexport type PocContactEntry = z.infer<typeof StoredContactEntrySchema>;\n\n/** An entry as READ: a missing or null flag is false (the first-entry rule then applies). */\nconst ReadContactEntrySchema = StoredContactEntrySchema.extend({\n is_preferred: z\n .boolean()\n .nullish()\n .transform((v) => v === true),\n});\n\n/**\n * The line a phone value names: digits only, a leading US country code\n * dropped. Canon's `phoneDigits` (prototype\n * `leads-app/server/objectStructuresEngine.generated.mjs` @ fa0fd0b0\n * L282-L286), verbatim in behaviour.\n */\nexport function pocPhoneDigits(v: string): string {\n const d = v.replace(/\\D/g, \"\");\n return d.length === 11 && d.charAt(0) === \"1\" ? d.slice(1) : d;\n}\n\n/**\n * DISPLAY only: how a reader may draw a stored phone. Canon's `formatPhone`\n * (same file, L246-L256; \"This is display only\", L244), verbatim in\n * behaviour: every non-digit is dropped, a redundant US `1` is dropped, and\n * the digits are drawn `(AAA) BBB-CCCC`, or `+cc (AAA) BBB-CCCC` past ten\n * digits. Empty when the value has no digit. Never written back: it is lossy\n * (an extension becomes digits of the number, a short number draws oddly), so\n * the store keeps the phone as typed.\n */\nexport function formatPocPhone(s: string): string {\n let d = s.replace(/\\D/g, \"\");\n if (!d) return \"\";\n if (d.length === 11 && d.charAt(0) === \"1\") d = d.slice(1);\n if (d.length <= 3) return `(${d}`;\n if (d.length <= 6) return `(${d.slice(0, 3)}) ${d.slice(3)}`;\n if (d.length <= 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;\n const cc = d.slice(0, d.length - 10);\n const r = d.slice(d.length - 10);\n return `+${cc} (${r.slice(0, 3)}) ${r.slice(3, 6)}-${r.slice(6)}`;\n}\n\nconst emailKey = (v: string) => v.trim().toLowerCase();\n\n/**\n * The preferred rule on an already-clean list: exactly one preferred when\n * non-empty, the first marked one, else the first entry.\n */\nfunction settlePreferred(list: readonly PocContactEntry[]): PocContactEntry[] {\n const at = list.findIndex((e) => e.is_preferred);\n const keep = at < 0 ? 0 : at;\n return list.map((e, i) => ({ value: e.value, is_preferred: i === keep }));\n}\n\n/** A stored list as READ: repaired, never refused (module comment). */\nfunction readEntries(\n list: readonly PocContactEntry[],\n clean: (v: string) => string,\n keyOf: (v: string) => string,\n): PocContactEntry[] {\n const seen = new Set<string>();\n const out: PocContactEntry[] = [];\n for (const e of list) {\n const value = clean(e.value);\n const k = value ? keyOf(value) : \"\";\n if (!k || seen.has(k)) continue;\n seen.add(k);\n out.push({ value, is_preferred: e.is_preferred });\n }\n return settlePreferred(out);\n}\n\n/** Stored `emails`, read: trimmed, lowercased, empty and repeated entries dropped, one preferred. */\nexport const StoredEmailListSchema = z\n .array(ReadContactEntrySchema)\n .transform((l) => readEntries(l, emailKey, (v) => v));\n\n/** Stored `phones`, read: trimmed, digitless and repeated lines dropped, one preferred. */\nexport const StoredPhoneListSchema = z\n .array(ReadContactEntrySchema)\n .transform((l) => readEntries(l, (v) => v.trim(), pocPhoneDigits));\n\n/**\n * A writer's list: at most one preferred, no repeated value; normalized so a\n * non-empty list has exactly one preferred (the marked one, else the first).\n */\nfunction entryListSchema(\n value: z.ZodType<string, z.ZodTypeDef, unknown>,\n keyOf: (v: string) => string,\n noun: \"email\" | \"phone\",\n) {\n return z\n .array(z.object({ value, is_preferred: z.boolean().optional() }).strict())\n .max(POC_MAX_CONTACT_ENTRIES)\n .superRefine((list, ctx) => {\n if (list.filter((e) => e.is_preferred === true).length > 1) {\n ctx.addIssue({ code: \"custom\", message: `A contact has at most one preferred ${noun}.` });\n }\n const seen = new Set<string>();\n list.forEach((e, i) => {\n const k = keyOf(e.value);\n if (seen.has(k)) {\n ctx.addIssue({\n code: \"custom\",\n path: [i, \"value\"],\n message: `The same ${noun} appears twice on one contact.`,\n });\n }\n seen.add(k);\n });\n })\n .transform((list): PocContactEntry[] =>\n settlePreferred(list.map((e) => ({ value: e.value, is_preferred: e.is_preferred === true }))),\n );\n}\n\n/** A writer's `emails`: lowercased addresses, at most one preferred, the first when none is marked. */\nexport const PocEmailListSchema = entryListSchema(PocEmailSchema, (v) => v, \"email\");\n\n/** A phone as a writer sends it: trimmed, at least one digit, stored as typed. */\nconst PocPhoneValueSchema = text(40).refine((v) => /\\d/.test(v), {\n message: \"A phone number has at least one digit.\",\n});\n\n/** A writer's `phones`: as typed, one per line (by digits), at most one preferred, the first when none is marked. */\nexport const PocPhoneListSchema = entryListSchema(PocPhoneValueSchema, pocPhoneDigits, \"phone\");\n\n/**\n * The preferred entry of a list: the one marked `is_preferred`, else the\n * first (the first-entry rule), else null for an empty or absent list.\n */\nexport function preferredContactEntry(\n list: readonly PocContactEntry[] | null | undefined,\n): PocContactEntry | null {\n if (!list || list.length === 0) return null;\n return list.find((e) => e.is_preferred) ?? list[0] ?? null;\n}\n\n/**\n * The contact's preferred email from its `emails`, or null. Takes a stored\n * row or any view. On a stored seat-linked row it is null (the email is the\n * seat's); a view's own `email` projection already resolves the seat.\n */\nexport function preferredEmail(c: { readonly emails: readonly PocContactEntry[] }): string | null {\n return preferredContactEntry(c.emails)?.value ?? null;\n}\n\n/** The contact's preferred phone, or null ({@link preferredEmail}'s rules). */\nexport function preferredPhone(c: { readonly phones: readonly PocContactEntry[] }): string | null {\n return preferredContactEntry(c.phones)?.value ?? null;\n}\n\n// ─── Owner ───────────────────────────────────────────────────────────\n\n/**\n * WHOSE contact this is, resolved by the platform route and normalized by the\n * platform writer.\n *\n * Id universe (decision D1, veto-able). Stored as plain strings, never\n * ObjectIds; readers match the string exactly:\n * - `agency_id`: `String(_id)` of the platform-db `agencies` row, the id a\n * share recipient carries in PAVE and Thread (platform\n * `lib/sharing-settings/recipient-id.ts`). The writer normalizes any\n * accepted form (`entity_id`, `id`, `_id`, a mapped registry row; a 24-hex\n * id in any case) through `resolveRecipientId` and refuses an owner that\n * does not resolve.\n * - `org_id`: `String(_id)` of the platform-db `organizations` row. An\n * agency and an org are linked only by a GENUINE 1:1 mirror:\n * `agencies.organizationId` names the org AND `organizations.agencyId`\n * names the agency (the auth mirror). `organizations.agencyId` alone is\n * many-to-one (the platform stamps the creating agency on every org it\n * creates) and never makes an org part of an agency. The writer stamps the\n * genuine mirror on an agency's rows, stamps the genuine mirror agency on\n * an org's rows, and otherwise leaves the other key null.\n * - `subject_id`: `agency` → `agency_id`; `org` → `org_id`; `program` →\n * `organizations.programs[].programId` on the agency's genuine-mirror org;\n * `team` → the team's `entity_id ?? id ?? String(_id)` (a `teams` row of\n * that agency); `location` → the site's id; `service` → the Service\n * Listing's `id` (a `servicelistings` row of `org_id`; `agency_id` null or\n * the org's genuine-mirror agency). The writer verifies membership;\n * `location` is refused until a location directory exists. Team and location\n * ids may be slugs two agencies share, so the subject is always read and\n * keyed together with `agency_id`.\n *\n * Every subject except an org-only partner resolves to an agency (canon stamps\n * `agency_id` on the row: platform-prototype `src/agencyhub.jsx` @ 0fa04c1\n * L411). An `org` subject carries `agency_id: null`, or its genuine mirror agency.\n */\nexport const PocOwnerSchema = z\n .object({\n subject_type: z.enum(POC_SUBJECT_TYPES),\n subject_id: idString,\n agency_id: idString.nullable(),\n org_id: idString.nullable(),\n })\n .strict()\n .superRefine((o, ctx) => {\n if (o.subject_type === \"agency\" && o.subject_id !== o.agency_id) {\n ctx.addIssue({ code: \"custom\", path: [\"subject_id\"], message: \"An agency's own contact names that agency: subject_id must equal agency_id.\" });\n }\n if (o.subject_type === \"org\" && o.subject_id !== o.org_id) {\n ctx.addIssue({ code: \"custom\", path: [\"subject_id\"], message: \"An org's own contact names that org: subject_id must equal org_id.\" });\n }\n if ((o.subject_type === \"program\" || o.subject_type === \"team\" || o.subject_type === \"location\") && !o.agency_id) {\n ctx.addIssue({ code: \"custom\", path: [\"agency_id\"], message: `A ${o.subject_type} contact names the agency it belongs to.` });\n }\n if (o.subject_type === \"service\" && !o.org_id) {\n ctx.addIssue({ code: \"custom\", path: [\"org_id\"], message: \"A service listing's contact names the listing's organization.\" });\n }\n });\nexport type PocOwner = z.infer<typeof PocOwnerSchema>;\n\n// ─── Writer bodies ───────────────────────────────────────────────────\n\nexport const PocDetailsSchema = z\n .object({\n user_id: PocLinkIdSchema.nullable().optional(),\n person_id: PocLinkIdSchema.nullable().optional(),\n display_name: text(200).nullable().optional(),\n emails: PocEmailListSchema.optional(),\n phones: PocPhoneListSchema.optional(),\n purposes: PurposesSchema.optional(),\n urgent_methods: UrgentMethodsSchema.optional(),\n is_primary: z.boolean().optional(),\n is_confidential: z.boolean().optional(),\n notes: text(2000).nullable().optional(),\n })\n .strict();\nexport type PocDetails = z.infer<typeof PocDetailsSchema>;\n/** What a body builder sends (defaulted and normalized fields optional). */\nexport type PocDetailsInput = z.input<typeof PocDetailsSchema>;\n\n/**\n * An advocate's in-app add of a partner's contact (pl-bt1; Crysta 2026-10-14\n * 23:25): a write-in with a name and at least one email (the preferred one is\n * the magic-link address), phones if known, tagged Referrals (magic link) unless\n * the body says otherwise. No seat or person link, no primary, no confidential flag, no\n * notes: those are the subject's own to set.\n */\nexport const PocInAppSchema = z\n .object({\n display_name: text(200),\n emails: PocEmailListSchema.refine((l) => l.length > 0, { message: \"An in-app add names at least one email.\" }),\n phones: PocPhoneListSchema.optional(),\n purposes: PurposesSchema.default([REFERRALS_MAGIC_LINK_PURPOSE]),\n urgent_methods: UrgentMethodsSchema.optional(),\n })\n .strict();\nexport type PocInApp = z.infer<typeof PocInAppSchema>;\n/** The `POST /api/partner-contacts` body a caller sends (`purposes` defaulted). */\nexport type PocInAppInput = z.input<typeof PocInAppSchema>;\n\n/** A seed row: the details plus the sheet's own `poc-*` id. */\nexport const PocSeedSchema = PocDetailsSchema.extend({\n id: z.string().trim().regex(POC_ID_PATTERN, \"A seeded contact id is poc-<lowercase letters, digits, '_' or '-'>.\"),\n}).strict();\nexport type PocSeed = z.infer<typeof PocSeedSchema>;\nexport type PocSeedInput = z.input<typeof PocSeedSchema>;\n\n/** An edit: at least one field; identity (`user_id`, `person_id`) is fixed at mint; a list replaces the stored list. */\nexport const PocPatchSchema = PocDetailsSchema.omit({ user_id: true, person_id: true })\n .strict()\n .refine((b) => Object.values(b).some((v) => v !== undefined), {\n message: \"A contact edit must name at least one field.\",\n });\nexport type PocPatch = z.infer<typeof PocPatchSchema>;\nexport type PocPatchInput = z.input<typeof PocPatchSchema>;\n\n/**\n * A parsed patch without its `undefined` values. A key present as\n * `undefined` means \"not edited\": written through, the driver would store\n * `null` (clearing `is_confidential` would publish a confidential contact).\n */\nexport function definedPatch<T extends Record<string, unknown>>(p: T): Partial<T> {\n return Object.fromEntries(Object.entries(p).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\n// ─── Stored document ─────────────────────────────────────────────────\n\nconst nullableString = z.string().nullable();\n\n/** The stored document (Mongo's `_id` stripped). Readers parse every row with it. */\nexport const PointOfContactDocSchema = z.object({\n id: z.string().min(1),\n subject_type: z.enum(POC_SUBJECT_TYPES),\n subject_id: z.string().min(1),\n agency_id: nullableString,\n org_id: nullableString,\n user_id: nullableString,\n person_id: nullableString,\n display_name: nullableString,\n /** Lowercased emails, read leniently. Empty on a seat-linked contact (it resolves from the seat). */\n emails: StoredEmailListSchema,\n /** Read leniently. Empty on a seat-linked contact. */\n phones: StoredPhoneListSchema,\n purposes: z.array(z.enum(CONTACT_PURPOSE_CODES)),\n /** CVC-185 codes. */\n urgent_methods: z.array(z.string()),\n is_primary: z.boolean(),\n is_confidential: z.boolean(),\n /** A removed contact is deactivated, never deleted. */\n active: z.boolean(),\n notes: nullableString,\n status: z.enum(POC_STATUSES),\n origin: z.enum(POC_ORIGINS),\n added_in_app: z.enum(POC_ADDED_IN_APPS).nullable(),\n /** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<preferred email>`, lowercased. */\n identity_key: z.string().min(1),\n confirmed_by: nullableString,\n confirmed_at: nullableString,\n deactivated_by: nullableString,\n deactivated_at: nullableString,\n /** Bumped by every write; edits and the steward's confirm name the version they saw. */\n version: z.number().int().nonnegative(),\n createdBy: nullableString,\n createdAt: z.string().min(1),\n updatedBy: nullableString,\n updatedAt: z.string().min(1),\n});\nexport type PointOfContactDoc = z.infer<typeof PointOfContactDocSchema>;\n\n/** The fields the whole-contact rules read. */\nexport type PocRuleInput = Pick<PointOfContactDoc, \"user_id\" | \"person_id\" | \"display_name\" | \"emails\" | \"phones\" | \"purposes\">;\n\nexport interface PocRuleViolation {\n reason: \"user_id_xor_person_id\" | \"seat_contact_has_own_reach\" | \"display_name_required\" | \"referral_contact_needs_email\";\n message: string;\n}\n\n/**\n * The whole-contact rules (module comment). A seat-linked Referrals contact is\n * NOT a violation here: the seat's email is checked by the writer, which can\n * read the seat. Returns every violation, empty when the contact is valid.\n */\nexport function pocRuleViolations(c: PocRuleInput): PocRuleViolation[] {\n const out: PocRuleViolation[] = [];\n const seat = !!c.user_id;\n if (c.user_id && c.person_id) {\n out.push({ reason: \"user_id_xor_person_id\", message: \"A contact points at a seat (user_id) or a person (person_id), never both.\" });\n }\n if (seat && (c.emails.length > 0 || c.phones.length > 0)) {\n out.push({\n reason: \"seat_contact_has_own_reach\",\n message: \"A seat-linked contact stores no email or phone of its own; they resolve from the seat.\",\n });\n }\n if (!seat && !c.display_name) {\n out.push({ reason: \"display_name_required\", message: \"A contact that holds no seat needs a display_name.\" });\n }\n if (!seat && c.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE) && c.emails.length === 0) {\n out.push({\n reason: \"referral_contact_needs_email\",\n message: \"A contact tagged Referrals (magic link) must have an email.\",\n });\n }\n return out;\n}\n\n/**\n * The identity a subject's contacts are deduplicated by (canon `hubSavePocs`,\n * platform-prototype `src/agencyhub.jsx` @ 0fa04c1 L382-L384). A write-in keys\n * on its name and its PREFERRED email, so changing the preferred email changes\n * the key: the writer recomputes it on every edit.\n */\nexport function pocIdentityKey(c: Pick<PointOfContactDoc, \"user_id\" | \"person_id\" | \"display_name\" | \"emails\">): string {\n const norm = (v: string | null) => (v ?? \"\").trim().toLowerCase();\n if (c.user_id) return `seat:${norm(c.user_id)}`;\n if (c.person_id) return `person:${norm(c.person_id)}`;\n return `writein:${norm(c.display_name)}|${norm(preferredEmail(c))}`;\n}\n","/**\n * Point of contact read rules (pl-3r8). Pure, no I/O. Every reader (Thread,\n * PAVE, LEADS, the platform) applies these through this module; none\n * re-implements them.\n *\n * ## Three views\n *\n * - **Network view** ({@link toNetworkView}): what any app may show or use\n * about another organization's contact. A row is network-visible only when\n * it is `active`, `confirmed` and NOT `is_confidential`:\n * - pending rows (in-app adds, seeded rows) wait for HTI Labs (Crysta\n * 2026-10-14: an in-app add is \"available platform-wide after HTI Labs\n * confirms it\");\n * - a confidential contact is \"never published\" (prototype\n * `Org + Personnel Registry/DIRECTORY_CSV_EDITING_GUIDE.md` @ 6c2db859\n * § 0.9 L958; hti-features `PointOfContact.v1.json` `is_confidential`:\n * \"Never publish this contact\"), so it is left out entirely rather\n * than masked. The network view is unchanged by pl-iza (0.32.0):\n * confidential rows are absent from every view another organization\n * sees (this view, `getContact`, `listContactsForSubject`, the\n * referral `recipients`; only the subject's owner and the steward see\n * them). A confidential Referrals (magic link) holder still receives\n * the magic link, but only through the send-only\n * `resolveMagicLinkRecipients` (`./reader.ts`), which never projects\n * the row and exposes a count;\n * - the seat / person links, `notes`, review stamps, actor ids and the\n * identity key are not projected.\n * - **Owner view** ({@link toOwnerView}): the subject's own editor (Admin\n * Hub → My Agency Info → Contacts). Unmasked, every status, with the seat's\n * reach resolved, so an editor round-trip never wipes a confidential or\n * pending contact. Actor ids and the app a partner added it in are not\n * projected: the owner sees `origin`, not who at another agency wrote it.\n * - **Steward view** ({@link toStewardView}): HTI Labs' review. Everything\n * except the identity key, with the seat's reach resolved.\n *\n * Every view carries `purpose_labels` (hti-features `purpose_labels`, readOnly).\n *\n * ## Emails and phones (pl-e98)\n *\n * The owner and steward views carry the row's own `emails` / `phones` (what\n * the editor edits; empty on a seat-linked row) beside the resolved `seat`.\n * The network view carries the REACHABLE lists: the row's, or for a\n * seat-linked row the seat's single email and phone as one preferred entry\n * each. EVERY view also carries read-only `email` / `phone`: the reachable\n * preferred address (the row's preferred entry, or the seat's for a\n * seat-linked contact), the projections canon's card keeps of its preferred\n * entries (platform-prototype `src/agencyhub.jsx` @ 6f428116 L8195-L8202). A\n * reader that sends to or shows one address reads that projection. Views own\n * their lists: they are copies, never the row's arrays.\n */\n\nimport {\n PointOfContactDocSchema,\n preferredContactEntry,\n type PocContactEntry,\n type PointOfContactDoc,\n} from \"./schemas.js\";\nimport { contactPurposeLabel, type ContactPurposeCode, type PocSubjectType } from \"./vocabulary.js\";\n\n/** A seat's reach, resolved by the reader from platform-db `users`. */\nexport interface SeatReach {\n email: string | null;\n phone: string | null;\n name: string | null;\n}\n\n/** The steward view: everything but the identity key, seat resolved. */\nexport interface PointOfContactStewardView extends Omit<PointOfContactDoc, \"identity_key\"> {\n purpose_labels: string[];\n /** The seat's reach for a seat-linked contact (null when unlinked or not found). */\n seat: SeatReach | null;\n /** Read-only: the reachable preferred email (the seat's for a seat-linked contact), or null. */\n email: string | null;\n /** Read-only: the reachable preferred phone, or null. */\n phone: string | null;\n}\n\n/** The owner view: unmasked, without other organizations' actor ids. */\nexport type PointOfContactOwnerView = Omit<\n PointOfContactStewardView,\n \"createdBy\" | \"updatedBy\" | \"confirmed_by\" | \"deactivated_by\" | \"added_in_app\"\n>;\n\n/** The network view: what other organizations see. */\nexport interface PointOfContactNetworkView {\n id: string;\n subject_type: PocSubjectType;\n subject_id: string;\n agency_id: string | null;\n org_id: string | null;\n display_name: string | null;\n /** The row's emails, or the seat's email as one preferred entry when the contact is seat-linked and a seat resolver was given. */\n emails: PocContactEntry[];\n /** The row's phones, or the seat's phone as one preferred entry (the same rules as `emails`). */\n phones: PocContactEntry[];\n /** The preferred of `emails` (`preferredEmail(view)`), or null. The magic-link address. */\n email: string | null;\n /** The preferred of `phones` (`preferredPhone(view)`), or null. */\n phone: string | null;\n purposes: ContactPurposeCode[];\n purpose_labels: string[];\n urgent_methods: string[];\n is_primary: boolean;\n updatedAt: string;\n}\n\n/** A stored row that does not match the contract. Readers propagate it. */\nexport class PointOfContactShapeError extends Error {\n constructor(\n readonly contactId: string | null,\n readonly issues: string[],\n ) {\n super(`points-of-contact: stored row ${contactId ?? \"(no id)\"} does not match the contract: ${issues.join(\"; \")}`);\n this.name = \"PointOfContactShapeError\";\n }\n}\n\n/**\n * A stored row → the typed document. Strict: every writer (the platform's,\n * and the shared in-app add every app runs, `./writer.ts`) writes every\n * field, so a row that does not parse (an unknown origin or status, a missing\n * id) is a defect and FAILS LOUDLY rather than being read as some default.\n */\nexport function normalizePointOfContact(raw: Record<string, unknown>): PointOfContactDoc {\n const parsed = PointOfContactDocSchema.safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new PointOfContactShapeError(\n typeof raw.id === \"string\" && raw.id ? raw.id : null,\n parsed.error.issues.map((i) => `${i.path.join(\".\") || \"(row)\"}: ${i.message}`),\n );\n}\n\n/** True when other organizations may see or use this contact. */\nexport function isNetworkVisible(d: Pick<PointOfContactDoc, \"active\" | \"status\" | \"is_confidential\">): boolean {\n return d.active && d.status === \"confirmed\" && !d.is_confidential;\n}\n\nconst copyEntries = (list: readonly PocContactEntry[]): PocContactEntry[] =>\n list.map((e) => ({ ...e }));\n\n/**\n * Where the contact is reached: the row's own lists, or for a seat-linked row\n * the seat's email (trimmed, lowercased) and phone as one preferred entry\n * each. Always fresh arrays.\n */\nfunction reachOf(\n d: PointOfContactDoc,\n seat: SeatReach | null | undefined,\n): { emails: PocContactEntry[]; phones: PocContactEntry[] } {\n if (!d.user_id) return { emails: copyEntries(d.emails), phones: copyEntries(d.phones) };\n const one = (v: string | null | undefined): PocContactEntry[] =>\n v ? [{ value: v, is_preferred: true }] : [];\n return {\n emails: one(seat?.email?.trim().toLowerCase()),\n phones: one(seat?.phone?.trim()),\n };\n}\n\nconst preferredValue = (list: readonly PocContactEntry[]): string | null =>\n preferredContactEntry(list)?.value ?? null;\n\n/** The steward view. */\nexport function toStewardView(\n d: PointOfContactDoc,\n seat?: SeatReach | null,\n): PointOfContactStewardView {\n const { identity_key: _internal, ...rest } = d;\n const reach = reachOf(d, seat);\n return {\n ...rest,\n emails: copyEntries(d.emails),\n phones: copyEntries(d.phones),\n purposes: [...d.purposes],\n urgent_methods: [...d.urgent_methods],\n purpose_labels: d.purposes.map(contactPurposeLabel),\n seat: d.user_id ? (seat ?? null) : null,\n email: preferredValue(reach.emails),\n phone: preferredValue(reach.phones),\n };\n}\n\n/** The owner view. */\nexport function toOwnerView(\n d: PointOfContactDoc,\n seat?: SeatReach | null,\n): PointOfContactOwnerView {\n const {\n createdBy: _c,\n updatedBy: _u,\n confirmed_by: _cb,\n deactivated_by: _db,\n added_in_app: _app,\n ...rest\n } = toStewardView(d, seat);\n return rest;\n}\n\n/**\n * The network view of one row, or null when the row is not network-visible.\n * A seat-linked row reads its email, phone and (when the row has none) name\n * from `seat`.\n */\nexport function toNetworkView(\n d: PointOfContactDoc,\n seat?: SeatReach | null,\n): PointOfContactNetworkView | null {\n if (!isNetworkVisible(d)) return null;\n const seatLinked = !!d.user_id;\n const { emails, phones } = reachOf(d, seat);\n return {\n id: d.id,\n subject_type: d.subject_type,\n subject_id: d.subject_id,\n agency_id: d.agency_id,\n org_id: d.org_id,\n display_name: d.display_name ?? (seatLinked ? (seat?.name ?? null) : null),\n emails,\n phones,\n email: preferredValue(emails),\n phone: preferredValue(phones),\n purposes: [...d.purposes],\n purpose_labels: d.purposes.map(contactPurposeLabel),\n urgent_methods: [...d.urgent_methods],\n is_primary: d.is_primary,\n updatedAt: d.updatedAt,\n };\n}\n\nconst SUBJECT_ORDER: Record<PocSubjectType, number> = {\n agency: 0,\n org: 1,\n program: 2,\n team: 3,\n location: 4,\n service: 5,\n};\n\n/** Reading order: the agency / org before its programs, teams and locations, primary first, then name, then id. */\nexport function byContactReadingOrder(\n a: Pick<PointOfContactDoc, \"subject_type\" | \"subject_id\" | \"is_primary\" | \"display_name\" | \"id\">,\n b: Pick<PointOfContactDoc, \"subject_type\" | \"subject_id\" | \"is_primary\" | \"display_name\" | \"id\">,\n): number {\n return (\n SUBJECT_ORDER[a.subject_type] - SUBJECT_ORDER[b.subject_type] ||\n a.subject_id.localeCompare(b.subject_id) ||\n Number(b.is_primary) - Number(a.is_primary) ||\n (a.display_name ?? \"\").localeCompare(b.display_name ?? \"\") ||\n a.id.localeCompare(b.id)\n );\n}\n","/**\n * Point of contact reads over a raw MongoDB driver handle (pl-3r8). No\n * mongoose, no driver import: the handle is typed structurally, so a\n * `mongodb` `Db` (the platform, PAVE's `platformDb`) or a mongoose\n * connection's `.db` both fit.\n *\n * Every read returns rows through `./readRules.ts`. A read ERROR propagates,\n * and so does a stored row that does not match the contract\n * (`PointOfContactShapeError`): a subject with no contacts honestly reads\n * `[]`, an unreadable or corrupt store never does.\n *\n * ## Seat-linked contacts\n *\n * A seat-linked row stores no email or phone; they live on the seat\n * (platform-db `users`). This package carries no driver, so it cannot build an\n * ObjectId filter for `users._id`; the reader passes a {@link SeatResolver}\n * that reads its own `users`. The partner rollup REQUIRES one, so a reader\n * cannot silently drop seat-linked referral contacts.\n *\n * ## Confidential Referrals (magic link) holders (pl-iza, 0.32.0)\n *\n * A confidential holder still receives the magic link; the sender never sees\n * the address (CVC-338, prototype `data/cvcs/core_contact_purpose.yaml` @\n * 184893b6 L95; HANDOFF.md @ 184893b6 L569, L575 \"POC-PROFILE-ALIGNMENTS\"\n * D(ii)). Confidential rows are absent from every view another organization\n * sees (only the owner and steward reads carry them). The referral rollup\n * reads them in a SEPARATE query and hands out only a count\n * (`confidentialCount`) or, to a send, a {@link ConfidentialReferralRecipients}\n * whose `deliver` alone touches the addresses (the implementation is not\n * exported). A confidential row never reaches `unreachable`, and a corrupt\n * row that may be confidential is counted, never thrown.\n */\n\nimport { POINTS_OF_CONTACT_COLLECTION, type PointOfContactDoc } from \"./schemas.js\";\nimport {\n byContactReadingOrder,\n normalizePointOfContact,\n toNetworkView,\n toOwnerView,\n toStewardView,\n type PointOfContactNetworkView,\n type PointOfContactOwnerView,\n type PointOfContactStewardView,\n type SeatReach,\n} from \"./readRules.js\";\nimport { REFERRALS_MAGIC_LINK_PURPOSE, type PocSubjectType } from \"./vocabulary.js\";\n\n/** The slice of a driver `Collection` the reads use. */\nexport interface PocCollectionLike {\n find(filter: Record<string, unknown>): { toArray(): Promise<unknown[]> };\n findOne(filter: Record<string, unknown>): Promise<unknown>;\n}\n\n/** The slice of a driver `Db` the reads use. */\nexport interface PocDbLike {\n collection(name: string): PocCollectionLike;\n}\n\n/** Resolves seat ids (platform-db `users._id`, string form) to their reach. Missing ids are simply absent. */\nexport type SeatResolver = (userIds: readonly string[]) => Promise<ReadonlyMap<string, SeatReach>>;\n\n/**\n * A subject, always read together with its agency where ids can collide.\n * Program, team and location ids can be slugs two agencies share, so their reads\n * REQUIRE `agency_id`. A service listing's contact names `agency_id` too:\n * the listing org's genuine-mirror agency, or `null` for an org-only partner.\n * Only agency and org subjects (whose ids are themselves unique) may omit it.\n */\nexport type PocSubjectRef =\n | { subject_type: \"agency\" | \"org\"; subject_id: string; agency_id?: string | null }\n | { subject_type: \"program\" | \"team\" | \"location\"; subject_id: string; agency_id: string }\n | { subject_type: \"service\"; subject_id: string; agency_id: string | null };\n\nfunction subjectFilter(subject: PocSubjectRef): Record<string, unknown> {\n const type = requireId(\"subject_type\", subject.subject_type) as PocSubjectType;\n const base = { subject_type: type, subject_id: requireId(\"subject_id\", subject.subject_id) };\n const agency = subject.agency_id;\n if (type === \"program\" || type === \"team\" || type === \"location\") {\n return { ...base, agency_id: requireId(\"agency_id\", agency) };\n }\n if (type === \"service\" && agency === undefined) {\n throw new TypeError(\n \"points-of-contact: a service subject read names agency_id (a string, or null for an org-only partner)\",\n );\n }\n if (agency === undefined) return base;\n return { ...base, agency_id: agency === null ? null : requireId(\"agency_id\", agency) };\n}\n\n/**\n * A partner, by its agency, its organization, or both. Both together read the\n * contacts on either (an agency's rows carry its mirror org, an org-only\n * partner's rows carry no agency).\n */\nexport interface PocPartnerSelector {\n agency_id?: string | null;\n org_id?: string | null;\n}\n\nfunction requireId(name: string, v: unknown): string {\n if (typeof v !== \"string\" || v.length === 0) {\n throw new TypeError(`points-of-contact: ${name} must be a non-empty string`);\n }\n return v;\n}\n\n/** The network-visible filter (`isNetworkVisible`, pushed into the query). */\nconst NETWORK_VISIBLE = { active: true, status: \"confirmed\", is_confidential: { $ne: true } } as const;\n\nconst rowOf = (r: unknown): Record<string, unknown> =>\n r !== null && typeof r === \"object\" ? (r as Record<string, unknown>) : {};\n\nasync function findDocs(\n db: PocDbLike,\n filter: Record<string, unknown>,\n): Promise<PointOfContactDoc[]> {\n const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).find(filter).toArray();\n return raw.map((r) => normalizePointOfContact(rowOf(r))).sort(byContactReadingOrder);\n}\n\nasync function seatsFor(\n docs: readonly PointOfContactDoc[],\n resolve?: SeatResolver,\n): Promise<ReadonlyMap<string, SeatReach>> {\n const ids = [...new Set(docs.map((d) => d.user_id).filter((u): u is string => !!u))];\n if (!resolve || ids.length === 0) return new Map();\n return resolve(ids);\n}\n\nconst seatOf = (d: PointOfContactDoc, seats: ReadonlyMap<string, SeatReach>) =>\n d.user_id ? (seats.get(d.user_id) ?? null) : null;\n\nfunction networkViews(\n docs: readonly PointOfContactDoc[],\n seats: ReadonlyMap<string, SeatReach>,\n): PointOfContactNetworkView[] {\n return docs\n .map((d) => toNetworkView(d, seatOf(d, seats)))\n .filter((v): v is PointOfContactNetworkView => v !== null)\n .sort(byContactReadingOrder); // again, now that seat-linked rows carry the seat's name\n}\n\n/**\n * A subject's contacts as other organizations see them: active, confirmed,\n * not confidential. Without a seat resolver, a seat-linked contact reads\n * `email: null`.\n */\nexport async function listContactsForSubject(\n db: PocDbLike,\n subject: PocSubjectRef,\n opts: { resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactNetworkView[]> {\n const docs = await findDocs(db, { ...subjectFilter(subject), ...NETWORK_VISIBLE });\n return networkViews(docs, await seatsFor(docs, opts.resolveSeats));\n}\n\n/**\n * A referral recipient: a network-visible contact with a resolved email, or\n * (only when asked, {@link ReferralContactsOptions.includeOwnPendingFor}) the\n * asking advocate's OWN pending in-app add, marked `pending: true` so a UI can\n * label it.\n */\nexport type ReferralRecipient = PointOfContactNetworkView & { email: string; pending?: true };\n\nexport interface ReferralContactsOptions {\n resolveSeats: SeatResolver;\n /**\n * The asking advocate's Auth0 `sub`, taken server-side from the verified\n * token (the same pinning as `mintPartnerContact`'s `actor.id`). When set,\n * the advocate's OWN pending in-app adds on the partner (`status: pending`,\n * active, `origin: in_app`, `createdBy` = this sub, tagged Referrals (magic\n * link), not confidential) are returned too, after the confirmed recipients\n * and marked `pending: true`. Nobody else's pending add is ever returned.\n */\n includeOwnPendingFor?: string;\n}\n\nexport interface ReferralContactsResult {\n /** One per distinct email, in reading order (the agency's own contacts first). */\n recipients: ReferralRecipient[];\n /**\n * Ids of tagged, VISIBLE contacts with no email to send to (a seat whose\n * `users` row has none). Never a confidential holder's id.\n */\n unreachable: string[];\n /**\n * The number of distinct confidential Referrals (magic link) holder\n * addresses (pl-iza): active, confirmed, `is_confidential`, tagged, on the\n * same rollup. Deduped among the confidential holders ONLY, never against\n * any visible, pending, typed or added address, so no other row or input\n * moves it. A sender sees this number, never a name, an id or an address\n * (\"+ 1 confidential recipient\").\n */\n confidentialCount: number;\n}\n\n/** The partner rollup keys: its agency, its organization, or both. */\nfunction partnerKeys(partner: PocPartnerSelector): Record<string, string>[] {\n const keys: Record<string, string>[] = [];\n if (partner.agency_id !== undefined && partner.agency_id !== null) {\n keys.push({ agency_id: requireId(\"agency_id\", partner.agency_id) });\n }\n if (partner.org_id !== undefined && partner.org_id !== null) {\n keys.push({ org_id: requireId(\"org_id\", partner.org_id) });\n }\n if (keys.length === 0) throw new TypeError(\"points-of-contact: select a partner by agency_id, org_id or both\");\n return keys;\n}\n\n/** The two public referral reads' shared result: confidential addresses stay inside this module. */\ninterface ReferralHolders {\n recipients: ReferralRecipient[];\n unreachable: string[];\n confidentialAddresses: string[];\n confidentialUnreachableCount: number;\n}\n\n/** A raw row that may be confidential: its stored flag is anything but `false` or absent. */\nconst mayBeConfidential = (raw: Record<string, unknown>) =>\n raw.is_confidential !== false && raw.is_confidential !== undefined;\n\n/**\n * A referral leg's rows. A row that does not match the contract and MAY be\n * confidential is skipped and counted, not thrown: a\n * `PointOfContactShapeError` names the row's id, and an app's error handler\n * can return an error message to the browser. Nothing is logged. In the\n * confidential leg every such row may be; in the visible and pending legs it\n * is one whose stored `is_confidential` is malformed (`\"true\"`, `1`, `null`:\n * it matches `{ $ne: true }`). Any other corrupt row still throws, as\n * {@link findDocs} does.\n */\nasync function findHolderDocs(\n db: PocDbLike,\n filter: Record<string, unknown>,\n confidentialLeg: boolean,\n): Promise<{ docs: PointOfContactDoc[]; skipped: number }> {\n const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).find(filter).toArray();\n const docs: PointOfContactDoc[] = [];\n let skipped = 0;\n for (const r of raw) {\n const row = rowOf(r);\n try {\n docs.push(normalizePointOfContact(row));\n } catch (err) {\n if (!confidentialLeg && !mayBeConfidential(row)) throw err;\n skipped++;\n }\n }\n return { docs: docs.sort(byContactReadingOrder), skipped };\n}\n\n/**\n * The partner's Referrals (magic link) holders, read once for both public\n * reads. Three queries on the same rollup keys, in this order: the visible\n * confirmed holders, the asking advocate's own pending adds (only when asked),\n * and (pl-iza) the confidential confirmed holders. The first two are the\n * pre-0.32.0 queries, unchanged. Seats are resolved ONCE, over the visible and\n * confidential rows together (pending in-app adds are never seat-linked).\n */\nasync function readReferralHolders(\n db: PocDbLike,\n partner: PocPartnerSelector,\n opts: ReferralContactsOptions,\n): Promise<ReferralHolders> {\n const keys = partnerKeys(partner);\n const pendingFor =\n opts.includeOwnPendingFor === undefined\n ? null\n : requireId(\"includeOwnPendingFor\", opts.includeOwnPendingFor);\n const visible = await findHolderDocs(\n db,\n { $or: keys, purposes: REFERRALS_MAGIC_LINK_PURPOSE, ...NETWORK_VISIBLE },\n false,\n );\n const pending =\n pendingFor === null\n ? { docs: [], skipped: 0 }\n : await findHolderDocs(\n db,\n {\n $or: keys,\n purposes: REFERRALS_MAGIC_LINK_PURPOSE,\n ...OWN_PENDING_IN_APP,\n createdBy: pendingFor,\n },\n false,\n );\n const confidential = await findHolderDocs(\n db,\n { $or: keys, purposes: REFERRALS_MAGIC_LINK_PURPOSE, ...CONFIDENTIAL_CONFIRMED },\n true,\n );\n const docs = visible.docs;\n const seats = await seatsFor([...docs, ...confidential.docs], opts.resolveSeats);\n\n const recipients: ReferralRecipient[] = [];\n const unreachable: string[] = [];\n const seen = new Set<string>();\n for (const v of networkViews(docs, seats)) {\n if (!v.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE)) continue;\n const email = v.email;\n if (!email) {\n unreachable.push(v.id);\n continue;\n }\n if (seen.has(email)) continue;\n seen.add(email);\n recipients.push({ ...v, email });\n }\n if (pendingFor !== null) {\n for (const d of pending.docs) {\n // The same filter again, on the parsed row: a reader never widens it.\n if (!isOwnPendingInApp(d, pendingFor)) continue;\n // An in-app add is a write-in (never seat-linked): its view is its own row's,\n // drawn as the network view would draw it once confirmed.\n const v = toNetworkView({ ...d, status: \"confirmed\" });\n const email = v?.email;\n if (!v || !email || seen.has(email)) continue;\n seen.add(email);\n recipients.push({ ...v, email, pending: true });\n }\n }\n\n // pl-iza: confidential holders still receive the link; the sender never sees\n // the address. Deduped among THEMSELVES only, never against a visible,\n // pending, typed or added address: any of those can change under the\n // advocate's eye (their add confirmed by a steward, a seat's email edited,\n // their own typing), and a count that dropped when one matched would tell\n // them a confidential holder's address. An overlap is simply sent twice.\n const confidentialAddresses: string[] = [];\n const confidentialSeen = new Set<string>();\n let confidentialUnreachableCount = visible.skipped + pending.skipped + confidential.skipped;\n for (const d of confidential.docs) {\n // The same filter again, on the parsed row.\n if (!isConfidentialHolder(d)) continue;\n // The steward view's `email` is the reachable preferred address (the\n // seat's for a seat-linked row), drawn as the network view draws it.\n const email = toStewardView(d, seatOf(d, seats)).email;\n if (!email) {\n confidentialUnreachableCount++;\n continue;\n }\n if (confidentialSeen.has(email)) continue;\n confidentialSeen.add(email);\n confidentialAddresses.push(email);\n }\n return { recipients, unreachable, confidentialAddresses, confidentialUnreachableCount };\n}\n\n/**\n * The partner's Referrals (magic link) contacts: every active, confirmed,\n * non-confidential contact tagged `REFERRALS_MAGIC_LINK` on the partner's\n * agency AND on its programs, teams and locations (the rollup, via the row's\n * `agency_id`), and on its organization (via `org_id`). A magic link goes to\n * every one of them (Crysta 2026-08-23, restated 2026-10-14), at its PREFERRED\n * email (pl-e98; the view's `email`). The same email tagged on two subjects is\n * one recipient.\n *\n * With `includeOwnPendingFor` (Nate 2026-10-15), the advocate also sees their\n * own pending in-app adds on the partner, so a contact they just added can be\n * picked before HTI Labs confirms it (pending, marked, after the confirmed\n * recipients; an email a confirmed recipient already has is not repeated).\n * Confidential rows stay out of `recipients` and `unreachable`; they are\n * counted (`confidentialCount`, pl-iza) and reached only through\n * {@link resolveMagicLinkRecipients}. The partner has a\n * magic-link holder when `recipients.length + confidentialCount > 0`.\n */\nexport async function listReferralContactsForPartner(\n db: PocDbLike,\n partner: PocPartnerSelector,\n opts: ReferralContactsOptions,\n): Promise<ReferralContactsResult> {\n const holders = await readReferralHolders(db, partner, opts);\n return {\n recipients: holders.recipients,\n unreachable: holders.unreachable,\n confidentialCount: holders.confidentialAddresses.length,\n };\n}\n\n/** What a send needs: the visible recipients, plus the confidential holders behind a count. */\nexport interface MagicLinkSendList {\n /** As {@link ReferralContactsResult.recipients}. */\n recipients: ReferralRecipient[];\n /** As {@link ReferralContactsResult.unreachable}: visible contacts only. */\n unreachable: string[];\n /** The confidential holders: a count, and a `deliver` that alone touches their addresses. */\n confidential: ConfidentialReferralRecipients;\n /**\n * SERVER-SIDE diagnostic, never returned to a sender: the confidential\n * holder rows that cannot be sent to (no email, a seat with none or not\n * found), plus skipped rows that do not match the contract and may be\n * confidential (their error would name their id). A count, never an id.\n */\n confidentialUnreachableCount: number;\n}\n\n/**\n * SEND-ONLY (pl-iza). The same read as {@link listReferralContactsForPartner},\n * with the confidential holders as a {@link ConfidentialReferralRecipients}\n * instead of a bare count. Call it at send time, server-side, and hand\n * `confidential.deliver` the mailer; never return the result to a browser\n * beyond `confidential.count` (its `toJSON` is `{ count }`). This is the only\n * way to obtain a `ConfidentialReferralRecipients` (the implementation is\n * not exported).\n *\n * Canon: CVC-338 `REFERRALS_MAGIC_LINK` (prototype\n * `data/cvcs/core_contact_purpose.yaml` @ 184893b6 L95): \"A confidential\n * holder still receives it; the sender never sees the address.\"\n */\nexport async function resolveMagicLinkRecipients(\n db: PocDbLike,\n partner: PocPartnerSelector,\n opts: ReferralContactsOptions,\n): Promise<MagicLinkSendList> {\n const holders = await readReferralHolders(db, partner, opts);\n return {\n recipients: holders.recipients,\n unreachable: holders.unreachable,\n confidential: new ConfidentialHolders(holders.confidentialAddresses),\n confidentialUnreachableCount: holders.confidentialUnreachableCount,\n };\n}\n\n/**\n * Sends one magic link to one address. It must THROW (or reject) on failure;\n * returning normally counts as delivered. It must not log, persist or return\n * `address`.\n */\nexport type ConfidentialSendOne = (address: string) => void | Promise<void>;\n\nexport interface ConfidentialDeliverOptions {\n /** At most this many sends (a non-negative integer); the rest are `overflow`. Unlimited when omitted. */\n capacity?: number;\n}\n\n/**\n * A confidential delivery's outcome: numbers and an error class name, never an\n * address. SERVER-SIDE, for audit only: a sender may see `count`, or one\n * all-or-nothing status derived from it, never `delivered`, `failed`,\n * `overflow` or `firstErrorName`.\n */\nexport interface ConfidentialDeliveryResult {\n /** The holder count (`delivered + failed + overflow`). */\n count: number;\n delivered: number;\n failed: number;\n /** Holders beyond `capacity`, not sent: `max(0, count - capacity)`. */\n overflow: number;\n /** The first failed send's `err.name` (never its message, which can echo the address), or null. */\n firstErrorName: string | null;\n}\n\nconst SAFE_ERROR_NAME = /^[A-Za-z_$][\\w$.-]{0,63}$/;\n\n/**\n * An error's class name only. Anything that is not a plain identifier, or a\n * `name` that cannot be read (a throwing getter, a revoked proxy), reads \"Error\".\n */\nfunction errorName(err: unknown): string {\n try {\n if (err === null || (typeof err !== \"object\" && typeof err !== \"function\")) return \"Error\";\n const name: unknown = (err as { name?: unknown }).name;\n return typeof name === \"string\" && SAFE_ERROR_NAME.test(name) ? name : \"Error\";\n } catch {\n return \"Error\";\n }\n}\n\n/**\n * A partner's confidential Referrals (magic link) holders (pl-iza). It carries\n * their addresses privately and exposes only `count`: `toJSON()` is\n * `{ count }`, `util.inspect` draws `ConfidentialReferralRecipients(n)`, and\n * no public member returns an address. Only {@link deliver} touches them,\n * handing each to the caller's `sendOne`.\n *\n * An interface, exported as a type only. The implementation is not\n * exported: obtain values only via {@link resolveMagicLinkRecipients}.\n */\nexport interface ConfidentialReferralRecipients {\n readonly count: number;\n /**\n * Sends to the first `capacity` holders (all when omitted), one at a time.\n * The outcome depends only on the holders, `capacity` and each send's\n * result, never on any address the caller handled: an address the sender\n * also typed is sent again, so nothing observable moves when one matches.\n * Never rejects for a failed send: each error is caught and only its `name`\n * is kept (a provider's message can echo the address). The result is\n * server-side only (see {@link ConfidentialDeliveryResult}).\n */\n deliver(\n sendOne: ConfidentialSendOne,\n opts?: ConfidentialDeliverOptions,\n ): Promise<ConfidentialDeliveryResult>;\n /** `{ count }`: what a response, a record or an event may carry. */\n toJSON(): { count: number };\n /** `ConfidentialReferralRecipients(n)`. */\n toString(): string;\n}\n\n/** The one implementation (not exported). */\nclass ConfidentialHolders implements ConfidentialReferralRecipients {\n readonly count: number;\n readonly #addresses: readonly string[];\n\n constructor(addresses: readonly string[]) {\n this.#addresses = Object.freeze([...addresses]);\n this.count = this.#addresses.length;\n Object.freeze(this);\n }\n\n /** See {@link ConfidentialReferralRecipients.deliver}. */\n async deliver(\n sendOne: ConfidentialSendOne,\n opts: ConfidentialDeliverOptions = {},\n ): Promise<ConfidentialDeliveryResult> {\n const { capacity } = opts;\n if (capacity !== undefined && !(Number.isInteger(capacity) && capacity >= 0)) {\n throw new TypeError(\"points-of-contact: capacity must be a non-negative integer\");\n }\n const toSend = capacity === undefined ? this.#addresses : this.#addresses.slice(0, capacity);\n const out: ConfidentialDeliveryResult = {\n count: this.count,\n delivered: 0,\n failed: 0,\n overflow: this.count - toSend.length,\n firstErrorName: null,\n };\n for (const address of toSend) {\n try {\n await sendOne(address);\n out.delivered++;\n } catch (err) {\n out.failed++;\n out.firstErrorName ??= errorName(err);\n }\n }\n return out;\n }\n\n /** `{ count }`: what a response, a record or an event may carry. */\n toJSON(): { count: number } {\n return { count: this.count };\n }\n\n toString(): string {\n return `ConfidentialReferralRecipients(${this.count})`;\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return this.toString();\n }\n}\n\n/** An outstanding in-app add, visible to its own adder only (and never when confidential). */\nconst OWN_PENDING_IN_APP = {\n active: true,\n status: \"pending\",\n origin: \"in_app\",\n is_confidential: { $ne: true },\n} as const;\n\nconst isOwnPendingInApp = (d: PointOfContactDoc, sub: string) =>\n d.active &&\n d.status === \"pending\" &&\n d.origin === \"in_app\" &&\n !d.is_confidential &&\n !d.user_id &&\n d.createdBy === sub &&\n d.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE);\n\n/** A confidential holder that receives magic links (pl-iza): active, confirmed, confidential. */\nconst CONFIDENTIAL_CONFIRMED = { active: true, status: \"confirmed\", is_confidential: true } as const;\n\nconst isConfidentialHolder = (d: PointOfContactDoc) =>\n d.active &&\n d.status === \"confirmed\" &&\n d.is_confidential &&\n d.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE);\n\n/** One contact as other organizations see it, or null (absent or not network-visible). */\nexport async function getContact(\n db: PocDbLike,\n id: string,\n opts: { resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactNetworkView | null> {\n const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).findOne({ id: requireId(\"id\", id) });\n if (!raw) return null;\n const d = normalizePointOfContact(rowOf(raw));\n return networkViews([d], await seatsFor([d], opts.resolveSeats))[0] ?? null;\n}\n\n/**\n * The OWNER read: every contact on the subject, unmasked, every status\n * (pending included), confidential included, seats resolved; inactive rows\n * only when asked. Callers gate it on the actor owning the subject.\n */\nexport async function listOwnerContactsForSubject(\n db: PocDbLike,\n subject: PocSubjectRef,\n opts: { includeInactive?: boolean; resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactOwnerView[]> {\n const docs = await findDocs(db, {\n ...subjectFilter(subject),\n ...(opts.includeInactive ? {} : { active: true }),\n });\n const seats = await seatsFor(docs, opts.resolveSeats);\n return docs.map((d) => toOwnerView(d, seatOf(d, seats)));\n}\n\n/** The STEWARD's review queue: every pending contact, seats resolved. */\nexport async function listPendingContacts(\n db: PocDbLike,\n opts: { resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactStewardView[]> {\n const docs = await findDocs(db, { status: \"pending\" });\n const seats = await seatsFor(docs, opts.resolveSeats);\n return docs.map((d) => toStewardView(d, seatOf(d, seats)));\n}\n","/**\n * The in-app partner add, shared (pl-bt1, pl-e98): an advocate in Thread, PAVE\n * or LEADS names a partner on a share and the contact they type lands in\n * platform-db `pointsofcontact` as a PENDING Point of contact tagged Referrals\n * (magic link). Every app runs THIS implementation against its own platform-db\n * handle; there is no HTTP hop. It is the platform's `addPartnerContact`\n * (platform `lib/points-of-contact/repository.ts`, the store behind\n * `POST /api/partner-contacts`) and the internals it uses from\n * `lib/points-of-contact/core.ts` (`resolveOwner` for an agency or org\n * subject, `insertContact`, the index set, the duplicate-key mapping) and\n * `lib/sharing-settings/recipient-id.ts` (`resolveRecipientId`), moved here\n * with the same rules, the same order of checks and the same refusal codes.\n *\n * ## What it does, in order\n *\n * 1. The actor names the advocate (`actor_required`), the app is one of\n * {@link POC_PARTNER_ADD_APPS} (`invalid_app`), the contact is a strict\n * {@link PocInAppSchema} body (`invalid_contact`), always tagged Referrals\n * (magic link) first.\n * 2. The partner is a strict {@link PartnerContactSelectorSchema} selector\n * (`invalid_partner`), resolved to its owner (decision D1): an agency in any\n * accepted form (`entity_id`, `id`, `_id` in either stored shape, a mapped\n * `registry_agencies` row) becomes `String(agencies._id)`; an org is\n * `String(organizations._id)`. An org whose org GENUINELY mirrors an\n * agency puts the contact on that agency (kickoff D1). Unresolved:\n * `owner_not_found`; an agency and org that are not one partner:\n * `owner_mismatch`. A canonical singleton org (`canonical_org`) or a PAVE\n * 2.0-shape org (`foreign_row_shape`) is refused.\n * 3. What already exists answers the add, looking only at rows the caller may\n * know about, matched on the package identity rule ({@link pocIdentityKey}:\n * `writein:<name>|<preferred email>`), never on a shared email: a visible\n * tagged contact, else the caller's own pending add (both `created:\n * false`, no write); the caller's own add that the partner removed is\n * refused (`contact_deactivated`).\n * 4. The caller's outstanding pending adds are capped per partner\n * ({@link POC_IN_APP_PENDING_CAP_PER_PARTNER}) and across the network\n * ({@link POC_IN_APP_PENDING_CAP_PER_ACTOR}): `too_many_pending_adds`.\n * 5. The row is inserted `pending`, `origin: in_app`, `added_in_app: <app>`,\n * version 1, after the whole-contact rules ({@link pocRuleViolations})\n * and the index check ({@link checkPocIndexes}: the writer never creates\n * an index; a missing one is `indexes_missing`, 503). A simultaneous\n * identical add that won the insert (`duplicate_pending_add`) answers with\n * the winner's row; an add that finds a cap exceeded after its insert\n * withdraws itself (429).\n *\n * ## The caller's part\n *\n * The full contract is the package README (\"Caller contract\"). In short:\n * `actor.id` is the advocate's Auth0 `sub`, taken server-side from the\n * verified token, never from a request body; `app` is the caller's own server\n * constant and the caller checks the advocate's `allowed_apps` for it; the\n * handle is the deployment's own platform-db, long-lived, reading from the\n * primary; `now` is never taken from a request. The platform's own write\n * guard (`read_only_registry`) is not here.\n *\n * ## No driver import, no logging\n *\n * Like the reads, the handle is typed structurally ({@link PocWriteDbLike}):\n * a `mongodb` `Db` or a mongoose connection's `.db` fits. The driver's\n * `ObjectId` class is passed in ({@link PocWriterDriver}): it builds the\n * ObjectId form of a 24-hex id (production `agencies._id` and\n * `organizations._id` are ObjectIds) and mints the `poc-<hex>` id. Nothing is\n * logged: a domain refusal is a returned code, never a throw, and no message\n * carries a stored value (a contact's email, a driver error's duplicate key).\n * A read or write ERROR (an outage, a stored row that does not parse,\n * `PointOfContactShapeError`) propagates.\n */\n\nimport { z } from \"zod\";\n\nimport { isAgencyOwnOrganization } from \"../orgDirectory/rules.js\";\nimport {\n AGENCIES_COLLECTION,\n ORGANIZATIONS_COLLECTION,\n readAgencyOwnOrganization,\n readDirectoryOrganization,\n type OrgDirectoryReadOptions,\n} from \"../orgDirectory/read.js\";\nimport type { PocDbLike } from \"./reader.js\";\nimport { normalizePointOfContact } from \"./readRules.js\";\nimport {\n POC_IDENTITY_INDEX_FILTER,\n POC_IN_APP_PENDING_INDEX_FILTER,\n POC_IN_APP_PENDING_INDEX_KEY,\n POC_PRIMARY_INDEX_FILTER,\n POINTS_OF_CONTACT_COLLECTION,\n POINT_OF_CONTACT_INDEXES,\n PocInAppSchema,\n pocIdentityKey,\n pocRuleViolations,\n type PocInApp,\n type PocInAppInput,\n type PocOwner,\n type PointOfContactDoc,\n} from \"./schemas.js\";\nimport {\n POC_ADDED_IN_APPS,\n REFERRALS_MAGIC_LINK_PURPOSE,\n pocInitialStatus,\n type PocAddedInApp,\n type PocStatus,\n} from \"./vocabulary.js\";\n\n// ─── Handle and driver ───────────────────────────────────────────────\n\n/** The slice of a driver cursor the writer uses. */\nexport interface PocWriteCursorLike {\n toArray(): Promise<unknown[]>;\n}\n\n/** One entry of a driver `indexes()` (`listIndexes`) listing. */\nexport interface PocIndexInfoLike {\n name?: unknown;\n key?: unknown;\n unique?: unknown;\n partialFilterExpression?: unknown;\n}\n\n/** The options the writer passes to `createIndex`. */\nexport interface PocCreateIndexOptions {\n name: string;\n unique?: boolean;\n partialFilterExpression?: Record<string, unknown>;\n}\n\n/** The slice of a driver `Collection` the writer uses. */\nexport interface PocWriteCollectionLike {\n find(filter: Record<string, unknown>, options?: Record<string, unknown>): PocWriteCursorLike;\n findOne(filter: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;\n countDocuments(filter: Record<string, unknown>): Promise<number>;\n insertOne(doc: Record<string, unknown>): Promise<unknown>;\n deleteOne(filter: Record<string, unknown>): Promise<unknown>;\n /** Used by the platform's {@link ensurePocIndexes} only; the writer never creates an index. */\n createIndex(key: Record<string, 1 | -1>, options: PocCreateIndexOptions): Promise<unknown>;\n indexes(): Promise<PocIndexInfoLike[]>;\n}\n\n/** The slice of a driver `Db` the writer uses: a platform-db handle the caller may write. */\nexport interface PocWriteDbLike {\n collection(name: string): PocWriteCollectionLike;\n}\n\n/** The driver's ObjectId class (`mongodb`'s `ObjectId`, or `mongoose.Types.ObjectId`). */\nexport interface PocObjectIdClass {\n new (hex?: string): { toHexString(): string };\n}\n\n/** What the writer needs from the caller's driver. */\nexport interface PocWriterDriver {\n ObjectId: PocObjectIdClass;\n}\n\n// ─── Vocabulary of the in-app add ────────────────────────────────────\n\n/** The apps an in-app add may come from: {@link POC_ADDED_IN_APPS} less `platform`. */\nexport type PocPartnerAddApp = Exclude<PocAddedInApp, \"platform\">;\nexport const POC_PARTNER_ADD_APPS = POC_ADDED_IN_APPS.filter(\n (a): a is PocPartnerAddApp => a !== \"platform\",\n) as readonly PocPartnerAddApp[];\n\nconst directoryId = z.string().trim().min(1).max(200);\n\n/**\n * The partner the advocate picked or created, in the directory id universe\n * (D1): `agency_id` = `String(agencies._id)` or any form that resolves to it,\n * `org_id` = `String(organizations._id)`. One key, or both when they are a\n * genuine mirror pair. The same keys as `listReferralContactsForPartner`, so\n * an app writes and reads one partner the same way. Strict: a subject the\n * body picks is refused.\n */\nexport const PartnerContactSelectorSchema = z\n .object({ agency_id: directoryId.optional(), org_id: directoryId.optional() })\n .strict()\n .refine((p) => Boolean(p.agency_id || p.org_id), {\n message: \"Name the partner's agency_id or org_id.\",\n });\nexport type PartnerContactSelector = z.infer<typeof PartnerContactSelectorSchema>;\nexport type PartnerContactSelectorInput = z.input<typeof PartnerContactSelectorSchema>;\n\n/** Outstanding (pending, active) in-app adds one adder may have across the network. */\nexport const POC_IN_APP_PENDING_CAP_PER_ACTOR = 25;\n/** Outstanding (pending, active) in-app adds one adder may have on one partner. */\nexport const POC_IN_APP_PENDING_CAP_PER_PARTNER = 5;\n\n// ─── Indexes ─────────────────────────────────────────────────────────\n\n/**\n * One outstanding in-app add per adder, per subject and identity\n * ({@link POC_IN_APP_PENDING_INDEX_KEY}: the stored `identity_key`, name +\n * preferred email). Two simultaneous identical first adds race to the insert;\n * the loser's E11000 maps to `duplicate_pending_add`, which\n * {@link mintPartnerContact} answers with the winner's row: the index and the\n * matcher ({@link pocRowsWithIdentity}) use the same key, so the re-read always\n * finds the winner.\n *\n * Not keyed on emails: people share mailboxes (`intake@`), and a\n * \"shares ANY email\" rule (an interim 0.30.0 platform build, multikey on\n * `emails.value`) answered one person's add with another's row and let a\n * removed row block every later add sharing a secondary mailbox.\n */\nexport const POC_IN_APP_PENDING_INDEX = POINT_OF_CONTACT_INDEXES.inAppPending;\n/** The steward's review queue, paged oldest first (platform `listPendingContacts`). */\nexport const POC_PENDING_QUEUE_INDEX = POINT_OF_CONTACT_INDEXES.pendingQueue;\n\nconst indexRuns = new WeakMap<object, Promise<void>>();\n\n/**\n * FOR THE PLATFORM (its deploy or boot), never an app's writer: Thread and\n * PAVE hold no index privilege, and {@link mintPartnerContact} only checks\n * the indexes ({@link checkPocIndexes}). The platform must deploy and run this\n * before any app writes.\n *\n * Create the `pointsofcontact` indexes, the platform's full set: plain\n * `createIndex` calls, idempotent (memoized per handle, retried after a\n * failure; a failure propagates). No migration: no data or index existed\n * before 0.30.0. The partial unique indexes are the store's uniqueness rules:\n * no twin of one person among a subject's visible rows, at most one visible\n * primary per subject, and one outstanding in-app add per adder, subject and\n * identity ({@link POC_IN_APP_PENDING_INDEX}). Pass a long-lived handle: the\n * memo is keyed on it.\n */\nexport function ensurePocIndexes(db: PocWriteDbLike): Promise<void> {\n const memo = indexRuns.get(db);\n if (memo) return memo;\n const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);\n const ix = POINT_OF_CONTACT_INDEXES;\n const run = (async () => {\n await coll.createIndex({ id: 1 }, { name: ix.id, unique: true });\n await coll.createIndex({ subject_type: 1, subject_id: 1, active: 1 }, { name: ix.subject });\n await coll.createIndex({ agency_id: 1, purposes: 1, active: 1 }, { name: ix.agencyPurpose });\n await coll.createIndex({ org_id: 1, purposes: 1, active: 1 }, { name: ix.orgPurpose });\n await coll.createIndex({ status: 1 }, { name: ix.status });\n await coll.createIndex(\n { agency_id: 1, subject_type: 1, subject_id: 1, identity_key: 1 },\n {\n name: ix.identity,\n unique: true,\n partialFilterExpression: { ...POC_IDENTITY_INDEX_FILTER },\n },\n );\n await coll.createIndex(\n { agency_id: 1, subject_type: 1, subject_id: 1 },\n { name: ix.primary, unique: true, partialFilterExpression: { ...POC_PRIMARY_INDEX_FILTER } },\n );\n await coll.createIndex(\n { ...POC_IN_APP_PENDING_INDEX_KEY },\n {\n name: POC_IN_APP_PENDING_INDEX,\n unique: true,\n partialFilterExpression: { ...POC_IN_APP_PENDING_INDEX_FILTER },\n },\n );\n await coll.createIndex({ status: 1, createdAt: 1, id: 1 }, { name: POC_PENDING_QUEUE_INDEX });\n })().catch((err) => {\n indexRuns.delete(db);\n throw err;\n });\n indexRuns.set(db, run);\n return run;\n}\n\nconst indexesChecked = new WeakMap<object, true>();\n\nconst codeOf = (err: unknown) =>\n err && typeof err === \"object\" ? (err as { code?: unknown }).code : undefined;\n/** NamespaceNotFound: `listIndexes` on a collection that does not exist. */\nconst NAMESPACE_NOT_FOUND = 26;\n\nconst sameKey = (got: unknown, want: Record<string, number>) => {\n if (!got || typeof got !== \"object\") return false;\n const g = Object.entries(got);\n const w = Object.entries(want);\n return g.length === w.length && w.every(([k, v], i) => g[i][0] === k && Number(g[i][1]) === v);\n};\n\nconst sameFilter = (got: unknown, want: Record<string, unknown> | undefined) => {\n if (!want) return got === undefined || got === null;\n if (!got || typeof got !== \"object\") return false;\n const sorted = (o: object) =>\n JSON.stringify(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : 1)));\n return sorted(got) === sorted(want);\n};\n\n/** The indexes the writer's guarantees rest on: the `id` and in-app pending unique indexes. */\nconst REQUIRED_INDEXES: { key: Record<string, number>; filter?: Record<string, unknown> }[] = [\n { key: { id: 1 } },\n { key: { ...POC_IN_APP_PENDING_INDEX_KEY }, filter: { ...POC_IN_APP_PENDING_INDEX_FILTER } },\n];\n\n/**\n * Whether the indexes the writer relies on exist, read through `listIndexes`\n * (the writer never creates one: least privilege; the platform creates them\n * with {@link ensurePocIndexes}). Each required index must exist with exactly\n * its key (fields, order, direction), `unique: true` and exactly its partial\n * filter (under any name): `id` unique, and {@link POC_IN_APP_PENDING_INDEX}\n * (the race recovery and the dedupe depend on it). A missing collection\n * (NamespaceNotFound) or index refuses the write, `indexes_missing` (503):\n * fail closed. A pass is memoized per handle; a refusal is not, so the next\n * add re-checks. Any other read error propagates.\n */\nexport async function checkPocIndexes(db: PocWriteDbLike): Promise<PartnerContactFailure | null> {\n if (indexesChecked.has(db)) return null;\n let listed: PocIndexInfoLike[];\n try {\n listed = await db.collection(POINTS_OF_CONTACT_COLLECTION).indexes();\n } catch (err) {\n if (codeOf(err) === NAMESPACE_NOT_FOUND) return INDEXES_MISSING;\n throw err;\n }\n const present = REQUIRED_INDEXES.every((want) =>\n listed.some(\n (ix) =>\n ix.unique === true &&\n sameKey(ix.key, want.key) &&\n sameFilter(ix.partialFilterExpression, want.filter),\n ),\n );\n if (!present) return INDEXES_MISSING;\n indexesChecked.set(db, true);\n return null;\n}\n\n// ─── Results ─────────────────────────────────────────────────────────\n\n/** Every refusal {@link mintPartnerContact} can return, as the platform route answers them. */\nexport const PARTNER_CONTACT_FAILURE_REASONS = [\n \"actor_required\",\n \"invalid_app\",\n \"invalid_contact\",\n \"invalid_partner\",\n \"owner_not_found\",\n \"owner_mismatch\",\n \"canonical_org\",\n \"foreign_row_shape\",\n \"contact_deactivated\",\n \"too_many_pending_adds\",\n \"duplicate_pending_add\",\n \"duplicate_contact\",\n \"primary_exists\",\n \"duplicate_contact_id\",\n \"duplicate_key\",\n \"user_id_xor_person_id\",\n \"seat_contact_has_own_reach\",\n \"display_name_required\",\n \"referral_contact_needs_email\",\n \"indexes_missing\",\n] as const;\nexport type PartnerContactFailureReason = (typeof PARTNER_CONTACT_FAILURE_REASONS)[number];\n\n/**\n * A domain refusal: `status` is the HTTP status the platform route answers it\n * with, `reason` its code, `message` a fixed human sentence, or for\n * `invalid_contact` / `invalid_partner` the schema's issue list (paths and\n * rule messages). Never a stored value.\n */\nexport interface PartnerContactFailure {\n ok: false;\n status: 400 | 409 | 429 | 503;\n reason: PartnerContactFailureReason;\n message?: string;\n}\n\n/** What an in-app add returns to the app: the contact's id and status, never another org's contact details. */\nexport interface PartnerContactReceipt {\n id: string;\n status: PocStatus;\n /** False when an equivalent contact already existed and nothing was written. */\n created: boolean;\n /** Where the store put it: the partner's agency when the org has a genuine-mirror agency (kickoff D1), else the org. */\n subject_type: PocOwner[\"subject_type\"];\n subject_id: string;\n agency_id: string | null;\n org_id: string | null;\n}\n\nexport type PartnerContactResult =\n | { ok: true; value: PartnerContactReceipt }\n | PartnerContactFailure;\n\nfunction fail(\n status: PartnerContactFailure[\"status\"],\n reason: PartnerContactFailureReason,\n message?: string,\n): PartnerContactFailure {\n return { ok: false, status, reason, ...(message ? { message } : {}) };\n}\n\nconst INDEXES_MISSING = fail(\n 503,\n \"indexes_missing\",\n \"The points-of-contact indexes are not in place; the platform must create them (ensurePocIndexes) before an app writes.\",\n);\n\nconst isFailure = (v: unknown): v is PartnerContactFailure =>\n !!v && typeof v === \"object\" && (v as { ok?: unknown }).ok === false;\n\nfunction invalid(\n err: z.ZodError,\n reason: \"invalid_contact\" | \"invalid_partner\",\n): PartnerContactFailure {\n const issues = err.issues.map((i) => `${i.path.map(String).join(\".\") || \"(body)\"}: ${i.message}`);\n return fail(400, reason, issues.join(\"; \"));\n}\n\n// ─── Ids ─────────────────────────────────────────────────────────────\n\nconst HEX_24 = /^[0-9a-fA-F]{24}$/;\n/** A 24-hex id in one spelling (lowercase), as `String(ObjectId)` prints it. */\nconst canonicalId = (v: string): string => (HEX_24.test(v) ? v.toLowerCase() : v);\nconst idOf = (v: unknown): string | null =>\n v === null || v === undefined || v === \"\" ? null : String(v);\n\ninterface Ids {\n /** Every stored form of one id: the string, plus its ObjectId when 24-hex. Feed to `$in`. */\n forms(value: string): unknown[];\n /** The org-directory reads' ObjectId factory. */\n read: OrgDirectoryReadOptions;\n /** A fresh `poc-<24 hex>` id. */\n newId(): string;\n}\n\nfunction idsOf(driver: PocWriterDriver): Ids {\n const { ObjectId } = driver;\n return {\n forms: (value) => (HEX_24.test(value) ? [value, new ObjectId(value)] : [value]),\n read: { toObjectId: (hex) => new ObjectId(hex) },\n newId: () => `poc-${new ObjectId().toHexString()}`,\n };\n}\n\n// ─── Agency resolution (platform `resolveRecipientId`) ───────────────\n\nconst REGISTRY_AGENCIES_COLLECTION = \"registry_agencies\";\nconst AGENCY_PROJECTION = { projection: { _id: 1, entity_id: 1, id: 1 } };\n\ninterface AgencyRowLike {\n _id?: unknown;\n entity_id?: unknown;\n id?: unknown;\n}\n\n/** Every string form that names a row: `entity_id`, `id`, `String(_id)`. */\nfunction formsOf(row: AgencyRowLike): string[] {\n const out: string[] = [];\n if (typeof row.entity_id === \"string\" && row.entity_id !== \"\") out.push(row.entity_id);\n if (typeof row.id === \"string\" && row.id !== \"\") out.push(row.id);\n if (row._id !== undefined && row._id !== null) out.push(String(row._id));\n return [...new Set(out)];\n}\n\n/** The three-id-universe agency match: `entity_id`, `id`, or `_id` in either stored form. */\nconst agencyIdFilter = (ids: Ids, agencyId: string): Record<string, unknown> => ({\n $or: [{ entity_id: agencyId }, { id: agencyId }, { _id: { $in: ids.forms(agencyId) } }],\n});\n\n/** First an `agencies` row the form names; else a registry row it names, mapped to the `agencies` row carrying one of its forms. */\nfunction resolveRecipient(\n form: string,\n agencies: readonly AgencyRowLike[],\n registry: readonly AgencyRowLike[],\n): string | null {\n const direct = agencies.find((a) => formsOf(a).includes(form));\n if (direct) return String(direct._id);\n const reg = registry.find((r) => formsOf(r).includes(form));\n if (!reg) return null;\n const regForms = formsOf(reg);\n const mapped = agencies.find((a) => formsOf(a).some((f) => regForms.includes(f)));\n return mapped ? String(mapped._id) : null;\n}\n\n/**\n * `String(_id)` of the platform-db `agencies` row a form names, or null. The\n * registry (`registry_agencies`) is read from the same handle: the platform\n * writes only when its registry handle IS platform-db. Read errors propagate.\n */\nasync function resolveAgencyId(db: PocWriteDbLike, ids: Ids, form: string): Promise<string | null> {\n const agencies = db.collection(AGENCIES_COLLECTION);\n const direct = (await agencies\n .find(agencyIdFilter(ids, form), AGENCY_PROJECTION)\n .toArray()) as AgencyRowLike[];\n if (direct.length > 0) return resolveRecipient(form, direct, []);\n const registry = (await db\n .collection(REGISTRY_AGENCIES_COLLECTION)\n .find(agencyIdFilter(ids, form), AGENCY_PROJECTION)\n .toArray()) as AgencyRowLike[];\n if (registry.length === 0) return null;\n const regForms = formsOf(registry[0]);\n const mapped = (await agencies\n .find({ $or: regForms.map((f) => agencyIdFilter(ids, f)) }, AGENCY_PROJECTION)\n .toArray()) as AgencyRowLike[];\n return resolveRecipient(form, mapped, registry);\n}\n\n/** The stored agency key of a form, canonical, or null. */\nasync function agencyKey(db: PocWriteDbLike, ids: Ids, form: string): Promise<string | null> {\n const id = await resolveAgencyId(db, ids, canonicalId(form));\n return id ? canonicalId(id) : null;\n}\n\n// ─── Owner (platform `resolveOwner`, agency and org subjects) ────────\n\nconst OWNER_NOT_FOUND = fail(\n 400,\n \"owner_not_found\",\n \"The contact's owner does not resolve to a platform agency or organization.\",\n);\nconst OWNER_MISMATCH = fail(\n 400,\n \"owner_mismatch\",\n \"The agency and organization named are not the same partner.\",\n);\n\n/** The agency whose OWN organization `org` is (both halves of the pair), or null. */\nasync function genuineMirrorAgency(\n db: PocWriteDbLike,\n ids: Ids,\n org: Record<string, unknown>,\n): Promise<string | null> {\n const declared = idOf(org.agencyId);\n if (!declared) return null;\n const agency = (await db\n .collection(AGENCIES_COLLECTION)\n .findOne(\n { _id: { $in: ids.forms(canonicalId(declared)) } },\n { projection: { _id: 1, organizationId: 1 } },\n )) as { _id?: unknown; organizationId?: unknown } | null;\n if (!agency || !isAgencyOwnOrganization(org, agency)) return null;\n return agencyKey(db, ids, String(agency._id));\n}\n\n/**\n * The selector → the stored owner. An agency names the agency subject (an org\n * named with it must be its genuine mirror); an org alone names the org\n * subject, rewritten to its genuine-mirror agency when it has one (kickoff\n * D1). Rows carry the other key only when the pair is a genuine mirror.\n */\nasync function resolvePartnerOwner(\n db: PocWriteDbLike,\n ids: Ids,\n p: PartnerContactSelector,\n): Promise<PocOwner | PartnerContactFailure> {\n let agencyId: string | null = null;\n if (p.agency_id) {\n agencyId = await agencyKey(db, ids, p.agency_id);\n if (!agencyId) return OWNER_NOT_FOUND;\n }\n\n let org: Record<string, unknown> | null = null;\n if (p.org_id) {\n org = (await db\n .collection(ORGANIZATIONS_COLLECTION)\n .findOne(\n { _id: { $in: ids.forms(canonicalId(p.org_id)) } },\n { projection: { _id: 1, agencyId: 1 } },\n )) as Record<string, unknown> | null;\n if (!org) return OWNER_NOT_FOUND;\n }\n const orgId = org ? canonicalId(String(org._id)) : null;\n\n if (!agencyId) {\n if (!org || !orgId) return OWNER_NOT_FOUND;\n const mirrorAgency = await genuineMirrorAgency(db, ids, org);\n if (mirrorAgency) {\n return {\n subject_type: \"agency\",\n subject_id: mirrorAgency,\n agency_id: mirrorAgency,\n org_id: orgId,\n };\n }\n return { subject_type: \"org\", subject_id: orgId, agency_id: null, org_id: orgId };\n }\n\n const own = await readAgencyOwnOrganization(db, agencyId, ids.read);\n const mirrorOrg = own ? canonicalId(own.id) : null;\n if (orgId && orgId !== mirrorOrg) return OWNER_MISMATCH;\n return { subject_type: \"agency\", subject_id: agencyId, agency_id: agencyId, org_id: mirrorOrg };\n}\n\n/**\n * The partner's organization row must be one an in-app add may name: never a\n * canonical singleton (Unknown, Anonymous) and never a PAVE 2.0-shape row, the\n * shapes the org directory also refuses (`organizationRowShape`).\n */\nasync function refuseForeignPartnerOrg(\n db: PocWriteDbLike,\n ids: Ids,\n orgId: string | null,\n): Promise<PartnerContactFailure | null> {\n if (!orgId) return null;\n const org = await readDirectoryOrganization(db, orgId, ids.read);\n if (org?.shape === \"canonical\") {\n return fail(409, \"canonical_org\", \"A canonical singleton organization is not a partner.\");\n }\n if (org?.shape === \"pave\") {\n return fail(\n 409,\n \"foreign_row_shape\",\n \"This organization is a PAVE 2.0-shape row; an in-app contact is not added to it.\",\n );\n }\n return null;\n}\n\n// ─── Existing rows ───────────────────────────────────────────────────\n\n/**\n * The rows on the resolved subject with this identity ({@link pocIdentityKey},\n * as stored in `identity_key`), any status or activity: the same key as\n * {@link POC_IN_APP_PENDING_INDEX}, so a raced add always finds the row that\n * won. The index and this matcher must agree, which is why both live here.\n * A row that does not parse throws.\n */\nexport async function pocRowsWithIdentity(\n db: PocDbLike,\n owner: Pick<PocOwner, \"agency_id\" | \"subject_type\" | \"subject_id\">,\n identityKey: string,\n): Promise<PointOfContactDoc[]> {\n const raw = await db\n .collection(POINTS_OF_CONTACT_COLLECTION)\n .find({\n agency_id: owner.agency_id,\n subject_type: owner.subject_type,\n subject_id: owner.subject_id,\n identity_key: identityKey,\n })\n .toArray();\n return raw\n .map((r) => normalizePointOfContact(r as Record<string, unknown>))\n .filter((d) => d.identity_key === identityKey);\n}\n\n/** The add's identity: a write-in, keyed on its name and preferred email. */\nconst identityOf = (body: PocInApp) =>\n pocIdentityKey({\n user_id: null,\n person_id: null,\n display_name: body.display_name,\n emails: body.emails,\n });\n\nconst ownInApp = (d: PointOfContactDoc, actorId: string) =>\n d.origin === \"in_app\" && d.createdBy === actorId;\n\n/**\n * What an in-app add of `body` on the resolved subject already is, looking\n * only at rows the caller may know about (no oracle for the rest):\n * - `visible`: an active, confirmed, not confidential contact with the same\n * identity that already carries every purpose asked for. Preferred.\n * - `own_pending`: the caller's own outstanding in-app add of the identity.\n * - `own_deactivated`: the caller's own in-app add of the identity that the\n * partner (or the steward) has since removed. Re-adding it is refused.\n * Another adder's pending row, a confidential contact, a contact without the\n * purposes and a contact someone else removed never match: such an add lands\n * as a new pending row, the steward's duplicate to resolve.\n */\nfunction classifyExisting(rows: PointOfContactDoc[], body: PocInApp, actorId: string) {\n const visible = rows.find(\n (d) =>\n d.active &&\n d.status === \"confirmed\" &&\n !d.is_confidential &&\n body.purposes.every((p) => d.purposes.includes(p)),\n );\n if (visible) return { kind: \"visible\" as const, doc: visible };\n const pending = rows.find((d) => d.active && d.status === \"pending\" && ownInApp(d, actorId));\n if (pending) return { kind: \"own_pending\" as const, doc: pending };\n const removed = rows.find((d) => !d.active && ownInApp(d, actorId));\n if (removed) return { kind: \"own_deactivated\" as const, doc: removed };\n return null;\n}\n\n// ─── Caps ────────────────────────────────────────────────────────────\n\n/** The adder's two caps: outstanding pending in-app adds on this partner, and across the network. */\nfunction pendingCaps(owner: PocOwner, actorId: string) {\n const mine = { createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER };\n return [\n {\n filter: {\n ...mine,\n agency_id: owner.agency_id,\n subject_type: owner.subject_type,\n subject_id: owner.subject_id,\n },\n cap: POC_IN_APP_PENDING_CAP_PER_PARTNER,\n refusal: fail(\n 429,\n \"too_many_pending_adds\",\n `At most ${POC_IN_APP_PENDING_CAP_PER_PARTNER} contacts you added to one partner can wait for HTI Labs at a time.`,\n ),\n },\n {\n filter: mine,\n cap: POC_IN_APP_PENDING_CAP_PER_ACTOR,\n refusal: fail(\n 429,\n \"too_many_pending_adds\",\n `At most ${POC_IN_APP_PENDING_CAP_PER_ACTOR} contacts you added can wait for HTI Labs at a time.`,\n ),\n },\n ];\n}\n\n/** The early refusal: the adder is already at a cap before inserting. */\nasync function checkPendingCaps(\n db: PocWriteDbLike,\n owner: PocOwner,\n actorId: string,\n): Promise<PartnerContactFailure | null> {\n const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);\n for (const c of pendingCaps(owner, actorId)) {\n if ((await coll.countDocuments(c.filter)) >= c.cap) return c.refusal;\n }\n return null;\n}\n\n/**\n * The binding check, after the insert: the count above and the insert are\n * not atomic, so parallel adds can all pass it. Each new row counts the\n * adder's pending rows (per partner, then across the network) AFTER its own\n * insert; over the cap, it deletes itself and the add is 429. This bounds\n * the outcome at the cap: every surviving row counted at most `cap` rows, and\n * the survivor that counted last counted every survivor (each was inserted\n * before its own count), so no more than `cap` survive. The price is a\n * spurious 429 under contention (a burst may withdraw rows that would have\n * fit; a retry then lands). It holds only if every count reads the primary\n * (README \"Caller contract\"). The row was never acknowledged to anyone, so\n * this is not the \"deactivate, never delete\" removal of a contact.\n */\nasync function overCapAfterInsert(\n db: PocWriteDbLike,\n owner: PocOwner,\n actorId: string,\n id: string,\n): Promise<PartnerContactFailure | null> {\n const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);\n for (const c of pendingCaps(owner, actorId)) {\n if ((await coll.countDocuments(c.filter)) > c.cap) {\n await coll.deleteOne({ id, createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER });\n return c.refusal;\n }\n }\n return null;\n}\n\n// ─── Insert ──────────────────────────────────────────────────────────\n\n/**\n * A duplicate-key error → the refusal for the index it hit, or null when the\n * error is not a duplicate key (the caller rethrows). Mapped per index by\n * name, then by key pattern. The driver's message is never returned: it\n * echoes the duplicate key, i.e. the contact's email.\n */\nexport function pocDuplicateKeyFailure(err: unknown): PartnerContactFailure | null {\n if (!err || typeof err !== \"object\") return null;\n const e = err as { code?: unknown; message?: unknown; keyPattern?: Record<string, unknown> };\n const msg = typeof e.message === \"string\" ? e.message : \"\";\n if (e.code !== 11000 && !/E11000/.test(msg)) return null;\n const ix = POINT_OF_CONTACT_INDEXES;\n const keys = Object.keys(e.keyPattern ?? {}).join(\",\");\n if (msg.includes(POC_IN_APP_PENDING_INDEX) || keys.includes(\"createdBy\")) {\n return fail(\n 409,\n \"duplicate_pending_add\",\n \"This adder already has a pending add of this person on this subject.\",\n );\n }\n if (msg.includes(ix.primary) || keys === \"agency_id,subject_type,subject_id\") {\n return fail(\n 409,\n \"primary_exists\",\n \"The subject already has a primary contact. Use setPrimary to move it.\",\n );\n }\n if (msg.includes(ix.identity) || keys.includes(\"identity_key\")) {\n return fail(409, \"duplicate_contact\", \"This person is already an active contact on this subject.\");\n }\n if (msg.includes(ix.id) || keys === \"id\") {\n return fail(409, \"duplicate_contact_id\", \"A contact with this id exists.\");\n }\n return fail(409, \"duplicate_key\", \"The contact collides with a unique index.\");\n}\n\n/**\n * Build, check and insert one in-app contact: `active`, version 1, `pending`\n * (D3: `pocInitialStatus(\"in_app\")`), unstamped, no seat or person link, not\n * primary, not confidential, no notes.\n */\nasync function insertInAppContact(\n db: PocWriteDbLike,\n f: {\n id: string;\n owner: PocOwner;\n body: PocInApp;\n app: PocPartnerAddApp;\n actorId: string;\n now: Date;\n },\n): Promise<{ ok: true; value: PointOfContactDoc } | PartnerContactFailure> {\n const at = f.now.toISOString();\n const base = {\n user_id: null,\n person_id: null,\n display_name: f.body.display_name,\n emails: f.body.emails,\n phones: f.body.phones ?? [],\n };\n const doc: PointOfContactDoc = {\n id: f.id,\n subject_type: f.owner.subject_type,\n subject_id: f.owner.subject_id,\n agency_id: f.owner.agency_id,\n org_id: f.owner.org_id,\n ...base,\n purposes: f.body.purposes,\n urgent_methods: f.body.urgent_methods ?? [],\n is_primary: false,\n is_confidential: false,\n active: true,\n notes: null,\n status: pocInitialStatus(\"in_app\"),\n origin: \"in_app\",\n added_in_app: f.app,\n identity_key: pocIdentityKey(base),\n confirmed_by: null,\n confirmed_at: null,\n deactivated_by: null,\n deactivated_at: null,\n version: 1,\n createdBy: f.actorId,\n createdAt: at,\n updatedBy: f.actorId,\n updatedAt: at,\n };\n\n const [broken] = pocRuleViolations(doc);\n if (broken) return fail(400, broken.reason, broken.message);\n\n const noIndexes = await checkPocIndexes(db);\n if (noIndexes) return noIndexes;\n try {\n await db.collection(POINTS_OF_CONTACT_COLLECTION).insertOne({ ...doc });\n } catch (err) {\n const dup = pocDuplicateKeyFailure(err);\n if (dup) return dup;\n throw err;\n }\n return { ok: true, value: doc };\n}\n\n// ─── The writer ──────────────────────────────────────────────────────\n\n/** Who is adding: the advocate. Never a steward here. */\nexport interface PocInAppActor {\n /**\n * The advocate's Auth0 `sub`, taken SERVER-SIDE from the verified token\n * (as the platform route takes `auth0Sub`), never from a request body or a\n * client-supplied header. Stored as `createdBy`; the adder's dedupe, caps and\n * removed-add refusal key on it.\n */\n id: string;\n}\n\nexport interface MintPartnerContactArgs {\n /** The app the advocate is adding from. */\n app: PocPartnerAddApp;\n /** The partner, by directory id ({@link PartnerContactSelectorSchema}). */\n partner: PartnerContactSelectorInput;\n /** The contact ({@link PocInAppSchema}: a name and at least one email; phones optional). */\n contact: PocInAppInput;\n actor: PocInAppActor;\n /** The mint time (`createdAt`); defaults to now. Server time only, never from a request. */\n now?: Date;\n}\n\n/**\n * An in-app add is ALWAYS tagged Referrals (magic link) (Crysta 2026-10-14;\n * kickoff D1): an explicit `[]` or a list without it gets it added in front;\n * any other purposes asked for are kept.\n */\nfunction withReferralTag(purposes: PocInApp[\"purposes\"]): PocInApp[\"purposes\"] {\n return [\n REFERRALS_MAGIC_LINK_PURPOSE,\n ...purposes.filter((p) => p !== REFERRALS_MAGIC_LINK_PURPOSE),\n ];\n}\n\n/**\n * The in-app partner add, written straight to platform-db (module comment).\n * Every argument is validated at run time as well as typed. Returns a\n * {@link PartnerContactReceipt} (`created: true` for a new pending row,\n * `false` when an equivalent contact answered and nothing was written) or a\n * {@link PartnerContactFailure}; never throws a domain refusal.\n */\nexport async function mintPartnerContact(\n db: PocWriteDbLike,\n args: MintPartnerContactArgs,\n driver: PocWriterDriver,\n): Promise<PartnerContactResult> {\n const actor = args.actor as unknown;\n const actorId =\n actor && typeof actor === \"object\" ? (actor as { id?: unknown }).id : undefined;\n if (typeof actorId !== \"string\" || actorId.trim().length === 0) {\n return fail(400, \"actor_required\", \"An in-app add names the advocate (their Auth0 sub).\");\n }\n if (!(POC_PARTNER_ADD_APPS as readonly unknown[]).includes(args.app)) {\n return fail(400, \"invalid_app\", `An in-app add names its app: ${POC_PARTNER_ADD_APPS.join(\", \")}.`);\n }\n const parsed = PocInAppSchema.safeParse(args.contact);\n if (!parsed.success) return invalid(parsed.error, \"invalid_contact\");\n const body: PocInApp = { ...parsed.data, purposes: withReferralTag(parsed.data.purposes) };\n const partner = PartnerContactSelectorSchema.safeParse(args.partner);\n if (!partner.success) return invalid(partner.error, \"invalid_partner\");\n\n const ids = idsOf(driver);\n const owner = await resolvePartnerOwner(db, ids, partner.data);\n if (isFailure(owner)) return owner;\n const foreign = await refuseForeignPartnerOrg(db, ids, owner.org_id);\n if (foreign) return foreign;\n\n const receipt = (d: PointOfContactDoc, created: boolean): PartnerContactResult => ({\n ok: true,\n value: {\n id: d.id,\n status: d.status,\n created,\n subject_type: owner.subject_type,\n subject_id: owner.subject_id,\n agency_id: owner.agency_id,\n org_id: owner.org_id,\n },\n });\n const existingNow = async () =>\n classifyExisting(await pocRowsWithIdentity(db, owner, identityOf(body)), body, actorId);\n\n const existing = await existingNow();\n if (existing?.kind === \"own_deactivated\") {\n return fail(\n 409,\n \"contact_deactivated\",\n \"You added this contact before and it has since been removed from the partner; it is not added again.\",\n );\n }\n if (existing) return receipt(existing.doc, false);\n\n const capped = await checkPendingCaps(db, owner, actorId);\n if (capped) return capped;\n\n const r = await insertInAppContact(db, {\n id: ids.newId(),\n owner,\n body,\n app: args.app,\n actorId,\n now: args.now ?? new Date(),\n });\n if (!r.ok) {\n if (r.reason !== \"duplicate_pending_add\") return r;\n // A simultaneous identical add won the insert: answer with its row.\n const raced = await existingNow();\n return raced && raced.kind !== \"own_deactivated\" ? receipt(raced.doc, false) : r;\n }\n const overCap = await overCapAfterInsert(db, owner, actorId, r.value.id);\n if (overCap) return overCap;\n return receipt(r.value, true);\n}\n","/**\n * The stored program row of `organizations.programs[]`, as a Zod schema for\n * readers. The Mongoose definition (`schemas/organization-program.ts`,\n * `organizationProgramSchemaDefinition`) is the write-side twin; a test holds\n * the key lists equal.\n */\n\nimport { z } from \"zod\";\n\nimport { PROGRAM_REVIEW_STATUS_VALUES } from \"./vocabulary.js\";\n\n/** The program row's keys, in the fragment's declaration order. */\nexport const ORGANIZATION_PROGRAM_ROW_KEYS = Object.freeze([\n \"programId\",\n \"name\",\n \"description\",\n \"status\",\n \"defaultSharingPolicy\",\n \"reviewStatus\",\n \"addedBy\",\n \"addedInApp\",\n \"addedInSession\",\n \"programType\",\n \"serviceArea\",\n \"providesRelevantServices\",\n \"operatingStartDate\",\n \"operatingEndDate\",\n \"locationId\",\n \"notes\",\n] as const);\n\nexport type OrganizationProgramRowKey = (typeof ORGANIZATION_PROGRAM_ROW_KEYS)[number];\n\nconst optionalText = z.string().nullish();\n/**\n * A detail field of the Program record. A value of the wrong kind reads as not\n * on record (`undefined`) rather than failing the row: a malformed detail must\n * never hide a program from a picker. `./programDetails.ts` shapes the values.\n */\nconst detailText = z.string().nullish().catch(undefined);\n\n/**\n * One stored program row. `programId` + `name` are required; the rest are\n * optional and may be null. Unknown keys are stripped (a reader never relies\n * on a key outside the fragment). The seven Program-record detail keys\n * (`programType` … `notes`, 0.76.0) never fail the row.\n */\nexport const OrganizationProgramRowSchema = z.object({\n programId: z.string().min(1),\n name: z.string().min(1),\n description: optionalText,\n status: optionalText,\n defaultSharingPolicy: optionalText,\n reviewStatus: z\n .enum(PROGRAM_REVIEW_STATUS_VALUES as unknown as [\"pending\", \"confirmed\", \"rejected\"])\n .nullish(),\n addedBy: optionalText,\n addedInApp: optionalText,\n addedInSession: optionalText,\n programType: detailText,\n serviceArea: detailText,\n providesRelevantServices: z.boolean().nullish().catch(undefined),\n operatingStartDate: detailText,\n operatingEndDate: detailText,\n locationId: detailText,\n notes: detailText,\n});\n\nexport type OrganizationProgramRow = z.infer<typeof OrganizationProgramRowSchema>;\n","/**\n * The program-row vocabulary of `organizations.programs[]`: the review\n * lifecycle, the lifecycle codes, the live rule and the name key. Pure (no\n * mongoose): `schemas/organization-program.ts` re-exports these, so the\n * Mongoose fragment and the `org-directory` read contract share one source.\n */\n\n// ─── Review status ──────────────────────────────────────────────────\n\n/**\n * Review lifecycle of a program named inside an app (UDD Program\n * `review_status`). The sheet's own words — a lane's `pending_steward` /\n * `declined` never reach the stored row.\n */\nexport const PROGRAM_REVIEW_STATUS = {\n PENDING: \"pending\",\n CONFIRMED: \"confirmed\",\n REJECTED: \"rejected\",\n} as const;\n\nexport type ProgramReviewStatus =\n (typeof PROGRAM_REVIEW_STATUS)[keyof typeof PROGRAM_REVIEW_STATUS];\n\n/** The three values, for `enum:` declarations and Zod `z.enum`. */\nexport const PROGRAM_REVIEW_STATUS_VALUES = Object.freeze([\n PROGRAM_REVIEW_STATUS.PENDING,\n PROGRAM_REVIEW_STATUS.CONFIRMED,\n PROGRAM_REVIEW_STATUS.REJECTED,\n] as const);\n\nexport function isProgramReviewStatus(value: unknown): value is ProgramReviewStatus {\n return (\n typeof value === \"string\" && (PROGRAM_REVIEW_STATUS_VALUES as readonly string[]).includes(value)\n );\n}\n\n// ─── Lifecycle status ───────────────────────────────────────────────\n\n/**\n * The program lifecycle codes the writers store. `active` is what PAVE 2.0's\n * `POST /organizations/:id/programs` writes; `retired` takes a program out of\n * every picker. Absent reads as active.\n */\nexport const PROGRAM_STATUS = {\n ACTIVE: \"active\",\n RETIRED: \"retired\",\n} as const;\n\nexport type ProgramStatus = (typeof PROGRAM_STATUS)[keyof typeof PROGRAM_STATUS];\n\nexport const PROGRAM_STATUS_VALUES = Object.freeze([\n PROGRAM_STATUS.ACTIVE,\n PROGRAM_STATUS.RETIRED,\n] as const);\n\n// ─── Live rule and name key ─────────────────────────────────────────\n\n/**\n * Whether a program row may be OFFERED (and matched by name on an add).\n * A retired or rejected program is not a place anyone can be enrolled today,\n * so pickers do not list it and typing its name mints a new row rather than\n * binding to it (the prototype's independent pre-review catch, 2026-10-06).\n */\nexport function isLiveOrganizationProgram(row: {\n status?: string | null | undefined;\n reviewStatus?: string | null | undefined;\n}): boolean {\n return (\n row.status !== PROGRAM_STATUS.RETIRED && row.reviewStatus !== PROGRAM_REVIEW_STATUS.REJECTED\n );\n}\n\n/**\n * The key two program names match on: trimmed, lower-cased. Canon:\n * `directoryProgramFor` (platform-prototype `src/surveys.jsx` L4233 @\n * `0fa04c1`); PAVE 2.0's `POST /organizations/:id/programs` dedupes the same\n * way.\n */\nexport function programNameKey(name: string): string {\n return name.trim().toLowerCase();\n}\n","/**\n * The Org record: the ONE definition of what an `organizations` row holds\n * about an organization, for every app that reads or writes the platform-wide\n * registry (Thread, PAVE, the Platform, auth). Pure: no mongoose, no driver.\n * The Mongoose twin is `schemas/organization.ts` (`addOrgRecordFields`); a\n * package test holds the two key lists equal.\n *\n * ## Canon\n *\n * UDD Org Data Object (Notion `7d71ef14abcd832fa3a6816ebe7a5dd9`, § 1 and § 5;\n * schema of record hti-features `udd-schemas/org/Org.v1.json`): an Org is one\n * real-world organization in the one platform-wide registry. It holds its name\n * (legal and common), its acronym, its required type, its parent when it is a\n * unit of a larger one, the two HMIS victim-service-provider answers, and how\n * it arrived and whether HTI Labs has reviewed it. Crysta, 2026-11-10: \"It\n * shouldn't be different in thread vs. pave. And the data objects for Org need\n * to be the same in both apps.\"\n *\n * ## Stored names\n *\n * The UDD spells these snake_case (`legal_name`, `parent_org_id`, ...). The\n * live platform-db writers use camelCase, so the stored names are the UDD's in\n * camelCase, as for the org-type fields (`schemas/agency.ts`) and the program\n * row (`schemas/organization-program.ts`). Two exceptions. The UDD `acronym` is\n * stored as `shortName`: a top-level `acronym` key marks a pre-pl-958 PAVE row\n * (`organizationRowShape`), and PAVE 2.0 already writes `shortName`. And the\n * UDD `id` (the Org's one identifier, a slug such as `the_spring`) is stored as\n * `key`: Mongoose gives every document an `id` of its own (the `_id` as a\n * string), and the Admin Hub's curated store already names it `key`.\n *\n * ## What is NOT here\n *\n * - `name` and `type`: every writer already stores them. `type` is mid-move\n * from the IC-58 number to the CVC-48 key and each app validates the\n * transition form itself until the migration has run.\n * - The row's tenancy and plumbing (`agencyScope`, `agencyId`, `community`,\n * `canonicalKey`, `status`, `programs`, contact fields): unchanged by this\n * module. {@link ORGANIZATION_ROW_KEYS} lists them so a model can be checked\n * against the whole row.\n */\nimport { z } from \"zod\";\n\nimport {\n PROGRAM_REVIEW_STATUS,\n PROGRAM_REVIEW_STATUS_VALUES,\n type ProgramReviewStatus,\n} from \"./vocabulary.js\";\n\n// ─── Review status ──────────────────────────────────────────────────\n\n/**\n * Review lifecycle of an organization added from inside an app. The same three\n * words, and the same lifecycle, as a program named inside an app (UDD Org\n * § 5 \"how it arrived\"; census item 2: \"the same lifecycle a program named\n * inside an app has\"). Absent on a steward row: nothing to review.\n */\nexport const ORG_REVIEW_STATUS = PROGRAM_REVIEW_STATUS;\nexport const ORG_REVIEW_STATUS_VALUES = PROGRAM_REVIEW_STATUS_VALUES;\nexport type OrgReviewStatus = ProgramReviewStatus;\n\n// ─── Lifecycle status ───────────────────────────────────────────────\n\n/**\n * `organizations.status`: 1 active, 2 inactive (soft-deleted; never removed).\n * The codes auth, Thread and PAVE already store.\n */\nexport const ORGANIZATION_STATUS = { ACTIVE: 1, INACTIVE: 2 } as const;\nexport type OrganizationStatus = (typeof ORGANIZATION_STATUS)[keyof typeof ORGANIZATION_STATUS];\n\n/**\n * Whether an organization may be OFFERED in a picker: active (an absent\n * `status` reads active, as legacy rows carry none) and not declined by HTI\n * Labs. A pending organization IS offered: an organization added inside an app\n * is available everywhere from the moment it is added (UDD Org § 2 scenario 1).\n * A stored reference to an organization that is no longer offered still\n * resolves by id.\n */\nexport function isListedOrganization(row: {\n status?: number | null | undefined;\n reviewStatus?: string | null | undefined;\n}): boolean {\n const active = row.status == null || row.status === ORGANIZATION_STATUS.ACTIVE;\n return active && row.reviewStatus !== ORG_REVIEW_STATUS.REJECTED;\n}\n\n// ─── The record's fields ────────────────────────────────────────────\n\n/**\n * The Org definition's fields beyond `name` and `type`, in the Mongoose\n * fragment's declaration order (`orgRecordSchemaDefinition`).\n */\nexport const ORG_RECORD_FIELD_NAMES = Object.freeze([\n \"key\",\n \"legalName\",\n \"commonName\",\n \"shortName\",\n \"website\",\n \"parentOrgId\",\n \"vsp\",\n \"vspPrivateNonprofit\",\n \"reviewStatus\",\n \"addedInApp\",\n \"addedBy\",\n] as const);\nexport type OrgRecordFieldName = (typeof ORG_RECORD_FIELD_NAMES)[number];\n\n/**\n * Stored on the row today and NOT part of the Org definition (UDD Org § 5,\n * \"As built today, and not part of this definition\"; Org.v1's runtime-overlay\n * five: `isCustom`, `added_in_session`, `added_by_user_id`, `type_override`,\n * `division`). PAVE 2.0 writes them; every model declares\n * them so no app silently drops another app's value. `typeKey` is the CVC-48\n * key PAVE writes beside a numeric `type` and retires with the type migration.\n */\nexport const ORG_AS_BUILT_FIELD_NAMES = Object.freeze([\n \"requiresROI\",\n \"isCustom\",\n \"addedByUserId\",\n \"addedInSession\",\n \"division\",\n \"typeOverride\",\n \"typeKey\",\n] as const);\nexport type OrgAsBuiltFieldName = (typeof ORG_AS_BUILT_FIELD_NAMES)[number];\n\n/** The row's keys every writer already stored before this module. */\nexport const ORGANIZATION_BASE_ROW_KEYS = Object.freeze([\n \"name\",\n \"type\",\n \"phones\",\n \"emails\",\n \"address\",\n \"notes\",\n \"status\",\n \"agencyScope\",\n \"agencyId\",\n \"community\",\n \"canonicalKey\",\n \"isAnonymous\",\n \"programs\",\n] as const);\n\n/**\n * Every top-level key of a shared-shape `organizations` row, the record\n * envelope aside. A model that declares exactly these is the same data object\n * as every other app's (`organizationSchemaIssues`, `schemas/organization.ts`).\n */\nexport const ORGANIZATION_ROW_KEYS = Object.freeze([\n ...ORGANIZATION_BASE_ROW_KEYS,\n ...ORG_RECORD_FIELD_NAMES,\n ...ORG_AS_BUILT_FIELD_NAMES,\n] as const);\nexport type OrganizationRowKey = (typeof ORGANIZATION_ROW_KEYS)[number];\n\n/** The record envelope each app's base document adds; never Org facts. */\nexport const ORGANIZATION_ENVELOPE_KEYS = Object.freeze([\n \"_id\",\n \"__v\",\n \"_schemaVersion\",\n \"createdUser\",\n \"createdTime\",\n \"updatedUser\",\n \"updatedTime\",\n] as const);\n\n// ─── The identifier ─────────────────────────────────────────────────\n\n/**\n * The Org's identifier (UDD Org `id`; stored as `key`): the one value that\n * names the same organization in every database, where `_id` is each\n * database's own. A lower-case slug: `the_spring`, `ascension_stjohn`,\n * `org-custom-8daxtira`, `org-6a1f5dadd0c33a5a149f3413`.\n *\n * Rules (the curated store's, Kickoff 13 item 3): unique; never changes once\n * set; never taken from a request body (`OrgIdentityWriteSchema` is strict and\n * does not name it); a new organization's key never encodes its name\n * ({@link mintOrgKey}). A row written before 0.65.0 has none until the\n * registry fill stamps one from a reviewed sheet.\n */\nexport const ORG_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,119}$/;\n\n/** Whether a value is a well-formed Org identifier. */\nexport function isOrgKey(value: unknown): value is string {\n return typeof value === \"string\" && ORG_KEY_PATTERN.test(value);\n}\n\n/**\n * The identifier for an organization created without one (added inside an\n * app, or by a steward typing a new organization): `org-<its _id>`. It encodes\n * no name, so a later rename never makes it wrong.\n */\nexport function mintOrgKey(id: string | { toHexString(): string }): string {\n const hex = (typeof id === \"string\" ? id : id.toHexString()).trim().toLowerCase();\n if (!/^[0-9a-f]{24}$/.test(hex)) {\n throw new Error(\"mintOrgKey: needs the organization's 24-hex _id\");\n }\n return `org-${hex}`;\n}\n\n// ─── Write shape ────────────────────────────────────────────────────\n\n/** A trimmed, non-empty line of text, or null to clear the field. */\nconst line = (max: number) => z.string().trim().min(1).max(max).nullable();\n\n/** The two-step message; the same sentence the Mongoose mount throws. */\nexport const ORG_VSP_TWO_STEP_MESSAGE =\n \"vspPrivateNonprofit is step 2 of the HMIS VSP two-step and requires vsp: true\";\n\n/**\n * The identity half of the record, as a request body may carry it. Every key\n * is optional (a PATCH names only what it changes); `null` clears a field.\n * Strict: an unknown key is refused, so a snake_case spelling never passes as\n * a silent no-op.\n */\nexport const OrgIdentityWriteSchema = z\n .object({\n legalName: line(300),\n commonName: line(300),\n shortName: line(60),\n website: line(500),\n /** Another organization's id (24-hex or a seed slug). Self-reference is the writer's check. */\n parentOrgId: line(120),\n })\n .partial()\n .strict();\nexport type OrgIdentityWrite = z.infer<typeof OrgIdentityWriteSchema>;\n\n/**\n * The two HMIS victim-service-provider answers. Tri-state: `null` is \"not yet\n * captured\", never a coerced false. Step 2 may be answered only with step 1\n * `true` in the same body (an update cannot see the stored row), and a body\n * that sets step 1 to `false` or `null` clears step 2 with it. Only HTI Labs\n * sets them (UDD Org rulings 2026-10-08 and 2026-10-09); the route decides who\n * that is.\n */\nexport const OrgVspWriteSchema = z\n .object({\n vsp: z.boolean().nullable(),\n vspPrivateNonprofit: z.boolean().nullable(),\n })\n .partial()\n .strict()\n .refine((v) => v.vspPrivateNonprofit == null || v.vsp === true, {\n message: ORG_VSP_TWO_STEP_MESSAGE,\n path: [\"vspPrivateNonprofit\"],\n })\n // Step 1 set to anything but `true` clears step 2 in the same write, so a\n // stored \"yes\" on step 2 can never outlive its step 1.\n .transform((v) => (\"vsp\" in v && v.vsp !== true ? { ...v, vspPrivateNonprofit: null } : v));\nexport type OrgVspWrite = z.infer<typeof OrgVspWriteSchema>;\n\n/**\n * How an organization arrived. Never taken from a request body: the server\n * stamps it from the authenticated caller ({@link orgArrivalStamp}).\n *\n * The same three facts, under the same names, as a Program, a Service Listing\n * and a Point of contact carry (`added_by` · `added_in_app` · `review_status`;\n * UDD ratification request R17, \"how an organization arrived\"). The older\n * runtime-overlay names on the row (`addedByUserId`, `isCustom`) are as-built\n * extras; `addedInSession` is carried as on the program row.\n */\nexport interface OrgArrival {\n reviewStatus: OrgReviewStatus;\n /** The app the organization was added in: `thread`, `pave`, `leads`, `platform`. */\n addedInApp: string;\n /** The adding user's platform `users._id`, as a string. */\n addedBy: string;\n /** The session it was added in, when there was one. */\n addedInSession?: string;\n}\n\n/**\n * The arrival stamp for an organization a user adds from inside an app: it is\n * on the list at once and waits for HTI Labs' review (UDD Org § 2 scenario 5;\n * census item 2). A steward's own add carries no stamp.\n */\nexport function orgArrivalStamp(input: {\n app: string;\n userId: string;\n sessionId?: string | null | undefined;\n}): OrgArrival {\n const app = input.app.trim().toLowerCase();\n const userId = input.userId.trim();\n if (!app) throw new Error(\"orgArrivalStamp: app is required\");\n if (!userId) throw new Error(\"orgArrivalStamp: userId is required\");\n const session = input.sessionId?.trim();\n return {\n reviewStatus: ORG_REVIEW_STATUS.PENDING,\n addedInApp: app,\n addedBy: userId,\n ...(session ? { addedInSession: session } : {}),\n };\n}\n\n// ─── Naming rules ───────────────────────────────────────────────────\n\ninterface OrgNames {\n name?: string | null | undefined;\n commonName?: string | null | undefined;\n legalName?: string | null | undefined;\n shortName?: string | null | undefined;\n}\n\nconst clean = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\");\n\n/**\n * The name to use when a sentence or a label names an organization: its common\n * name when it has one, else its name. Canon: the prototype's contact-history\n * register and referral wording (`org.common_name || org.name`).\n */\nexport function orgCommonName(org: OrgNames | null | undefined): string {\n return clean(org?.commonName) || clean(org?.name);\n}\n\n/**\n * The name a report to a funder or HMIS uses: the legal name when captured,\n * else the name (Org.v1 `legal_name`: \"consumers fall back to name when blank\").\n */\nexport function orgLegalName(org: OrgNames | null | undefined): string {\n return clean(org?.legalName) || clean(org?.name);\n}\n\n/** Whether a row's name is nothing but its short name (\"ASJS\" named \"ASJS\"). */\nexport function isShortNameOnly(org: OrgNames | null | undefined): boolean {\n const n = clean(org?.name);\n const a = clean(org?.shortName);\n return !n || (!!a && n.toLowerCase() === a.toLowerCase());\n}\n\n/**\n * How a unit of a larger organization reads: its own name, and \"<parent> unit\"\n * beneath it when the unit has no name beyond its short name (Crysta\n * 2026-09-03, \"No names yet — show the parent\"). A row with a real name keeps\n * it. Canon: the prototype's one resolver, `orgDisplayParts`.\n */\nexport function orgDisplayParts(\n org: OrgNames | null | undefined,\n parent: OrgNames | null | undefined,\n): { name: string; sub: string } {\n const name = clean(org?.name) || clean(org?.shortName);\n const parentName = clean(parent?.name) || clean(parent?.shortName);\n const sub = parentName && isShortNameOnly(org) ? `${parentName} unit` : \"\";\n return { name, sub };\n}\n\n/** {@link orgDisplayParts} on one line: \"ASJS · Ascension St. John Medical Center unit\". */\nexport function orgDisplayName(\n org: OrgNames | null | undefined,\n parent?: OrgNames | null | undefined,\n): string {\n const d = orgDisplayParts(org, parent);\n return d.sub ? `${d.name} · ${d.sub}` : d.name;\n}\n\n/**\n * Why `parentOrgId` may not be set to this value, or null when it may. One\n * level only (the picker folds units under their organization): an\n * organization is never its own parent, a parent is not itself a unit, and an\n * organization that has units cannot become one.\n */\nexport function orgParentIssue(input: {\n orgId: string | null | undefined;\n parentOrgId: string | null | undefined;\n /** The proposed parent's own `parentOrgId`, when the parent row was read. */\n parentsParentOrgId?: string | null | undefined;\n /** Whether any organization already names `orgId` as its parent. */\n hasUnits?: boolean | undefined;\n}): \"self\" | \"parent_is_unit\" | \"org_has_units\" | null {\n const parent = clean(input.parentOrgId).toLowerCase();\n if (!parent) return null;\n if (clean(input.orgId).toLowerCase() === parent) return \"self\";\n if (clean(input.parentsParentOrgId)) return \"parent_is_unit\";\n if (input.hasUnits) return \"org_has_units\";\n return null;\n}\n","/**\n * The Program record's own fields beyond its name, on a stored\n * `organizations.programs[]` row: what kind of program it is, where it\n * serves, whether it provides direct services to victims, when it operates,\n * which of its organization's sites it works from, and notes.\n *\n * Canon: the UDD Program Data Object (`program_type` · `service_area` ·\n * `provides_relevant_services` · `operating_start_date` ·\n * `operating_end_date` · `location_id` · `notes`; profile confirmed by Crysta\n * 2026-10-05) and the Admin Hub's program editor (platform-prototype\n * `src/screens.jsx`, `OrgProgramFields`). Stored camelCase, like the rest of\n * the row. The Platform's program editor has written these since 2026-11-11\n * (platform #148, #155); this module is the Platform's own reader and write\n * shapes (`lib/org-directory/program-details.ts`) made shared, so Thread, PAVE\n * and the Platform read and validate one program the same way.\n *\n * The rules it carries:\n *\n * - NOT ON RECORD IS NULL. Every field is optional. A value of the wrong\n * kind reads as not on record; it never fails the program row.\n * - `providesRelevantServices` has three states: true, false, and null\n * (never asked). Null is never coerced to No.\n * - A date is a real calendar day, `YYYY-MM-DD`, stored as a string.\n * - `programType` is a key of the organization-type codebook (CVC-48\n * `core-referral_entity_category`). This subpath stays free of the\n * codebook, so the reader returns the stored string and the write check\n * takes the caller's type rule: resolve a read with `resolveOrgTypeKey`\n * (`@htilabs/platform-common-models/constants`) and offer only\n * `ORG_TYPE_SELECTABLE_KEYS`.\n * - `locationId` names a site of the program's OWN organization. Whether it\n * is one is the writer's check (it needs the database); the write check\n * here only bounds the string.\n *\n * NO ZOD HERE, on purpose. This package is built with zod 3; the Platform and\n * Thread run zod 4, and a zod-3 field cannot be nested in a zod-4 object. So\n * the write rules are plain data (`PROGRAM_DETAIL_RULES`) and one plain\n * function (`checkProgramDetails`) that any app wraps in its own schema\n * library.\n *\n * Pure: no mongoose, no driver, no codebook import, no schema library.\n */\n\n/** The detail keys, in the program editor's field order. */\nexport const PROGRAM_DETAIL_KEYS = Object.freeze([\n \"programType\",\n \"serviceArea\",\n \"providesRelevantServices\",\n \"operatingStartDate\",\n \"operatingEndDate\",\n \"locationId\",\n \"notes\",\n] as const);\nexport type ProgramDetailKey = (typeof PROGRAM_DETAIL_KEYS)[number];\n\n/** A program's detail fields as a reader sees them (`null` = not on record). */\nexport interface ProgramDetails {\n /** The stored organization-type key (CVC-48), unresolved; null when absent. */\n programType: string | null;\n /** Free text: the service area or jurisdiction. */\n serviceArea: string | null;\n /** Direct services to victims: true, false, or null (never asked; not a No). */\n providesRelevantServices: boolean | null;\n /** A calendar day, `YYYY-MM-DD`. */\n operatingStartDate: string | null;\n /** A calendar day, `YYYY-MM-DD`. */\n operatingEndDate: string | null;\n /** The id of the organization's site the program works from, or null. */\n locationId: string | null;\n notes: string | null;\n}\n\n/** The longest service area the editor stores. */\nexport const PROGRAM_SERVICE_AREA_MAX = 200;\n/** The longest program note the editor stores. */\nexport const PROGRAM_NOTES_MAX = 4000;\n/** The longest site id a program row stores. */\nexport const PROGRAM_LOCATION_ID_MAX = 200;\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** A real calendar day in `YYYY-MM-DD` (what a date input sends). */\nexport function isCalendarDay(v: unknown): v is string {\n if (typeof v !== \"string\" || !DAY.test(v)) return false;\n const [y, m, d] = v.split(\"-\").map(Number) as [number, number, number];\n const t = new Date(Date.UTC(y, m - 1, d));\n return t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d;\n}\n\nconst text = (v: unknown): string | null =>\n typeof v === \"string\" && v.trim() ? v.trim() : null;\n\n/**\n * One stored row's detail fields. A value of the wrong kind (a date that is\n * not a calendar day, a non-boolean answer, a blank string) reads as not on\n * record. `programType` is returned as stored (trimmed), not resolved.\n */\nexport function programDetailsOf(raw: unknown): ProgramDetails {\n const r = raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : {};\n return {\n programType: text(r.programType),\n serviceArea: text(r.serviceArea),\n providesRelevantServices:\n typeof r.providesRelevantServices === \"boolean\" ? r.providesRelevantServices : null,\n operatingStartDate: isCalendarDay(r.operatingStartDate) ? r.operatingStartDate : null,\n operatingEndDate: isCalendarDay(r.operatingEndDate) ? r.operatingEndDate : null,\n locationId: text(r.locationId),\n notes: text(r.notes),\n };\n}\n\n// ─── Write rules (plain data and one plain function; no schema library) ─────\n\n/** What kind of value a detail field holds. */\nexport type ProgramDetailKind = \"orgType\" | \"text\" | \"yesNo\" | \"calendarDay\" | \"siteId\";\n\n/** One detail field's write rule. `maxLength` is counted after trimming. */\nexport interface ProgramDetailRule {\n readonly kind: ProgramDetailKind;\n readonly maxLength?: number;\n}\n\n/**\n * The write rule of every detail field. On every field: an ADD may leave the\n * key out (not on record) and may not send `null`; an EDIT may leave the key\n * out (unchanged) or send `null` (clear the field). Text is trimmed and may\n * not be blank.\n */\nexport const PROGRAM_DETAIL_RULES: Readonly<Record<ProgramDetailKey, ProgramDetailRule>> =\n Object.freeze({\n programType: Object.freeze({ kind: \"orgType\" }),\n serviceArea: Object.freeze({ kind: \"text\", maxLength: PROGRAM_SERVICE_AREA_MAX }),\n providesRelevantServices: Object.freeze({ kind: \"yesNo\" }),\n operatingStartDate: Object.freeze({ kind: \"calendarDay\" }),\n operatingEndDate: Object.freeze({ kind: \"calendarDay\" }),\n locationId: Object.freeze({ kind: \"siteId\", maxLength: PROGRAM_LOCATION_ID_MAX }),\n notes: Object.freeze({ kind: \"text\", maxLength: PROGRAM_NOTES_MAX }),\n } as const);\n\n/** `create`: a program ADD. `patch`: a program EDIT, where `null` clears. */\nexport type ProgramDetailsWriteMode = \"create\" | \"patch\";\n\nexport type ProgramDetailErrorCode =\n | \"null_on_create\"\n | \"wrong_kind\"\n | \"blank\"\n | \"too_long\"\n | \"not_a_calendar_day\"\n | \"type_not_offered\";\n\n/** One refused field of a program write. */\nexport interface ProgramDetailError {\n readonly field: ProgramDetailKey;\n readonly code: ProgramDetailErrorCode;\n readonly message: string;\n}\n\n/**\n * The cleaned detail fields of a write: ONLY the keys the body carried. An\n * absent key is not written. `null` (an edit only) clears the field.\n */\nexport interface ProgramDetailsWrite {\n programType?: string | null;\n serviceArea?: string | null;\n providesRelevantServices?: boolean | null;\n operatingStartDate?: string | null;\n operatingEndDate?: string | null;\n locationId?: string | null;\n notes?: string | null;\n}\n\nexport interface ProgramDetailsCheckOptions {\n readonly mode: ProgramDetailsWriteMode;\n /**\n * The caller's rule for an offered organization type: the key to store, or\n * `null` when the value is not a type a person may choose. Required, because\n * this subpath does not import the codebook (the Platform passes its\n * `offeredWriteKey`).\n */\n readonly programType: (value: unknown) => string | null | undefined;\n}\n\nexport type ProgramDetailsCheck =\n | { readonly ok: true; readonly details: ProgramDetailsWrite }\n | { readonly ok: false; readonly errors: readonly ProgramDetailError[] };\n\nconst MESSAGES: Readonly<Record<ProgramDetailErrorCode, string>> = Object.freeze({\n null_on_create: \"Leave the field out when there is nothing to record.\",\n wrong_kind: \"That value is not the right kind for this field.\",\n blank: \"Leave the field out, or clear it, rather than sending it blank.\",\n too_long: \"That text is too long for this field.\",\n not_a_calendar_day: \"A date is a calendar day, YYYY-MM-DD.\",\n type_not_offered: \"That is not a program type a person can choose.\",\n});\n\n/**\n * Check and clean the detail fields of a program write body. Reads only the\n * seven detail keys; any other key of the body is the caller's to judge.\n *\n * Returns the cleaned details (text trimmed, the type as the key to store), or\n * EVERY refused field, never just the first. A key whose value is `undefined`\n * counts as absent.\n */\nexport function checkProgramDetails(\n body: unknown,\n options: ProgramDetailsCheckOptions,\n): ProgramDetailsCheck {\n const b = body && typeof body === \"object\" ? (body as Record<string, unknown>) : {};\n const details: Record<string, string | boolean | null> = {};\n const errors: ProgramDetailError[] = [];\n const refuse = (field: ProgramDetailKey, code: ProgramDetailErrorCode): void => {\n errors.push({ field, code, message: MESSAGES[code] });\n };\n\n for (const field of PROGRAM_DETAIL_KEYS) {\n const v = b[field];\n if (v === undefined) continue;\n if (v === null) {\n if (options.mode === \"patch\") details[field] = null;\n else refuse(field, \"null_on_create\");\n continue;\n }\n const rule = PROGRAM_DETAIL_RULES[field];\n if (rule.kind === \"yesNo\") {\n if (typeof v === \"boolean\") details[field] = v;\n else refuse(field, \"wrong_kind\");\n } else if (rule.kind === \"orgType\") {\n const key = options.programType(v);\n if (typeof key === \"string\" && key !== \"\") details[field] = key;\n else refuse(field, \"type_not_offered\");\n } else if (typeof v !== \"string\") {\n refuse(field, \"wrong_kind\");\n } else if (rule.kind === \"calendarDay\") {\n if (isCalendarDay(v)) details[field] = v;\n else refuse(field, \"not_a_calendar_day\");\n } else {\n const t = v.trim();\n if (t === \"\") refuse(field, \"blank\");\n else if (rule.maxLength !== undefined && t.length > rule.maxLength) refuse(field, \"too_long\");\n else details[field] = t;\n }\n }\n\n return errors.length > 0\n ? { ok: false, errors }\n : { ok: true, details: details as ProgramDetailsWrite };\n}\n","/**\n * Read rules for the platform-db org directory: which row shape a document\n * is, when an organization is an agency's OWN record, and the normalised read\n * view every app shares. Pure: no mongoose, no driver.\n *\n * Contract: platform `docs/ORG_DIRECTORY_CONTRACT.md`.\n */\n\nimport { OrganizationProgramRowSchema, type OrganizationProgramRow } from \"./schemas.js\";\nimport { isListedOrganization, isOrgKey, type OrgReviewStatus } from \"./orgRecord.js\";\nimport { programDetailsOf, type ProgramDetails } from \"./programDetails.js\";\nimport { isLiveOrganizationProgram, isProgramReviewStatus } from \"./vocabulary.js\";\n\n/** A driver ObjectId, or anything that prints itself as one. */\nexport interface ObjectIdLike {\n toHexString(): string;\n}\n\n/** An id's comparable string form: an ObjectId's hex, a string as-is, else null. */\nexport function directoryIdString(value: unknown): string | null {\n if (typeof value === \"string\") return value === \"\" ? null : value;\n if (\n value &&\n typeof value === \"object\" &&\n typeof (value as ObjectIdLike).toHexString === \"function\"\n ) {\n return (value as ObjectIdLike).toHexString();\n }\n return null;\n}\n\n/** Two ids name the same row (string vs ObjectId of one hex are the same). Absent is never a match. */\nexport function sameDirectoryId(a: unknown, b: unknown): boolean {\n const x = directoryIdString(a);\n const y = directoryIdString(b);\n return x !== null && y !== null && x.toLowerCase() === y.toLowerCase();\n}\n\n/**\n * Which writer's shape a stored `organizations` row has.\n *\n * - `canonical`: auth / Thread's global singletons (Unknown, Anonymous), marked by `canonicalKey`.\n * - `pave`: PAVE 2.0's legacy own shape (`packages/db/src/models/organization.ts`\n * before pl-958): a string `id`, `acronym`, `location`. Any ONE of the three\n * marks it.\n * - `thread`: the shared Thread / auth / Platform / PAVE (pl-958) shape: a\n * `type` in either stored form — the IC-58 Int (legacy) or a non-empty string\n * (the CVC-48 key). Whether the value is a VALID type is not this rule's\n * question (the subpath stays SOT-free); readers resolve it.\n * - `unknown`: none of the above (no type, `type: null`, an empty string —\n * e.g. the Platform's account rows).\n *\n * The FORM of `type` never decides `pave`: `organizations.type` is moving from\n * the IC-58 Int to the CVC-48 key on every shared row (auth's provisioning\n * writes the key; the `migrate:org-type-keys` script rewrites the rest), so a\n * key string is a shared-shape row. On platform-prod / platform-dev\n * (2026-10-16) every PAVE-shape row carries all three markers and no\n * Thread / auth / canonical row carries any of them.\n */\nexport type OrganizationRowShape = \"canonical\" | \"pave\" | \"thread\" | \"unknown\";\n\nexport function organizationRowShape(raw: unknown): OrganizationRowShape {\n if (!raw || typeof raw !== \"object\") return \"unknown\";\n const r = raw as Record<string, unknown>;\n if (typeof r.canonicalKey === \"string\" && r.canonicalKey !== \"\") return \"canonical\";\n if (typeof r.id === \"string\" || \"acronym\" in r || \"location\" in r) return \"pave\";\n if (typeof r.type === \"number\" || (typeof r.type === \"string\" && r.type.trim() !== \"\")) {\n return \"thread\";\n }\n return \"unknown\";\n}\n\n/**\n * Whether `org` is `agency`'s OWN organization record: both halves of the pair\n * auth's `ensureOrganizationForAgency` writes hold — `org.agencyId` names the\n * agency AND `agency.organizationId` names the org. Neither half alone counts;\n * `agencyScope` (tenancy) never counts.\n */\nexport function isAgencyOwnOrganization(\n org: { _id?: unknown; agencyId?: unknown } | null | undefined,\n agency: { _id?: unknown; organizationId?: unknown } | null | undefined,\n): boolean {\n if (!org || !agency) return false;\n return (\n sameDirectoryId(org.agencyId, agency._id) && sameDirectoryId(agency.organizationId, org._id)\n );\n}\n\n/**\n * One program as readers see it. Since 0.76.0 it carries the Program record's\n * own fields ({@link ProgramDetails}: kind, service area, direct services,\n * operating dates, site, notes), `null` where nothing is on record.\n * `programType` is the stored string; resolve it with `resolveOrgTypeKey`\n * (this subpath stays free of the codebook).\n */\nexport interface DirectoryProgramView extends ProgramDetails {\n programId: string;\n name: string;\n description: string | null;\n status: string | null;\n reviewStatus: OrganizationProgramRow[\"reviewStatus\"] | null;\n addedBy: string | null;\n addedInApp: string | null;\n /** Offered in pickers: not retired, not rejected. */\n live: boolean;\n}\n\n/** One program row as readers see it, or null when it fails the row schema. */\nexport function toDirectoryProgramView(raw: unknown): DirectoryProgramView | null {\n const parsed = OrganizationProgramRowSchema.safeParse(raw);\n if (!parsed.success) return null;\n const p = parsed.data;\n return {\n programId: p.programId,\n name: p.name,\n description: p.description ?? null,\n status: p.status ?? null,\n reviewStatus: p.reviewStatus ?? null,\n addedBy: p.addedBy ?? null,\n addedInApp: p.addedInApp ?? null,\n live: isLiveOrganizationProgram(p),\n ...programDetailsOf(p),\n };\n}\n\nexport interface DirectoryOrganizationView {\n /** `String(_id)`: the id listings and sharing settings key on. */\n id: string;\n shape: OrganizationRowShape;\n name: string;\n /** The stored `type` when it is a number (the legacy IC-58 Int), else null. */\n type: number | null;\n /**\n * The stored `type` when it is a string, else null: a CVC-48\n * `referral_entity_category` key on a shared-shape row once it is migrated\n * (or written by auth's provisioning), and on a legacy PAVE-shape row.\n */\n typeKey: string | null;\n /** PAVE's own string `id` on a PAVE-shape row, else null. */\n paveId: string | null;\n community: string | null;\n /** auth's identity half; see {@link isAgencyOwnOrganization}. */\n agencyId: string | null;\n /** Tenancy scope. Never an identity. */\n agencyScope: string | null;\n canonicalKey: string | null;\n // ── The Org record (`orgRecord.ts`); null = not captured ──\n /** The Org's identifier (the UDD `id`): the same in every database. Null on a row not yet given one. */\n key: string | null;\n legalName: string | null;\n commonName: string | null;\n /**\n * The curated short name (the UDD `acronym`): the stored `shortName`, else a\n * legacy PAVE-shape row's `acronym`. Never derived from the name here.\n */\n shortName: string | null;\n website: string | null;\n /** The organization this one is a unit of. */\n parentOrgId: string | null;\n /** HMIS VSP step 1. Tri-state: null = never captured. */\n vsp: boolean | null;\n /** HMIS VSP step 2. Null unless `vsp` is true. */\n vspPrivateNonprofit: boolean | null;\n /** pending · confirmed · rejected for an organization added inside an app; null on a steward row. */\n reviewStatus: OrgReviewStatus | null;\n addedInApp: string | null;\n /** Who added it (a platform `users._id`); a pre-0.60 row's `addedByUserId` reads here too. */\n addedBy: string | null;\n addedInSession: string | null;\n /** The stored lifecycle code (1 active, 2 inactive), else null. */\n status: number | null;\n /** Offered in pickers: active and not declined (`isListedOrganization`). */\n listed: boolean;\n programs: DirectoryProgramView[];\n /** Program rows that failed the row schema (not returned). */\n invalidPrograms: number;\n}\n\nconst text = (v: unknown): string | null => (typeof v === \"string\" && v !== \"\" ? v : null);\nconst line = (v: unknown): string | null => (typeof v === \"string\" && v.trim() !== \"\" ? v.trim() : null);\nconst flag = (v: unknown): boolean | null => (typeof v === \"boolean\" ? v : null);\n\n/** Normalise a stored row of any writer's shape into the shared read view. */\nexport function toDirectoryOrganizationView(raw: unknown): DirectoryOrganizationView | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const id = directoryIdString(r._id);\n if (!id) return null;\n const rows = Array.isArray(r.programs) ? r.programs : [];\n const programs = rows\n .map(toDirectoryProgramView)\n .filter((p): p is DirectoryProgramView => p !== null);\n const vsp = flag(r.vsp);\n const reviewStatus = isProgramReviewStatus(r.reviewStatus) ? r.reviewStatus : null;\n const status = typeof r.status === \"number\" ? r.status : null;\n return {\n id,\n shape: organizationRowShape(r),\n name: text(r.name) ?? \"\",\n type: typeof r.type === \"number\" ? r.type : null,\n typeKey: typeof r.type === \"string\" ? r.type : null,\n paveId: text(r.id),\n community: text(r.community),\n agencyId: directoryIdString(r.agencyId),\n agencyScope: directoryIdString(r.agencyScope),\n canonicalKey: text(r.canonicalKey),\n key: isOrgKey(r.key) ? r.key : null,\n legalName: line(r.legalName),\n commonName: line(r.commonName),\n shortName: line(r.shortName) ?? line(r.acronym),\n website: line(r.website),\n parentOrgId: directoryIdString(r.parentOrgId),\n vsp,\n vspPrivateNonprofit: vsp === true ? flag(r.vspPrivateNonprofit) : null,\n reviewStatus,\n addedInApp: line(r.addedInApp),\n addedBy: line(r.addedBy) ?? line(r.addedByUserId),\n addedInSession: line(r.addedInSession),\n status,\n listed: isListedOrganization({ status, reviewStatus }),\n programs,\n invalidPrograms: rows.length - programs.length,\n };\n}\n","/**\n * The raw-driver reads of the platform-db org directory. No driver import: the\n * readers take any object with the MongoDB driver's\n * `collection(name).findOne(filter, options)` shape, plus a `toObjectId`\n * factory so a 24-hex string id also matches a row stored under an ObjectId\n * (production `organizations._id` and `agencies._id` are ObjectIds).\n */\n\nimport {\n isAgencyOwnOrganization,\n toDirectoryOrganizationView,\n type DirectoryOrganizationView,\n type ObjectIdLike,\n} from \"./rules.js\";\n\nexport const ORGANIZATIONS_COLLECTION = \"organizations\";\nexport const AGENCIES_COLLECTION = \"agencies\";\n\nexport interface OrgDirectoryDbLike {\n collection(name: string): {\n findOne(filter: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;\n };\n}\n\nexport interface OrgDirectoryReadOptions {\n /** Build the driver's ObjectId from 24-hex (e.g. `(h) => new ObjectId(h)`). */\n toObjectId?: (hex: string) => unknown;\n}\n\nconst HEX = /^[0-9a-fA-F]{24}$/;\n\n/** Every stored form of one id: the string, and its ObjectId when 24-hex. */\nexport function organizationIdForms(\n id: string | ObjectIdLike,\n opts: OrgDirectoryReadOptions = {},\n): unknown[] {\n if (typeof id !== \"string\") return [id.toHexString(), id];\n return HEX.test(id) && opts.toObjectId ? [id, opts.toObjectId(id.toLowerCase())] : [id];\n}\n\n/** One organization in the shared view, or null. Read errors propagate. */\nexport async function readDirectoryOrganization(\n db: OrgDirectoryDbLike,\n id: string | ObjectIdLike,\n opts: OrgDirectoryReadOptions = {},\n): Promise<DirectoryOrganizationView | null> {\n const raw = await db\n .collection(ORGANIZATIONS_COLLECTION)\n .findOne({ _id: { $in: organizationIdForms(id, opts) } });\n return raw ? toDirectoryOrganizationView(raw) : null;\n}\n\n/**\n * An agency's OWN organization (both halves of the pair hold), or null — never\n * an organization the agency merely scopes (`agencyScope`) or that points at it\n * from one side only. The agency is looked up by `_id`.\n */\nexport async function readAgencyOwnOrganization(\n db: OrgDirectoryDbLike,\n agencyId: string | ObjectIdLike,\n opts: OrgDirectoryReadOptions = {},\n): Promise<DirectoryOrganizationView | null> {\n const agency = (await db\n .collection(AGENCIES_COLLECTION)\n .findOne(\n { _id: { $in: organizationIdForms(agencyId, opts) } },\n { projection: { _id: 1, organizationId: 1 } },\n )) as { _id?: unknown; organizationId?: unknown } | null;\n if (!agency || agency.organizationId == null) return null;\n const pointer = agency.organizationId as string | ObjectIdLike;\n const org = (await db\n .collection(ORGANIZATIONS_COLLECTION)\n .findOne({ _id: { $in: organizationIdForms(pointer, opts) } })) as {\n _id?: unknown;\n agencyId?: unknown;\n } | null;\n return org && isAgencyOwnOrganization(org, agency) ? toDirectoryOrganizationView(org) : null;\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,QAAU;AAAA,EACV,MAAQ;AAAA,EACR,SAAW;AAAA,EACX,SAAW;AAAA,E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W,MAAM,YAAY;AACnC,MAAI,UAAU,SAAS,mBAAmB;AACxC,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,MAAI,SAAU,QAAO,QAAQ,SAAS,KAAK,KAAK;AAEhD,QAAM,SAAS,MAAM,iBAAiB,IAAI,OAAO,OAAO;AACxD,MAAI,OAAQ,QAAO;AAEnB,QAAM,IAAI,MAAM,mBAAmB,IAAI;AAAA,IACrC,IAAI,IAAI,MAAM;AAAA,IACd;AAAA,IACA;AAAA,IACA,KAAK,KAAK;AAAA,IACV;AAAA,IACA,KAAK,KAAK,OAAO,oBAAI,KAAK;AAAA,EAC5B,CAAC;AACD,MAAI,CAAC,EAAE,IAAI;AACT,QAAI,EAAE,WAAW,wBAAyB,QAAO;AAEjD,UAAM,QAAQ,MAAM,YAAY;AAChC,WAAO,SAAS,MAAM,SAAS,oBAAoB,QAAQ,MAAM,KAAK,KAAK,IAAI;AAAA,EACjF;AACA,QAAM,UAAU,MAAM,mBAAmB,IAAI,OAAO,SAAS,EAAE,MAAM,EAAE;AACvE,MAAI,QAAS,QAAO;AACpB,SAAO,QAAQ,EAAE,OAAO,IAAI;AAC9B;","names":["import_zod","import_zod","import_zod","text","text","line","HEX_24"]}
|
|
1
|
+
{"version":3,"sources":["../../src/pointsOfContact/index.ts","../../src/cvcs/preferredContactMethod.v1.1.0.json","../../src/pointsOfContact/vocabulary.ts","../../src/pointsOfContact/schemas.ts","../../src/pointsOfContact/readRules.ts","../../src/pointsOfContact/reader.ts","../../src/pointsOfContact/writer.ts","../../src/orgDirectory/schemas.ts","../../src/orgDirectory/vocabulary.ts","../../src/orgDirectory/orgRecord.ts","../../src/orgDirectory/programDetails.ts","../../src/orgDirectory/rules.ts","../../src/orgDirectory/read.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models/points-of-contact\n *\n * The Point of contact contract (pl-3r8): the platform-db `pointsofcontact`\n * collection's vocabularies, Zod schemas, stored and view types, read rules\n * (network vs owner view, confidential exclusion, the Referrals (magic link)\n * partner rollup with its confidential-holder count and send-only\n * `resolveMagicLinkRecipients` / `ConfidentialReferralRecipients`, pl-iza)\n * and raw-driver reads, plus the ONE shared writer every app\n * runs: the in-app partner add (`mintPartnerContact`, pl-bt1) and the index\n * set it relies on (`ensurePocIndexes`). Pure TypeScript, no mongoose, no\n * driver import. The platform app owns every other write (its own Admin Hub,\n * survey, edits, confirm, seed: `platform lib/points-of-contact/`); Thread,\n * PAVE and LEADS read through this module and write a pending in-app add\n * through it directly, without an HTTP hop. Subpath only (not re-exported from\n * the package root).\n */\n\nexport * from \"./vocabulary.js\";\nexport * from \"./schemas.js\";\nexport * from \"./readRules.js\";\nexport * from \"./reader.js\";\nexport * from \"./writer.js\";\n","{\n \"domain\": \"preferred_contact_method\",\n \"name\": \"Core Preferred Contact Method\",\n \"version\": \"1.1.0\",\n \"_status\": \"CANONICAL -- Notion CVC-185 `core-preferred_contact_method` v1.1 (IC-2 Contact Info). Page Status in the canon capture at generation: 'Active'; yaml mirror `vocab_status: canonical`. Exported from prototype canon @ a5ecd452. WHAT IT IS: the PERSON-level routing preference -- which channel a person prefers to be reached on, when it is safe. A preference is not permission: it never overrides a contact entry's safety flags. The Agency Hub reuses a declared subset (Email, Call, Text) for an agency contact's time-sensitive channels. TWO LABEL REGISTERS per entry, both from canon: `title` is the word the apps render (yaml `display_name`); `codebookLabel` is the Notion codebook Label (yaml `codebook_label`). Where they differ the divergence is declared in canon. Show `title` in UI. STORAGE: the package key and the positional code are FROZEN at first publication (2026-04-22) because apps store them; `canonicalCode` is canon's UPPER_SNAKE code. APP keeps the key `messaging_app_dm` (its pre-2026-09-01 code name, which canon keeps as a legacy alias). `legacyValueMap` maps an inbound spelling (lower-cased) to the canonical code. LEVEL 0 NOT MIRRORED: canon also defines UNK, ANON and DNC; no picker offers them (UNK and ANON arrive through decline affordances, DNC is system-stamped) and they are left out of this version so no consumer key tuple changes. Wording is verbatim from the Notion codebook capture and the yaml mirror. Generated by scripts/gen-preferred-contact-method.py -- do not hand-edit.\",\n \"_source\": \"htilabstech/prototype/data/cvcs/core_preferred_contact_method.yaml @ a5ecd452 (read from origin/main) + htilabstech/prototype/Final CVCs/Contact Info (IC-2)/core-preferred_contact_method — codebook.csv + htilabstech/prototype/Final CVCs/Contact Info (IC-2)/core-preferred_contact_method.md @ a5ecd452 (CVC-185 v1.1)\",\n \"levels\": {\n \"1\": \"Contact method\"\n },\n \"legacyValueMap\": {\n \"app\": \"APP\",\n \"call\": \"CALL\",\n \"email\": \"EMAIL\",\n \"messaging_app_dm\": \"APP\",\n \"text\": \"TEXT\"\n },\n \"pickers\": {\n \"pave_contact_info_prefs_bar\": [\n \"TEXT\",\n \"CALL\",\n \"EMAIL\",\n \"APP\"\n ],\n \"leads_contact_info_prefs_bar\": [\n \"TEXT\",\n \"CALL\",\n \"EMAIL\",\n \"APP\"\n ],\n \"platform_agency_hub_urgent_methods\": [\n \"EMAIL\",\n \"CALL\",\n \"TEXT\"\n ]\n },\n \"pickerExclusions\": {\n \"platform_agency_hub_urgent_methods\": {\n \"APP\": \"An agency contact is reached at work, through channels the agency controls and can hand over when someone leaves. A personal messaging-app or social DM is neither, so the Agency Hub does not offer it. Excluded deliberately at the 2026-09-01 transition, not an oversight — if an agency ever asks for it, add APP here rather than minting an agency-side code.\"\n }\n },\n \"entries\": [\n {\n \"code\": \"185-001-000-000-000-000-000\",\n \"key\": \"call\",\n \"title\": \"Call\",\n \"codebookLabel\": \"Call (voice)\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be contacted by phone call when safe and appropriate.\",\n \"canonicalCode\": \"CALL\",\n \"guidance\": \"Person-level preference only. Requires at least one phone entry that is safe to contact by call (and, if applicable, voicemail rules captured at entry level).\",\n \"logicNotes\": \"If no safe phone entry exists, warn and prompt to add/update a safe phone method or remove this preference.\\n\\nThe CALL warning is phone-only and requires safe_to_call: a non-phone entry never satisfies it, whatever its safety flags. safe_to_call is canonical-by-CVC despite IC-2 § 2 enumerating only safe_to_text + safe_to_leave_voicemail (Data-2 codification, 2026-05-26) — do not retire it to \\\"align to the IC\\\".\\n\\nCode canonicalized to UPPERCASE CALL on 2026-09-01 (CVC185-AUDIT). Legacy lowercase call normalizes to CALL on read.\"\n },\n {\n \"code\": \"185-002-000-000-000-000-000\",\n \"key\": \"text\",\n \"title\": \"Text\",\n \"codebookLabel\": \"Text (SMS)\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be contacted via text message (SMS) when safe and appropriate.\",\n \"canonicalCode\": \"TEXT\",\n \"guidance\": \"Requires a phone/contact entry that explicitly supports safe-to-text. Do not infer texting safety from general ‘safe to contact’.\",\n \"logicNotes\": \"If selected but no contact entry has safe_to_text=true, warn and offer quick fix: remove preference or update contact method safety flags.\\n\\nCode canonicalized to UPPERCASE TEXT on 2026-09-01 (CVC185-AUDIT). Both PAVE and LEADS have stored the UPPERCASE form since 2026-05-26; the lowercase form on this page had never been consumed by either app. Legacy lowercase text is accepted on read by canonicalizePrefMethod (monolith) and normalizes to TEXT.\"\n },\n {\n \"code\": \"185-003-000-000-000-000-000\",\n \"key\": \"email\",\n \"title\": \"Email\",\n \"codebookLabel\": \"Email\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be contacted via email when safe and appropriate.\",\n \"canonicalCode\": \"EMAIL\",\n \"guidance\": \"Use as a person-level routing preference (not an instruction to use an unsafe email address). Pair with contact-entry safety flags; if no safe email exists, prompt user to update contact info or adjust preference.\",\n \"logicNotes\": \"Does not override entry-level safety constraints. If selected but no safe email entry exists, warn: \\\"No safe contact method supports 'Email'.\\\"\\n\\nCode canonicalized to UPPERCASE EMAIL on 2026-09-01 (CVC185-AUDIT). Legacy lowercase email normalizes to EMAIL on read.\"\n },\n {\n \"code\": \"185-004-000-000-000-000-000\",\n \"key\": \"messaging_app_dm\",\n \"title\": \"Messaging app\",\n \"codebookLabel\": \"Messaging app DM\",\n \"selectable\": true,\n \"parentCode\": null,\n \"childCodes\": [],\n \"definition\": \"Person prefers to be reached by direct message on an app or platform — messaging apps (WhatsApp, Signal, Telegram, Kik) AND social-media DMs (Instagram, Snapchat, Facebook, X) alike — when safe and appropriate.\",\n \"canonicalCode\": \"APP\",\n \"guidance\": \"ONE routing bucket for \\\"DM me somewhere\\\", not a per-brand choice. Requires at least one app OR social-media contact entry that is safe to use. The specific platform is captured at the contact-entry level (type + domain), never here.\\n\\nRULING R2 (Ava, 2026-09-01, CVC185-AUDIT): an Instagram / Snapchat / Facebook DM satisfies this preference exactly as WhatsApp or Signal does. The contact-TYPE taxonomy (CVC-149) keeps App and Social Media as separate kinds; this person-level ROUTING preference deliberately collapses both. Do not split this into two values, and do not narrow it to messaging apps only — the routing question is the channel, not the brand.\",\n \"logicNotes\": \"Warning fires when no entry on file has type IN (app, social) AND safety=safe AND NOT do_not_contact. Both shipped implementations already test the union — monolith renderPrefBar and leads-app prefWarnings — so R2 documents shipped behaviour rather than changing it.\\n\\nCode canonicalized to APP on 2026-09-01 (CVC185-AUDIT), replacing messaging_app_dm. Two reasons: both apps have stored APP since 2026-05-26 and nothing has ever stored messaging_app_dm; and under R2 the value covers social-media DMs too, which the old code name contradicted on its face. Legacy messaging_app_dm and lowercase app both normalize to APP on read.\\n\\nAPP LABEL DIVERGENCE (declared, not drift): this codebook and IC-2 § III.3 render the label \\\"Messaging app DM\\\"; both apps render the chip as \\\"Messaging app\\\". The stored code is identical; only the presentational string differs.\"\n }\n ]\n}\n","/**\n * Point of contact vocabularies (pl-3r8): subject types, purposes, urgent\n * methods, review status and writers. Defined once here; every reader and the\n * platform writer import them.\n *\n * ## Purposes are a declared list, NOT a CVC (a CVC is owed)\n *\n * No `core-contact_purpose` CVC exists in this package. The eight codes below\n * are copied verbatim from the prototype's declared list,\n * `data/contact_purposes.yaml` @ prototype 6c2db859 (L11-L33), which states\n * \"NOT YET A CVC — minting `core-contact_purpose` is an open line for\n * Crysta\". The Notion profile (UDD — Objects \"Point of Contact Data Object\",\n * 3ec1ef14abcd81dc9a47ec37e217adc3, § 6 q2) leaves it a list \"until the sharing\n * work says whether anything routes on a purpose\". `REFERRALS_MAGIC_LINK` now\n * routes (Crysta 2026-10-14, Slack D0811D2R6QN p1792036474007189), so the mint\n * question is live. When the CVC lands, this list is replaced by it.\n *\n * The first five are the agency purposes (Crysta 2026-08-23: one contacts\n * list; Compliance · Training · Referrals (magic link) · Billing · Data &\n * reporting). The last three are program-level (Crysta 2026-10-14: \"plus\n * Program contact · Referral contact · Program Director at program level\").\n *\n * ## Urgent methods are CVC-185\n *\n * `urgent_methods` stores CVC-185 `preferred_contact_method` CODES, restricted\n * to the Agency Hub subset (email · call · text). Canon: platform-prototype\n * `src/agencyhub.jsx` @ 0fa04c1 L7937-L7963 (the declared\n * `platform_agency_hub_urgent_methods` subset omits the messaging-app DM) and\n * the prototype generator's gate (`tools/build_platform_directory.py` @\n * 6c2db859 L2577-L2580). Codes are read from the package SOT, never typed, and\n * a code the SOT marks `selectable: false` is refused.\n */\n\nimport preferredContactMethodSot from \"../cvcs/preferredContactMethod.v1.1.0.json\" with { type: \"json\" };\nimport type { PreferredContactMethodKey } from \"../generated/cvc-enums.js\";\n\n// ─── Subjects ────────────────────────────────────────────────────────\n\n/**\n * What a contact is FOR. Crysta 2026-10-14: \"a reachable person for a subject\n * (agency, program, team, site)\". `org` is added (decision D2, veto-able) for\n * a partner that exists only as an organization: Crysta's ruling that an\n * in-app add \"creates the organization and a contact\", canon `hubSavePocs`\n * stamping an empty `agency_id` when it has none (platform-prototype\n * `src/agencyhub.jsx` @ 0fa04c1 L411), and the Notion draft's proposed `org`\n * subject (§ 5). `account` is not accepted.\n *\n * ## `location` is stored; \"Site\" is displayed (pl-f4c, 0.30.0)\n *\n * The UDD names the object Site (since 2026-10-04), but its stored names, ids\n * and columns stay `location`: the schema of record is hti-features\n * `udd-schemas/location/Location.v1.json`, and the POC draft enum is\n * `agency | program | location | team`. Canon stores `location` everywhere:\n * the POC directory columns (prototype\n * `docs/leads-platform/ORG_STACK_DATA_OBJECTS_2026-10-01.md` @ fa0fd0b0 L236,\n * \"subject_type (agency · program · location · team)\"), the registry kind\n * (`leads-app/server/models/RegistryEntities.mjs` @ fa0fd0b0 L105-L117) and\n * the object-log subject enum (`leads-app/server/models/ObjectDirectoryEntry.mjs`\n * @ fa0fd0b0 L51). So the stored value is `location` and the display word is\n * {@link pocSubjectTypeLabel}'s \"Site\". 0.28.0 stored `site`; there is no prod\n * data, so `site` is simply refused (no legacy acceptance, no migration).\n *\n * `service` is a Service Listing's contact (Crysta's kickoff D4, prototype\n * `KICKOFF_SERVICE_LISTING_AND_PARTNER_CONTACT_BUILD_2026-10-14.md` @ c6380f73\n * L15: \"the listing contact is a Point of contact row (`subject_type:\n * service`, profile § 6 q3, confirmed)\"); `subject_id` is the listing id.\n *\n * An in-app add's contact sits on the partner's agency when the org has one\n * (kickoff D1, L12: \"`subject_type: agency` when the org has an agency row,\n * else the org\"); the platform writer rewrites an `org` subject whose org\n * genuinely mirrors an agency to that agency.\n */\nexport const POC_SUBJECT_TYPES = [\"agency\", \"org\", \"program\", \"team\", \"location\", \"service\"] as const;\nexport type PocSubjectType = (typeof POC_SUBJECT_TYPES)[number];\n\n/**\n * The display word for each subject type: the object names of prototype\n * `docs/leads-platform/ORG_STACK_DATA_OBJECTS_2026-10-01.md` @ fa0fd0b0 § 1\n * (L60-L68: Org · Agency · Program / department · Team · Service listing),\n * with `location` shown as \"Site\", the UDD's object name since 2026-10-04\n * (pl-f4c). Store the code, render the label.\n */\nexport const POC_SUBJECT_TYPE_LABELS: Readonly<Record<PocSubjectType, string>> = {\n agency: \"Agency\",\n org: \"Org\",\n program: \"Program\",\n team: \"Team\",\n location: \"Site\",\n service: \"Service listing\",\n};\n\n/** The display word of a subject type; an unknown type reads as itself. */\nexport function pocSubjectTypeLabel(type: string): string {\n return Object.hasOwn(POC_SUBJECT_TYPE_LABELS, type)\n ? POC_SUBJECT_TYPE_LABELS[type as PocSubjectType]\n : type;\n}\n\n// ─── Purposes ────────────────────────────────────────────────────────\n\n/** The declared purpose codes (prototype `data/contact_purposes.yaml` @ 6c2db859 L11-L33). */\nexport const CONTACT_PURPOSE_CODES = [\n \"COMPLIANCE\",\n \"TRAINING\",\n \"REFERRALS_MAGIC_LINK\",\n \"BILLING\",\n \"DATA_REPORTING\",\n \"PROGRAM_CONTACT\",\n \"REFERRAL_CONTACT\",\n \"DIRECTOR\",\n] as const;\nexport type ContactPurposeCode = (typeof CONTACT_PURPOSE_CODES)[number];\n\nexport interface ContactPurpose {\n readonly code: ContactPurposeCode;\n readonly label: string;\n /**\n * Where the prototype offers it: the agency contacts list, or a program's\n * contact slots (Crysta 2026-10-14: \"at program level\"). Informational: no\n * subject is refused a purpose (canon does not enforce it; open question).\n */\n readonly level: \"agency\" | \"program\";\n}\n\n/** The declared purpose list with labels. */\nexport const CONTACT_PURPOSES: readonly ContactPurpose[] = [\n { code: \"COMPLIANCE\", label: \"Compliance\", level: \"agency\" },\n { code: \"TRAINING\", label: \"Training\", level: \"agency\" },\n { code: \"REFERRALS_MAGIC_LINK\", label: \"Referrals (magic link)\", level: \"agency\" },\n { code: \"BILLING\", label: \"Billing\", level: \"agency\" },\n { code: \"DATA_REPORTING\", label: \"Data & reporting\", level: \"agency\" },\n { code: \"PROGRAM_CONTACT\", label: \"Program contact\", level: \"program\" },\n { code: \"REFERRAL_CONTACT\", label: \"Referral contact\", level: \"program\" },\n { code: \"DIRECTOR\", label: \"Program Director\", level: \"program\" },\n];\n\n/**\n * The magic-link purpose. A magic link goes to EVERY contact on the partner\n * carrying it (Crysta 2026-08-23, restated 2026-10-14), and a contact carrying\n * it must have an email (Crysta 2026-10-14, the Admin Hub editor rule). CVC-338\n * (prototype `data/cvcs/core_contact_purpose.yaml` @ 184893b6 L95): \"A\n * confidential holder still receives it; the sender never sees the address.\"\n * (pl-iza: `resolveMagicLinkRecipients`, `ConfidentialReferralRecipients`.)\n */\nexport const REFERRALS_MAGIC_LINK_PURPOSE: ContactPurposeCode = \"REFERRALS_MAGIC_LINK\";\n\nconst PURPOSE_BY_CODE = new Map<string, ContactPurpose>(CONTACT_PURPOSES.map((p) => [p.code, p]));\n\nexport function isContactPurposeCode(code: unknown): code is ContactPurposeCode {\n return typeof code === \"string\" && (CONTACT_PURPOSE_CODES as readonly string[]).includes(code);\n}\n\n/** The display label of a purpose code; an unknown code reads as itself. */\nexport function contactPurposeLabel(code: string): string {\n return PURPOSE_BY_CODE.get(code)?.label ?? code;\n}\n\n// ─── Urgent methods (CVC-185 subset) ─────────────────────────────────\n\n/** The Agency Hub subset of CVC-185, by key. */\nexport const POC_URGENT_METHOD_KEYS = [\"email\", \"call\", \"text\"] as const satisfies readonly PreferredContactMethodKey[];\n\nconst CVC185_ENTRIES = preferredContactMethodSot.entries;\n\nfunction cvc185Entry(key: string): (typeof CVC185_ENTRIES)[number] {\n const e = CVC185_ENTRIES.find((x) => x.key === key);\n // A re-mirror that drops one of the subset's keys must fail loudly at load,\n // never silently shrink the vocabulary.\n if (!e) throw new Error(`points-of-contact: CVC-185 preferred_contact_method has no key \"${key}\"`);\n return e;\n}\n\n/** The subset's CVC-185 entries, SOT order preserved by the subset's own order. */\nexport interface PocUrgentMethod {\n key: string;\n code: string;\n title: string;\n selectable: boolean;\n}\n\nexport const POC_URGENT_METHODS: readonly PocUrgentMethod[] =\n POC_URGENT_METHOD_KEYS.map((k) => {\n const e = cvc185Entry(k);\n return { key: e.key, code: e.code, title: e.title, selectable: e.selectable !== false };\n });\n\nconst URGENT_BY_CODE = new Map(POC_URGENT_METHODS.map((m) => [m.code, m]));\n\n/** True for a CVC-185 code in the Agency Hub subset that the SOT marks selectable. */\nexport function isPocUrgentMethodCode(code: unknown): code is string {\n return typeof code === \"string\" && URGENT_BY_CODE.get(code)?.selectable === true;\n}\n\n/** The CVC-185 code for a subset key (`email` · `call` · `text`), else null. */\nexport function pocUrgentMethodCode(key: string): string | null {\n return POC_URGENT_METHODS.find((m) => m.key === key)?.code ?? null;\n}\n\n// ─── Review status, writers ──────────────────────────────────────────\n\n/**\n * `confirmed` = visible platform-wide; `pending` = held for HTI Labs (the\n * steward). Decision D3 (veto-able), from Crysta 2026-10-14: only writer 3,\n * the in-app / steward add, is \"pending … available platform-wide after HTI\n * Labs confirms it\". The survey's Q2 contacts and the agency's own Admin Hub\n * list carry no review gate (canon `hubSavePocs` has no status), so they land\n * `confirmed` with no steward stamp. See {@link pocInitialStatus}.\n */\nexport const POC_STATUSES = [\"pending\", \"confirmed\"] as const;\nexport type PocStatus = (typeof POC_STATUSES)[number];\n\n/**\n * Who wrote the contact. Stored on the row. `steward_seed` is the reviewed\n * import of the prototype directory sheet (pl-cbu).\n */\nexport const POC_ORIGINS = [\"survey\", \"admin_hub\", \"in_app\", \"steward_seed\"] as const;\nexport type PocOrigin = (typeof POC_ORIGINS)[number];\n\n/** Where the contact was entered (null on a seed row). */\nexport const POC_ADDED_IN_APPS = [\"pave\", \"thread\", \"leads\", \"platform\"] as const;\nexport type PocAddedInApp = (typeof POC_ADDED_IN_APPS)[number];\n\n/** The status a writer's new contact starts in (D3). */\nexport function pocInitialStatus(origin: PocOrigin): PocStatus {\n return origin === \"survey\" || origin === \"admin_hub\" ? \"confirmed\" : \"pending\";\n}\n","/**\n * Point of contact schemas and stored types (pl-3r8).\n *\n * A **Point of contact** is a reachable person FOR a subject (agency, org,\n * program, team, location (shown \"Site\"), service listing), for one or more\n * purposes. It is a platform-wide record on platform-db, not something\n * created at first login (Crysta 2026-10-14,\n * Slack D0811D2R6QN p1792036474007189). Columns follow the prototype directory\n * (`Org + Personnel Registry/HTI_POINT_OF_CONTACT_DIRECTORY.csv` @ prototype\n * 6c2db859 L1): `poc_id · subject_type · subject_id · user_id | person_id ·\n * display_name · email · phone · purposes · urgent_methods · is_primary ·\n * is_confidential · active · notes`. `poc_id` is stored as `id` (the\n * hti-features schema's name).\n *\n * ## Emails and phones are lists (pl-e98, 0.30.0)\n *\n * The sheet's single `email` / `phone` columns became `emails[]` / `phones[]`\n * of {@link PocContactEntry} `{ value, is_preferred }`, Crysta's 2026-08-24\n * multi-entry correction. Canon's Admin Hub ledger keeps \"every active email\n * and phone as its own row, one preferred per type\" (platform-prototype\n * `src/agencyhub.jsx` @ 6f428116 L8096-L8106) and stores each as `{type,\n * value, preferred}` (`methodsFor` L8107-L8132, the save L8181); on a Point of\n * contact the type is the list the entry sits in. The flag is named after the\n * CONTACT rail's `is_preferred` (prototype\n * `leads-app/server/models/ObjectDirectoryEntry.mjs` @ fa0fd0b0 L52); the\n * contact-level `is_primary` (the subject's primary contact) is unrelated and\n * unchanged. No per-entry use label: CVC-154 `contact_info_use_type` is\n * investigative-only and offered by no Platform, PAVE or Thread picker\n * (prototype `data/cvcs/core_contact_info_use_type.yaml` @ fa0fd0b0 L93-L97).\n *\n * The single fields are GONE from the stored row and from every writer body\n * (no prod data, clean cut; no read shim for stored single fields). Read the\n * preferred address through {@link preferredEmail} / {@link preferredPhone};\n * every view also carries read-only `email` / `phone` projections of the\n * preferred entries, as canon's card does (L8195-L8202).\n *\n * The preferred rule. A WRITER list ({@link PocEmailListSchema} /\n * {@link PocPhoneListSchema}) holds at most one entry marked `is_preferred`\n * and is normalized to exactly one: the marked entry, else the FIRST (canon\n * L8126-L8129). It refuses the same email twice or the same phone line twice\n * (by digits, canon's `phoneDigits`, prototype\n * `leads-app/server/objectStructuresEngine.generated.mjs` @ fa0fd0b0\n * L282-L286), and a phone with no digit. A phone is stored AS TYPED, trimmed,\n * as this object's canon writer, the Admin Hub ledger, stores it\n * (`agencyhub.jsx` @ 6f428116 L8124-L8125, L8173, L8511-L8518). An extension\n * makes a distinct line: `402-677-3902 x5` and `402-677-3902` differ by\n * digits, so both may sit on one contact. {@link formatPocPhone} is a\n * DISPLAY-only helper readers apply (canon calls `formatPhone` \"display\n * only\", L229-L245). A list in an edit replaces the stored list; `[]` clears\n * it, `null` is refused.\n *\n * A STORED list is READ leniently ({@link PointOfContactDocSchema}): the same\n * normalization repairs it (emails trimmed and lowercased, empty and duplicate\n * entries dropped, a missing or null `is_preferred` read as false, no\n * preferred → the first, several → the first marked), so one row's list\n * never takes down a partner's whole read. Only structurally invalid data\n * (not an array, a non-object entry, a non-string value, a non-boolean flag)\n * throws.\n *\n * ## Known deviations (0.30.0)\n *\n * - A seat-linked contact still reads ONE email and ONE phone from `users`\n * until a person Contact log exists (pl-9h4). Canon's motivating case\n * (Crysta's own seat-linked contact) is therefore not yet met.\n * - An entry is removed, not retired: canon's write-in ledger keeps retired\n * entries stamped `retiredOn` (retire-not-remove, L8181-L8185); this list\n * keeps only the live ones.\n * - The write-in identity key uses the preferred email only\n * ({@link pocIdentityKey}, as canon's `hubSavePocs` L382-L384 uses the card's flat\n * email): changing the preferred email changes `identity_key`, and a\n * secondary email shared with another row is not deduplicated. The writer\n * maps an identity unique-index collision to a domain error (the\n * platform's job).\n *\n * ## Shapes and trust levels\n *\n * - {@link PocOwnerSchema}: WHOSE contact it is. Resolved by the platform\n * route, never read from a request body.\n * - {@link PocDetailsSchema}: what the subject's own writers (survey, Admin\n * Hub) may say about the person. `.strict()`: a body carrying `status`,\n * `origin`, `id`, `active`, a stamp or an owner key is refused.\n * - {@link PocInAppSchema}: what an advocate adding a partner may say: a\n * write-in with a name and an email, no primary / confidential / notes.\n * - {@link PocSeedSchema}: the details plus the sheet's `poc-*` id.\n * - {@link PocPatchSchema}: an edit. Identity (`user_id`, `person_id`) is\n * fixed at mint; a different person is a different contact.\n *\n * ## Whole-contact rules ({@link pocRuleViolations})\n *\n * Checked on a mint and on the MERGED document of an edit:\n * 1. `user_id` XOR `person_id` (prototype generator\n * `tools/build_platform_directory.py` @ 6c2db859 L2556-L2557).\n * 2. A seat-linked contact stores no emails or phones of its own (both\n * lists empty); they resolve from the seat (L2561-L2563; Notion profile\n * § 3 \"A contact's phone and email belong to the person\").\n * 3. A contact that is not seat-linked carries a `display_name` (L2571-L2572).\n * 4. A contact tagged Referrals (magic link) has an email (Crysta\n * 2026-10-14); the magic link goes to its preferred email. For a\n * seat-linked contact the seat must have one; the writer checks the seat.\n */\n\nimport { z } from \"zod\";\n\nimport {\n CONTACT_PURPOSE_CODES,\n POC_ADDED_IN_APPS,\n POC_ORIGINS,\n POC_STATUSES,\n POC_SUBJECT_TYPES,\n REFERRALS_MAGIC_LINK_PURPOSE,\n isPocUrgentMethodCode,\n} from \"./vocabulary.js\";\n\n/**\n * The platform-db collection. The platform writes it; the one exception is the\n * in-app partner add, which every app writes through the shared\n * `mintPartnerContact` (`./writer.ts`).\n */\nexport const POINTS_OF_CONTACT_COLLECTION = \"pointsofcontact\";\n\n/**\n * Index names. `ensurePocIndexes` (`./writer.ts`) creates them, with the\n * in-app pending and review-queue indexes; readers rely on them.\n */\nexport const POINT_OF_CONTACT_INDEXES = {\n /** `{id}` unique. */\n id: \"pointsofcontact_id_unique\",\n /** `{subject_type, subject_id, active}`: contacts for a subject. */\n subject: \"pointsofcontact_subject\",\n /** `{agency_id, purposes, active}`: the partner rollup by agency. */\n agencyPurpose: \"pointsofcontact_agency_purpose\",\n /** `{org_id, purposes, active}`: the partner rollup by org. */\n orgPurpose: \"pointsofcontact_org_purpose\",\n /** `{status}`: the steward's review queue. */\n status: \"pointsofcontact_status\",\n /**\n * `{agency_id, subject_type, subject_id, identity_key}` unique where `active` and\n * `confirmed`: no twin of one person among a subject's visible contacts.\n * Pending duplicates are the steward's call, so a stranger's pending add\n * never blocks the owner's own.\n */\n identity: \"pointsofcontact_identity_unique\",\n /**\n * `{agency_id, subject_type, subject_id}` unique where `is_primary`, `active` and\n * `confirmed`: at most one VISIBLE primary per subject, so a stranger's\n * pending add can never hold the slot.\n */\n primary: \"pointsofcontact_primary_unique\",\n /**\n * `{agency_id, subject_type, subject_id, identity_key, createdBy}` unique\n * where {@link POC_IN_APP_PENDING_INDEX_FILTER}: one outstanding in-app add\n * per adder, subject and IDENTITY ({@link pocIdentityKey}: name + preferred\n * email). See `POC_IN_APP_PENDING_INDEX`.\n */\n inAppPending: \"pointsofcontact_inapp_pending_unique\",\n /** `{status, createdAt, id}`: the steward's review queue, paged oldest first. */\n pendingQueue: \"pointsofcontact_pending_queue\",\n} as const;\n\n/** The partial filter of {@link POINT_OF_CONTACT_INDEXES.identity}. */\nexport const POC_IDENTITY_INDEX_FILTER = { active: true, status: \"confirmed\" } as const;\n\n/** The partial filter of {@link POINT_OF_CONTACT_INDEXES.primary}. */\nexport const POC_PRIMARY_INDEX_FILTER = { is_primary: true, active: true, status: \"confirmed\" } as const;\n\n/** The partial filter of {@link POINT_OF_CONTACT_INDEXES.inAppPending}: an outstanding in-app add. */\nexport const POC_IN_APP_PENDING_INDEX_FILTER = { status: \"pending\", origin: \"in_app\", active: true } as const;\n\n/**\n * The key of {@link POINT_OF_CONTACT_INDEXES.inAppPending}: the stored scalar\n * `identity_key`. Never an email list: two people may share a mailbox\n * (`intake@`), and an email-list key would merge them.\n */\nexport const POC_IN_APP_PENDING_INDEX_KEY = {\n agency_id: 1,\n subject_type: 1,\n subject_id: 1,\n identity_key: 1,\n createdBy: 1,\n} as const;\n\n/** A caller-chosen id (seed path only): the hti-features `^poc-[a-z0-9_-]+$` pattern. */\nexport const POC_ID_PATTERN = /^poc-[a-z0-9_-]+$/;\n\nconst HEX_24 = /^[0-9a-fA-F]{24}$/;\n\nconst idString = z.string().trim().min(1).max(200);\nconst text = (max: number) => z.string().trim().min(1).max(max);\n\n/** A seat or person id. A 24-hex id is lowercased so one seat has one spelling. */\nexport const PocLinkIdSchema = idString.transform((v) => (HEX_24.test(v) ? v.toLowerCase() : v));\n\n/** A lowercased, trimmed email address. */\nexport const PocEmailSchema = z.string().trim().toLowerCase().email(\"Not an email address.\").max(254);\n\nconst PurposesSchema = z\n .array(z.enum(CONTACT_PURPOSE_CODES))\n .max(CONTACT_PURPOSE_CODES.length)\n .transform((list) => [...new Set(list)]);\n\nconst UrgentMethodsSchema = z\n .array(\n z.string().refine(isPocUrgentMethodCode, {\n message:\n \"urgent_methods holds selectable CVC-185 preferred_contact_method codes from the Agency Hub subset (email · call · text).\",\n }),\n )\n .max(3)\n .transform((list) => [...new Set(list)]);\n\n// ─── Email / phone entries ───────────────────────────────────────────\n\n/** At most this many emails, and this many phones, on one contact. */\nexport const POC_MAX_CONTACT_ENTRIES = 10;\n\n/** One stored email or phone entry. The single source of {@link PocContactEntry}. */\nexport const StoredContactEntrySchema = z.object({\n /** An email (lowercased) or a phone as typed (trimmed). */\n value: z.string(),\n /** Exactly one entry of a non-empty list is the preferred one. */\n is_preferred: z.boolean(),\n});\n/** One email or phone on a contact (pl-e98). */\nexport type PocContactEntry = z.infer<typeof StoredContactEntrySchema>;\n\n/** An entry as READ: a missing or null flag is false (the first-entry rule then applies). */\nconst ReadContactEntrySchema = StoredContactEntrySchema.extend({\n is_preferred: z\n .boolean()\n .nullish()\n .transform((v) => v === true),\n});\n\n/**\n * The line a phone value names: digits only, a leading US country code\n * dropped. Canon's `phoneDigits` (prototype\n * `leads-app/server/objectStructuresEngine.generated.mjs` @ fa0fd0b0\n * L282-L286), verbatim in behaviour.\n */\nexport function pocPhoneDigits(v: string): string {\n const d = v.replace(/\\D/g, \"\");\n return d.length === 11 && d.charAt(0) === \"1\" ? d.slice(1) : d;\n}\n\n/**\n * DISPLAY only: how a reader may draw a stored phone. Canon's `formatPhone`\n * (same file, L246-L256; \"This is display only\", L244), verbatim in\n * behaviour: every non-digit is dropped, a redundant US `1` is dropped, and\n * the digits are drawn `(AAA) BBB-CCCC`, or `+cc (AAA) BBB-CCCC` past ten\n * digits. Empty when the value has no digit. Never written back: it is lossy\n * (an extension becomes digits of the number, a short number draws oddly), so\n * the store keeps the phone as typed.\n */\nexport function formatPocPhone(s: string): string {\n let d = s.replace(/\\D/g, \"\");\n if (!d) return \"\";\n if (d.length === 11 && d.charAt(0) === \"1\") d = d.slice(1);\n if (d.length <= 3) return `(${d}`;\n if (d.length <= 6) return `(${d.slice(0, 3)}) ${d.slice(3)}`;\n if (d.length <= 10) return `(${d.slice(0, 3)}) ${d.slice(3, 6)}-${d.slice(6)}`;\n const cc = d.slice(0, d.length - 10);\n const r = d.slice(d.length - 10);\n return `+${cc} (${r.slice(0, 3)}) ${r.slice(3, 6)}-${r.slice(6)}`;\n}\n\nconst emailKey = (v: string) => v.trim().toLowerCase();\n\n/**\n * The preferred rule on an already-clean list: exactly one preferred when\n * non-empty, the first marked one, else the first entry.\n */\nfunction settlePreferred(list: readonly PocContactEntry[]): PocContactEntry[] {\n const at = list.findIndex((e) => e.is_preferred);\n const keep = at < 0 ? 0 : at;\n return list.map((e, i) => ({ value: e.value, is_preferred: i === keep }));\n}\n\n/** A stored list as READ: repaired, never refused (module comment). */\nfunction readEntries(\n list: readonly PocContactEntry[],\n clean: (v: string) => string,\n keyOf: (v: string) => string,\n): PocContactEntry[] {\n const seen = new Set<string>();\n const out: PocContactEntry[] = [];\n for (const e of list) {\n const value = clean(e.value);\n const k = value ? keyOf(value) : \"\";\n if (!k || seen.has(k)) continue;\n seen.add(k);\n out.push({ value, is_preferred: e.is_preferred });\n }\n return settlePreferred(out);\n}\n\n/** Stored `emails`, read: trimmed, lowercased, empty and repeated entries dropped, one preferred. */\nexport const StoredEmailListSchema = z\n .array(ReadContactEntrySchema)\n .transform((l) => readEntries(l, emailKey, (v) => v));\n\n/** Stored `phones`, read: trimmed, digitless and repeated lines dropped, one preferred. */\nexport const StoredPhoneListSchema = z\n .array(ReadContactEntrySchema)\n .transform((l) => readEntries(l, (v) => v.trim(), pocPhoneDigits));\n\n/**\n * A writer's list: at most one preferred, no repeated value; normalized so a\n * non-empty list has exactly one preferred (the marked one, else the first).\n */\nfunction entryListSchema(\n value: z.ZodType<string, z.ZodTypeDef, unknown>,\n keyOf: (v: string) => string,\n noun: \"email\" | \"phone\",\n) {\n return z\n .array(z.object({ value, is_preferred: z.boolean().optional() }).strict())\n .max(POC_MAX_CONTACT_ENTRIES)\n .superRefine((list, ctx) => {\n if (list.filter((e) => e.is_preferred === true).length > 1) {\n ctx.addIssue({ code: \"custom\", message: `A contact has at most one preferred ${noun}.` });\n }\n const seen = new Set<string>();\n list.forEach((e, i) => {\n const k = keyOf(e.value);\n if (seen.has(k)) {\n ctx.addIssue({\n code: \"custom\",\n path: [i, \"value\"],\n message: `The same ${noun} appears twice on one contact.`,\n });\n }\n seen.add(k);\n });\n })\n .transform((list): PocContactEntry[] =>\n settlePreferred(list.map((e) => ({ value: e.value, is_preferred: e.is_preferred === true }))),\n );\n}\n\n/** A writer's `emails`: lowercased addresses, at most one preferred, the first when none is marked. */\nexport const PocEmailListSchema = entryListSchema(PocEmailSchema, (v) => v, \"email\");\n\n/** A phone as a writer sends it: trimmed, at least one digit, stored as typed. */\nconst PocPhoneValueSchema = text(40).refine((v) => /\\d/.test(v), {\n message: \"A phone number has at least one digit.\",\n});\n\n/** A writer's `phones`: as typed, one per line (by digits), at most one preferred, the first when none is marked. */\nexport const PocPhoneListSchema = entryListSchema(PocPhoneValueSchema, pocPhoneDigits, \"phone\");\n\n/**\n * The preferred entry of a list: the one marked `is_preferred`, else the\n * first (the first-entry rule), else null for an empty or absent list.\n */\nexport function preferredContactEntry(\n list: readonly PocContactEntry[] | null | undefined,\n): PocContactEntry | null {\n if (!list || list.length === 0) return null;\n return list.find((e) => e.is_preferred) ?? list[0] ?? null;\n}\n\n/**\n * The contact's preferred email from its `emails`, or null. Takes a stored\n * row or any view. On a stored seat-linked row it is null (the email is the\n * seat's); a view's own `email` projection already resolves the seat.\n */\nexport function preferredEmail(c: { readonly emails: readonly PocContactEntry[] }): string | null {\n return preferredContactEntry(c.emails)?.value ?? null;\n}\n\n/** The contact's preferred phone, or null ({@link preferredEmail}'s rules). */\nexport function preferredPhone(c: { readonly phones: readonly PocContactEntry[] }): string | null {\n return preferredContactEntry(c.phones)?.value ?? null;\n}\n\n// ─── Owner ───────────────────────────────────────────────────────────\n\n/**\n * WHOSE contact this is, resolved by the platform route and normalized by the\n * platform writer.\n *\n * Id universe (decision D1, veto-able). Stored as plain strings, never\n * ObjectIds; readers match the string exactly:\n * - `agency_id`: `String(_id)` of the platform-db `agencies` row, the id a\n * share recipient carries in PAVE and Thread (platform\n * `lib/sharing-settings/recipient-id.ts`). The writer normalizes any\n * accepted form (`entity_id`, `id`, `_id`, a mapped registry row; a 24-hex\n * id in any case) through `resolveRecipientId` and refuses an owner that\n * does not resolve.\n * - `org_id`: `String(_id)` of the platform-db `organizations` row. An\n * agency and an org are linked only by a GENUINE 1:1 mirror:\n * `agencies.organizationId` names the org AND `organizations.agencyId`\n * names the agency (the auth mirror). `organizations.agencyId` alone is\n * many-to-one (the platform stamps the creating agency on every org it\n * creates) and never makes an org part of an agency. The writer stamps the\n * genuine mirror on an agency's rows, stamps the genuine mirror agency on\n * an org's rows, and otherwise leaves the other key null.\n * - `subject_id`: `agency` → `agency_id`; `org` → `org_id`; `program` →\n * `organizations.programs[].programId` on the agency's genuine-mirror org;\n * `team` → the team's `entity_id ?? id ?? String(_id)` (a `teams` row of\n * that agency); `location` → the site's id; `service` → the Service\n * Listing's `id` (a `servicelistings` row of `org_id`; `agency_id` null or\n * the org's genuine-mirror agency). The writer verifies membership;\n * `location` is refused until a location directory exists. Team and location\n * ids may be slugs two agencies share, so the subject is always read and\n * keyed together with `agency_id`.\n *\n * Every subject except an org-only partner resolves to an agency (canon stamps\n * `agency_id` on the row: platform-prototype `src/agencyhub.jsx` @ 0fa04c1\n * L411). An `org` subject carries `agency_id: null`, or its genuine mirror agency.\n */\nexport const PocOwnerSchema = z\n .object({\n subject_type: z.enum(POC_SUBJECT_TYPES),\n subject_id: idString,\n agency_id: idString.nullable(),\n org_id: idString.nullable(),\n })\n .strict()\n .superRefine((o, ctx) => {\n if (o.subject_type === \"agency\" && o.subject_id !== o.agency_id) {\n ctx.addIssue({ code: \"custom\", path: [\"subject_id\"], message: \"An agency's own contact names that agency: subject_id must equal agency_id.\" });\n }\n if (o.subject_type === \"org\" && o.subject_id !== o.org_id) {\n ctx.addIssue({ code: \"custom\", path: [\"subject_id\"], message: \"An org's own contact names that org: subject_id must equal org_id.\" });\n }\n if ((o.subject_type === \"program\" || o.subject_type === \"team\" || o.subject_type === \"location\") && !o.agency_id) {\n ctx.addIssue({ code: \"custom\", path: [\"agency_id\"], message: `A ${o.subject_type} contact names the agency it belongs to.` });\n }\n if (o.subject_type === \"service\" && !o.org_id) {\n ctx.addIssue({ code: \"custom\", path: [\"org_id\"], message: \"A service listing's contact names the listing's organization.\" });\n }\n });\nexport type PocOwner = z.infer<typeof PocOwnerSchema>;\n\n// ─── Writer bodies ───────────────────────────────────────────────────\n\nexport const PocDetailsSchema = z\n .object({\n user_id: PocLinkIdSchema.nullable().optional(),\n person_id: PocLinkIdSchema.nullable().optional(),\n display_name: text(200).nullable().optional(),\n emails: PocEmailListSchema.optional(),\n phones: PocPhoneListSchema.optional(),\n purposes: PurposesSchema.optional(),\n urgent_methods: UrgentMethodsSchema.optional(),\n is_primary: z.boolean().optional(),\n is_confidential: z.boolean().optional(),\n notes: text(2000).nullable().optional(),\n })\n .strict();\nexport type PocDetails = z.infer<typeof PocDetailsSchema>;\n/** What a body builder sends (defaulted and normalized fields optional). */\nexport type PocDetailsInput = z.input<typeof PocDetailsSchema>;\n\n/**\n * An advocate's in-app add of a partner's contact (pl-bt1; Crysta 2026-10-14\n * 23:25): a write-in with a name and at least one email (the preferred one is\n * the magic-link address), phones if known, tagged Referrals (magic link) unless\n * the body says otherwise. No seat or person link, no primary, no confidential flag, no\n * notes: those are the subject's own to set.\n */\nexport const PocInAppSchema = z\n .object({\n display_name: text(200),\n emails: PocEmailListSchema.refine((l) => l.length > 0, { message: \"An in-app add names at least one email.\" }),\n phones: PocPhoneListSchema.optional(),\n purposes: PurposesSchema.default([REFERRALS_MAGIC_LINK_PURPOSE]),\n urgent_methods: UrgentMethodsSchema.optional(),\n })\n .strict();\nexport type PocInApp = z.infer<typeof PocInAppSchema>;\n/** The `POST /api/partner-contacts` body a caller sends (`purposes` defaulted). */\nexport type PocInAppInput = z.input<typeof PocInAppSchema>;\n\n/** A seed row: the details plus the sheet's own `poc-*` id. */\nexport const PocSeedSchema = PocDetailsSchema.extend({\n id: z.string().trim().regex(POC_ID_PATTERN, \"A seeded contact id is poc-<lowercase letters, digits, '_' or '-'>.\"),\n}).strict();\nexport type PocSeed = z.infer<typeof PocSeedSchema>;\nexport type PocSeedInput = z.input<typeof PocSeedSchema>;\n\n/** An edit: at least one field; identity (`user_id`, `person_id`) is fixed at mint; a list replaces the stored list. */\nexport const PocPatchSchema = PocDetailsSchema.omit({ user_id: true, person_id: true })\n .strict()\n .refine((b) => Object.values(b).some((v) => v !== undefined), {\n message: \"A contact edit must name at least one field.\",\n });\nexport type PocPatch = z.infer<typeof PocPatchSchema>;\nexport type PocPatchInput = z.input<typeof PocPatchSchema>;\n\n/**\n * A parsed patch without its `undefined` values. A key present as\n * `undefined` means \"not edited\": written through, the driver would store\n * `null` (clearing `is_confidential` would publish a confidential contact).\n */\nexport function definedPatch<T extends Record<string, unknown>>(p: T): Partial<T> {\n return Object.fromEntries(Object.entries(p).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\n// ─── Stored document ─────────────────────────────────────────────────\n\nconst nullableString = z.string().nullable();\n\n/** The stored document (Mongo's `_id` stripped). Readers parse every row with it. */\nexport const PointOfContactDocSchema = z.object({\n id: z.string().min(1),\n subject_type: z.enum(POC_SUBJECT_TYPES),\n subject_id: z.string().min(1),\n agency_id: nullableString,\n org_id: nullableString,\n user_id: nullableString,\n person_id: nullableString,\n display_name: nullableString,\n /** Lowercased emails, read leniently. Empty on a seat-linked contact (it resolves from the seat). */\n emails: StoredEmailListSchema,\n /** Read leniently. Empty on a seat-linked contact. */\n phones: StoredPhoneListSchema,\n purposes: z.array(z.enum(CONTACT_PURPOSE_CODES)),\n /** CVC-185 codes. */\n urgent_methods: z.array(z.string()),\n is_primary: z.boolean(),\n is_confidential: z.boolean(),\n /** A removed contact is deactivated, never deleted. */\n active: z.boolean(),\n notes: nullableString,\n status: z.enum(POC_STATUSES),\n origin: z.enum(POC_ORIGINS),\n added_in_app: z.enum(POC_ADDED_IN_APPS).nullable(),\n /** `seat:<user_id>` · `person:<person_id>` · `writein:<name>|<preferred email>`, lowercased. */\n identity_key: z.string().min(1),\n confirmed_by: nullableString,\n confirmed_at: nullableString,\n deactivated_by: nullableString,\n deactivated_at: nullableString,\n /** Bumped by every write; edits and the steward's confirm name the version they saw. */\n version: z.number().int().nonnegative(),\n createdBy: nullableString,\n createdAt: z.string().min(1),\n updatedBy: nullableString,\n updatedAt: z.string().min(1),\n});\nexport type PointOfContactDoc = z.infer<typeof PointOfContactDocSchema>;\n\n/** The fields the whole-contact rules read. */\nexport type PocRuleInput = Pick<PointOfContactDoc, \"user_id\" | \"person_id\" | \"display_name\" | \"emails\" | \"phones\" | \"purposes\">;\n\nexport interface PocRuleViolation {\n reason: \"user_id_xor_person_id\" | \"seat_contact_has_own_reach\" | \"display_name_required\" | \"referral_contact_needs_email\";\n message: string;\n}\n\n/**\n * The whole-contact rules (module comment). A seat-linked Referrals contact is\n * NOT a violation here: the seat's email is checked by the writer, which can\n * read the seat. Returns every violation, empty when the contact is valid.\n */\nexport function pocRuleViolations(c: PocRuleInput): PocRuleViolation[] {\n const out: PocRuleViolation[] = [];\n const seat = !!c.user_id;\n if (c.user_id && c.person_id) {\n out.push({ reason: \"user_id_xor_person_id\", message: \"A contact points at a seat (user_id) or a person (person_id), never both.\" });\n }\n if (seat && (c.emails.length > 0 || c.phones.length > 0)) {\n out.push({\n reason: \"seat_contact_has_own_reach\",\n message: \"A seat-linked contact stores no email or phone of its own; they resolve from the seat.\",\n });\n }\n if (!seat && !c.display_name) {\n out.push({ reason: \"display_name_required\", message: \"A contact that holds no seat needs a display_name.\" });\n }\n if (!seat && c.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE) && c.emails.length === 0) {\n out.push({\n reason: \"referral_contact_needs_email\",\n message: \"A contact tagged Referrals (magic link) must have an email.\",\n });\n }\n return out;\n}\n\n/**\n * The identity a subject's contacts are deduplicated by (canon `hubSavePocs`,\n * platform-prototype `src/agencyhub.jsx` @ 0fa04c1 L382-L384). A write-in keys\n * on its name and its PREFERRED email, so changing the preferred email changes\n * the key: the writer recomputes it on every edit.\n */\nexport function pocIdentityKey(c: Pick<PointOfContactDoc, \"user_id\" | \"person_id\" | \"display_name\" | \"emails\">): string {\n const norm = (v: string | null) => (v ?? \"\").trim().toLowerCase();\n if (c.user_id) return `seat:${norm(c.user_id)}`;\n if (c.person_id) return `person:${norm(c.person_id)}`;\n return `writein:${norm(c.display_name)}|${norm(preferredEmail(c))}`;\n}\n","/**\n * Point of contact read rules (pl-3r8). Pure, no I/O. Every reader (Thread,\n * PAVE, LEADS, the platform) applies these through this module; none\n * re-implements them.\n *\n * ## Three views\n *\n * - **Network view** ({@link toNetworkView}): what any app may show or use\n * about another organization's contact. A row is network-visible only when\n * it is `active`, `confirmed` and NOT `is_confidential`:\n * - pending rows (in-app adds, seeded rows) wait for HTI Labs (Crysta\n * 2026-10-14: an in-app add is \"available platform-wide after HTI Labs\n * confirms it\");\n * - a confidential contact is \"never published\" (prototype\n * `Org + Personnel Registry/DIRECTORY_CSV_EDITING_GUIDE.md` @ 6c2db859\n * § 0.9 L958; hti-features `PointOfContact.v1.json` `is_confidential`:\n * \"Never publish this contact\"), so it is left out entirely rather\n * than masked. The network view is unchanged by pl-iza (0.32.0):\n * confidential rows are absent from every view another organization\n * sees (this view, `getContact`, `listContactsForSubject`, the\n * referral `recipients`; only the subject's owner and the steward see\n * them). A confidential Referrals (magic link) holder still receives\n * the magic link, but only through the send-only\n * `resolveMagicLinkRecipients` (`./reader.ts`), which never projects\n * the row and exposes a count;\n * - the seat / person links, `notes`, review stamps, actor ids and the\n * identity key are not projected.\n * - **Owner view** ({@link toOwnerView}): the subject's own editor (Admin\n * Hub → My Agency Info → Contacts). Unmasked, every status, with the seat's\n * reach resolved, so an editor round-trip never wipes a confidential or\n * pending contact. Actor ids and the app a partner added it in are not\n * projected: the owner sees `origin`, not who at another agency wrote it.\n * - **Steward view** ({@link toStewardView}): HTI Labs' review. Everything\n * except the identity key, with the seat's reach resolved.\n *\n * Every view carries `purpose_labels` (hti-features `purpose_labels`, readOnly).\n *\n * ## Emails and phones (pl-e98)\n *\n * The owner and steward views carry the row's own `emails` / `phones` (what\n * the editor edits; empty on a seat-linked row) beside the resolved `seat`.\n * The network view carries the REACHABLE lists: the row's, or for a\n * seat-linked row the seat's single email and phone as one preferred entry\n * each. EVERY view also carries read-only `email` / `phone`: the reachable\n * preferred address (the row's preferred entry, or the seat's for a\n * seat-linked contact), the projections canon's card keeps of its preferred\n * entries (platform-prototype `src/agencyhub.jsx` @ 6f428116 L8195-L8202). A\n * reader that sends to or shows one address reads that projection. Views own\n * their lists: they are copies, never the row's arrays.\n */\n\nimport {\n PointOfContactDocSchema,\n preferredContactEntry,\n type PocContactEntry,\n type PointOfContactDoc,\n} from \"./schemas.js\";\nimport { contactPurposeLabel, type ContactPurposeCode, type PocSubjectType } from \"./vocabulary.js\";\n\n/** A seat's reach, resolved by the reader from platform-db `users`. */\nexport interface SeatReach {\n email: string | null;\n phone: string | null;\n name: string | null;\n}\n\n/** The steward view: everything but the identity key, seat resolved. */\nexport interface PointOfContactStewardView extends Omit<PointOfContactDoc, \"identity_key\"> {\n purpose_labels: string[];\n /** The seat's reach for a seat-linked contact (null when unlinked or not found). */\n seat: SeatReach | null;\n /** Read-only: the reachable preferred email (the seat's for a seat-linked contact), or null. */\n email: string | null;\n /** Read-only: the reachable preferred phone, or null. */\n phone: string | null;\n}\n\n/** The owner view: unmasked, without other organizations' actor ids. */\nexport type PointOfContactOwnerView = Omit<\n PointOfContactStewardView,\n \"createdBy\" | \"updatedBy\" | \"confirmed_by\" | \"deactivated_by\" | \"added_in_app\"\n>;\n\n/** The network view: what other organizations see. */\nexport interface PointOfContactNetworkView {\n id: string;\n subject_type: PocSubjectType;\n subject_id: string;\n agency_id: string | null;\n org_id: string | null;\n display_name: string | null;\n /** The row's emails, or the seat's email as one preferred entry when the contact is seat-linked and a seat resolver was given. */\n emails: PocContactEntry[];\n /** The row's phones, or the seat's phone as one preferred entry (the same rules as `emails`). */\n phones: PocContactEntry[];\n /** The preferred of `emails` (`preferredEmail(view)`), or null. The magic-link address. */\n email: string | null;\n /** The preferred of `phones` (`preferredPhone(view)`), or null. */\n phone: string | null;\n purposes: ContactPurposeCode[];\n purpose_labels: string[];\n urgent_methods: string[];\n is_primary: boolean;\n updatedAt: string;\n}\n\n/** A stored row that does not match the contract. Readers propagate it. */\nexport class PointOfContactShapeError extends Error {\n constructor(\n readonly contactId: string | null,\n readonly issues: string[],\n ) {\n super(`points-of-contact: stored row ${contactId ?? \"(no id)\"} does not match the contract: ${issues.join(\"; \")}`);\n this.name = \"PointOfContactShapeError\";\n }\n}\n\n/**\n * A stored row → the typed document. Strict: every writer (the platform's,\n * and the shared in-app add every app runs, `./writer.ts`) writes every\n * field, so a row that does not parse (an unknown origin or status, a missing\n * id) is a defect and FAILS LOUDLY rather than being read as some default.\n */\nexport function normalizePointOfContact(raw: Record<string, unknown>): PointOfContactDoc {\n const parsed = PointOfContactDocSchema.safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new PointOfContactShapeError(\n typeof raw.id === \"string\" && raw.id ? raw.id : null,\n parsed.error.issues.map((i) => `${i.path.join(\".\") || \"(row)\"}: ${i.message}`),\n );\n}\n\n/** True when other organizations may see or use this contact. */\nexport function isNetworkVisible(d: Pick<PointOfContactDoc, \"active\" | \"status\" | \"is_confidential\">): boolean {\n return d.active && d.status === \"confirmed\" && !d.is_confidential;\n}\n\nconst copyEntries = (list: readonly PocContactEntry[]): PocContactEntry[] =>\n list.map((e) => ({ ...e }));\n\n/**\n * Where the contact is reached: the row's own lists, or for a seat-linked row\n * the seat's email (trimmed, lowercased) and phone as one preferred entry\n * each. Always fresh arrays.\n */\nfunction reachOf(\n d: PointOfContactDoc,\n seat: SeatReach | null | undefined,\n): { emails: PocContactEntry[]; phones: PocContactEntry[] } {\n if (!d.user_id) return { emails: copyEntries(d.emails), phones: copyEntries(d.phones) };\n const one = (v: string | null | undefined): PocContactEntry[] =>\n v ? [{ value: v, is_preferred: true }] : [];\n return {\n emails: one(seat?.email?.trim().toLowerCase()),\n phones: one(seat?.phone?.trim()),\n };\n}\n\nconst preferredValue = (list: readonly PocContactEntry[]): string | null =>\n preferredContactEntry(list)?.value ?? null;\n\n/** The steward view. */\nexport function toStewardView(\n d: PointOfContactDoc,\n seat?: SeatReach | null,\n): PointOfContactStewardView {\n const { identity_key: _internal, ...rest } = d;\n const reach = reachOf(d, seat);\n return {\n ...rest,\n emails: copyEntries(d.emails),\n phones: copyEntries(d.phones),\n purposes: [...d.purposes],\n urgent_methods: [...d.urgent_methods],\n purpose_labels: d.purposes.map(contactPurposeLabel),\n seat: d.user_id ? (seat ?? null) : null,\n email: preferredValue(reach.emails),\n phone: preferredValue(reach.phones),\n };\n}\n\n/** The owner view. */\nexport function toOwnerView(\n d: PointOfContactDoc,\n seat?: SeatReach | null,\n): PointOfContactOwnerView {\n const {\n createdBy: _c,\n updatedBy: _u,\n confirmed_by: _cb,\n deactivated_by: _db,\n added_in_app: _app,\n ...rest\n } = toStewardView(d, seat);\n return rest;\n}\n\n/**\n * The network view of one row, or null when the row is not network-visible.\n * A seat-linked row reads its email, phone and (when the row has none) name\n * from `seat`.\n */\nexport function toNetworkView(\n d: PointOfContactDoc,\n seat?: SeatReach | null,\n): PointOfContactNetworkView | null {\n if (!isNetworkVisible(d)) return null;\n const seatLinked = !!d.user_id;\n const { emails, phones } = reachOf(d, seat);\n return {\n id: d.id,\n subject_type: d.subject_type,\n subject_id: d.subject_id,\n agency_id: d.agency_id,\n org_id: d.org_id,\n display_name: d.display_name ?? (seatLinked ? (seat?.name ?? null) : null),\n emails,\n phones,\n email: preferredValue(emails),\n phone: preferredValue(phones),\n purposes: [...d.purposes],\n purpose_labels: d.purposes.map(contactPurposeLabel),\n urgent_methods: [...d.urgent_methods],\n is_primary: d.is_primary,\n updatedAt: d.updatedAt,\n };\n}\n\nconst SUBJECT_ORDER: Record<PocSubjectType, number> = {\n agency: 0,\n org: 1,\n program: 2,\n team: 3,\n location: 4,\n service: 5,\n};\n\n/** Reading order: the agency / org before its programs, teams and locations, primary first, then name, then id. */\nexport function byContactReadingOrder(\n a: Pick<PointOfContactDoc, \"subject_type\" | \"subject_id\" | \"is_primary\" | \"display_name\" | \"id\">,\n b: Pick<PointOfContactDoc, \"subject_type\" | \"subject_id\" | \"is_primary\" | \"display_name\" | \"id\">,\n): number {\n return (\n SUBJECT_ORDER[a.subject_type] - SUBJECT_ORDER[b.subject_type] ||\n a.subject_id.localeCompare(b.subject_id) ||\n Number(b.is_primary) - Number(a.is_primary) ||\n (a.display_name ?? \"\").localeCompare(b.display_name ?? \"\") ||\n a.id.localeCompare(b.id)\n );\n}\n","/**\n * Point of contact reads over a raw MongoDB driver handle (pl-3r8). No\n * mongoose, no driver import: the handle is typed structurally, so a\n * `mongodb` `Db` (the platform, PAVE's `platformDb`) or a mongoose\n * connection's `.db` both fit.\n *\n * Every read returns rows through `./readRules.ts`. A read ERROR propagates,\n * and so does a stored row that does not match the contract\n * (`PointOfContactShapeError`): a subject with no contacts honestly reads\n * `[]`, an unreadable or corrupt store never does.\n *\n * ## Seat-linked contacts\n *\n * A seat-linked row stores no email or phone; they live on the seat\n * (platform-db `users`). This package carries no driver, so it cannot build an\n * ObjectId filter for `users._id`; the reader passes a {@link SeatResolver}\n * that reads its own `users`. The partner rollup REQUIRES one, so a reader\n * cannot silently drop seat-linked referral contacts.\n *\n * ## Confidential Referrals (magic link) holders (pl-iza, 0.32.0)\n *\n * A confidential holder still receives the magic link; the sender never sees\n * the address (CVC-338, prototype `data/cvcs/core_contact_purpose.yaml` @\n * 184893b6 L95; HANDOFF.md @ 184893b6 L569, L575 \"POC-PROFILE-ALIGNMENTS\"\n * D(ii)). Confidential rows are absent from every view another organization\n * sees (only the owner and steward reads carry them). The referral rollup\n * reads them in a SEPARATE query and hands out only a count\n * (`confidentialCount`) or, to a send, a {@link ConfidentialReferralRecipients}\n * whose `deliver` alone touches the addresses (the implementation is not\n * exported). A confidential row never reaches `unreachable`, and a corrupt\n * row that may be confidential is counted, never thrown.\n */\n\nimport { POINTS_OF_CONTACT_COLLECTION, type PointOfContactDoc } from \"./schemas.js\";\nimport {\n byContactReadingOrder,\n normalizePointOfContact,\n toNetworkView,\n toOwnerView,\n toStewardView,\n type PointOfContactNetworkView,\n type PointOfContactOwnerView,\n type PointOfContactStewardView,\n type SeatReach,\n} from \"./readRules.js\";\nimport { REFERRALS_MAGIC_LINK_PURPOSE, type PocSubjectType } from \"./vocabulary.js\";\n\n/** The slice of a driver `Collection` the reads use. */\nexport interface PocCollectionLike {\n find(filter: Record<string, unknown>): { toArray(): Promise<unknown[]> };\n findOne(filter: Record<string, unknown>): Promise<unknown>;\n}\n\n/** The slice of a driver `Db` the reads use. */\nexport interface PocDbLike {\n collection(name: string): PocCollectionLike;\n}\n\n/** Resolves seat ids (platform-db `users._id`, string form) to their reach. Missing ids are simply absent. */\nexport type SeatResolver = (userIds: readonly string[]) => Promise<ReadonlyMap<string, SeatReach>>;\n\n/**\n * A subject, always read together with its agency where ids can collide.\n * Program, team and location ids can be slugs two agencies share, so their reads\n * REQUIRE `agency_id`. A service listing's contact names `agency_id` too:\n * the listing org's genuine-mirror agency, or `null` for an org-only partner.\n * Only agency and org subjects (whose ids are themselves unique) may omit it.\n */\nexport type PocSubjectRef =\n | { subject_type: \"agency\" | \"org\"; subject_id: string; agency_id?: string | null }\n | { subject_type: \"program\" | \"team\" | \"location\"; subject_id: string; agency_id: string }\n | { subject_type: \"service\"; subject_id: string; agency_id: string | null };\n\nfunction subjectFilter(subject: PocSubjectRef): Record<string, unknown> {\n const type = requireId(\"subject_type\", subject.subject_type) as PocSubjectType;\n const base = { subject_type: type, subject_id: requireId(\"subject_id\", subject.subject_id) };\n const agency = subject.agency_id;\n if (type === \"program\" || type === \"team\" || type === \"location\") {\n return { ...base, agency_id: requireId(\"agency_id\", agency) };\n }\n if (type === \"service\" && agency === undefined) {\n throw new TypeError(\n \"points-of-contact: a service subject read names agency_id (a string, or null for an org-only partner)\",\n );\n }\n if (agency === undefined) return base;\n return { ...base, agency_id: agency === null ? null : requireId(\"agency_id\", agency) };\n}\n\n/**\n * A partner, by its agency, its organization, or both. Both together read the\n * contacts on either (an agency's rows carry its mirror org, an org-only\n * partner's rows carry no agency).\n */\nexport interface PocPartnerSelector {\n agency_id?: string | null;\n org_id?: string | null;\n}\n\nfunction requireId(name: string, v: unknown): string {\n if (typeof v !== \"string\" || v.length === 0) {\n throw new TypeError(`points-of-contact: ${name} must be a non-empty string`);\n }\n return v;\n}\n\n/** The network-visible filter (`isNetworkVisible`, pushed into the query). */\nconst NETWORK_VISIBLE = { active: true, status: \"confirmed\", is_confidential: { $ne: true } } as const;\n\nconst rowOf = (r: unknown): Record<string, unknown> =>\n r !== null && typeof r === \"object\" ? (r as Record<string, unknown>) : {};\n\nasync function findDocs(\n db: PocDbLike,\n filter: Record<string, unknown>,\n): Promise<PointOfContactDoc[]> {\n const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).find(filter).toArray();\n return raw.map((r) => normalizePointOfContact(rowOf(r))).sort(byContactReadingOrder);\n}\n\nasync function seatsFor(\n docs: readonly PointOfContactDoc[],\n resolve?: SeatResolver,\n): Promise<ReadonlyMap<string, SeatReach>> {\n const ids = [...new Set(docs.map((d) => d.user_id).filter((u): u is string => !!u))];\n if (!resolve || ids.length === 0) return new Map();\n return resolve(ids);\n}\n\nconst seatOf = (d: PointOfContactDoc, seats: ReadonlyMap<string, SeatReach>) =>\n d.user_id ? (seats.get(d.user_id) ?? null) : null;\n\nfunction networkViews(\n docs: readonly PointOfContactDoc[],\n seats: ReadonlyMap<string, SeatReach>,\n): PointOfContactNetworkView[] {\n return docs\n .map((d) => toNetworkView(d, seatOf(d, seats)))\n .filter((v): v is PointOfContactNetworkView => v !== null)\n .sort(byContactReadingOrder); // again, now that seat-linked rows carry the seat's name\n}\n\n/**\n * A subject's contacts as other organizations see them: active, confirmed,\n * not confidential. Without a seat resolver, a seat-linked contact reads\n * `email: null`.\n */\nexport async function listContactsForSubject(\n db: PocDbLike,\n subject: PocSubjectRef,\n opts: { resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactNetworkView[]> {\n const docs = await findDocs(db, { ...subjectFilter(subject), ...NETWORK_VISIBLE });\n return networkViews(docs, await seatsFor(docs, opts.resolveSeats));\n}\n\n/**\n * A referral recipient: a network-visible contact with a resolved email, or\n * (only when asked, {@link ReferralContactsOptions.includeOwnPendingFor}) the\n * asking advocate's OWN pending in-app add, marked `pending: true` so a UI can\n * label it.\n */\nexport type ReferralRecipient = PointOfContactNetworkView & { email: string; pending?: true };\n\nexport interface ReferralContactsOptions {\n resolveSeats: SeatResolver;\n /**\n * The asking advocate's Auth0 `sub`, taken server-side from the verified\n * token (the same pinning as `mintPartnerContact`'s `actor.id`). When set,\n * the advocate's OWN pending in-app adds on the partner (`status: pending`,\n * active, `origin: in_app`, `createdBy` = this sub, tagged Referrals (magic\n * link), not confidential) are returned too, after the confirmed recipients\n * and marked `pending: true`. Nobody else's pending add is ever returned.\n */\n includeOwnPendingFor?: string;\n}\n\nexport interface ReferralContactsResult {\n /** One per distinct email, in reading order (the agency's own contacts first). */\n recipients: ReferralRecipient[];\n /**\n * Ids of tagged, VISIBLE contacts with no email to send to (a seat whose\n * `users` row has none). Never a confidential holder's id.\n */\n unreachable: string[];\n /**\n * The number of distinct confidential Referrals (magic link) holder\n * addresses (pl-iza): active, confirmed, `is_confidential`, tagged, on the\n * same rollup. Deduped among the confidential holders ONLY, never against\n * any visible, pending, typed or added address, so no other row or input\n * moves it. A sender sees this number, never a name, an id or an address\n * (\"+ 1 confidential recipient\").\n */\n confidentialCount: number;\n}\n\n/** The partner rollup keys: its agency, its organization, or both. */\nfunction partnerKeys(partner: PocPartnerSelector): Record<string, string>[] {\n const keys: Record<string, string>[] = [];\n if (partner.agency_id !== undefined && partner.agency_id !== null) {\n keys.push({ agency_id: requireId(\"agency_id\", partner.agency_id) });\n }\n if (partner.org_id !== undefined && partner.org_id !== null) {\n keys.push({ org_id: requireId(\"org_id\", partner.org_id) });\n }\n if (keys.length === 0) throw new TypeError(\"points-of-contact: select a partner by agency_id, org_id or both\");\n return keys;\n}\n\n/** The two public referral reads' shared result: confidential addresses stay inside this module. */\ninterface ReferralHolders {\n recipients: ReferralRecipient[];\n unreachable: string[];\n confidentialAddresses: string[];\n confidentialUnreachableCount: number;\n}\n\n/** A raw row that may be confidential: its stored flag is anything but `false` or absent. */\nconst mayBeConfidential = (raw: Record<string, unknown>) =>\n raw.is_confidential !== false && raw.is_confidential !== undefined;\n\n/**\n * A referral leg's rows. A row that does not match the contract and MAY be\n * confidential is skipped and counted, not thrown: a\n * `PointOfContactShapeError` names the row's id, and an app's error handler\n * can return an error message to the browser. Nothing is logged. In the\n * confidential leg every such row may be; in the visible and pending legs it\n * is one whose stored `is_confidential` is malformed (`\"true\"`, `1`, `null`:\n * it matches `{ $ne: true }`). Any other corrupt row still throws, as\n * {@link findDocs} does.\n */\nasync function findHolderDocs(\n db: PocDbLike,\n filter: Record<string, unknown>,\n confidentialLeg: boolean,\n): Promise<{ docs: PointOfContactDoc[]; skipped: number }> {\n const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).find(filter).toArray();\n const docs: PointOfContactDoc[] = [];\n let skipped = 0;\n for (const r of raw) {\n const row = rowOf(r);\n try {\n docs.push(normalizePointOfContact(row));\n } catch (err) {\n if (!confidentialLeg && !mayBeConfidential(row)) throw err;\n skipped++;\n }\n }\n return { docs: docs.sort(byContactReadingOrder), skipped };\n}\n\n/**\n * The partner's Referrals (magic link) holders, read once for both public\n * reads. Three queries on the same rollup keys, in this order: the visible\n * confirmed holders, the asking advocate's own pending adds (only when asked),\n * and (pl-iza) the confidential confirmed holders. The first two are the\n * pre-0.32.0 queries, unchanged. Seats are resolved ONCE, over the visible and\n * confidential rows together (pending in-app adds are never seat-linked).\n */\nasync function readReferralHolders(\n db: PocDbLike,\n partner: PocPartnerSelector,\n opts: ReferralContactsOptions,\n): Promise<ReferralHolders> {\n const keys = partnerKeys(partner);\n const pendingFor =\n opts.includeOwnPendingFor === undefined\n ? null\n : requireId(\"includeOwnPendingFor\", opts.includeOwnPendingFor);\n const visible = await findHolderDocs(\n db,\n { $or: keys, purposes: REFERRALS_MAGIC_LINK_PURPOSE, ...NETWORK_VISIBLE },\n false,\n );\n const pending =\n pendingFor === null\n ? { docs: [], skipped: 0 }\n : await findHolderDocs(\n db,\n {\n $or: keys,\n purposes: REFERRALS_MAGIC_LINK_PURPOSE,\n ...OWN_PENDING_IN_APP,\n createdBy: pendingFor,\n },\n false,\n );\n const confidential = await findHolderDocs(\n db,\n { $or: keys, purposes: REFERRALS_MAGIC_LINK_PURPOSE, ...CONFIDENTIAL_CONFIRMED },\n true,\n );\n const docs = visible.docs;\n const seats = await seatsFor([...docs, ...confidential.docs], opts.resolveSeats);\n\n const recipients: ReferralRecipient[] = [];\n const unreachable: string[] = [];\n const seen = new Set<string>();\n for (const v of networkViews(docs, seats)) {\n if (!v.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE)) continue;\n const email = v.email;\n if (!email) {\n unreachable.push(v.id);\n continue;\n }\n if (seen.has(email)) continue;\n seen.add(email);\n recipients.push({ ...v, email });\n }\n if (pendingFor !== null) {\n for (const d of pending.docs) {\n // The same filter again, on the parsed row: a reader never widens it.\n if (!isOwnPendingInApp(d, pendingFor)) continue;\n // An in-app add is a write-in (never seat-linked): its view is its own row's,\n // drawn as the network view would draw it once confirmed.\n const v = toNetworkView({ ...d, status: \"confirmed\" });\n const email = v?.email;\n if (!v || !email || seen.has(email)) continue;\n seen.add(email);\n recipients.push({ ...v, email, pending: true });\n }\n }\n\n // pl-iza: confidential holders still receive the link; the sender never sees\n // the address. Deduped among THEMSELVES only, never against a visible,\n // pending, typed or added address: any of those can change under the\n // advocate's eye (their add confirmed by a steward, a seat's email edited,\n // their own typing), and a count that dropped when one matched would tell\n // them a confidential holder's address. An overlap is simply sent twice.\n const confidentialAddresses: string[] = [];\n const confidentialSeen = new Set<string>();\n let confidentialUnreachableCount = visible.skipped + pending.skipped + confidential.skipped;\n for (const d of confidential.docs) {\n // The same filter again, on the parsed row.\n if (!isConfidentialHolder(d)) continue;\n // The steward view's `email` is the reachable preferred address (the\n // seat's for a seat-linked row), drawn as the network view draws it.\n const email = toStewardView(d, seatOf(d, seats)).email;\n if (!email) {\n confidentialUnreachableCount++;\n continue;\n }\n if (confidentialSeen.has(email)) continue;\n confidentialSeen.add(email);\n confidentialAddresses.push(email);\n }\n return { recipients, unreachable, confidentialAddresses, confidentialUnreachableCount };\n}\n\n/**\n * The partner's Referrals (magic link) contacts: every active, confirmed,\n * non-confidential contact tagged `REFERRALS_MAGIC_LINK` on the partner's\n * agency AND on its programs, teams and locations (the rollup, via the row's\n * `agency_id`), and on its organization (via `org_id`). A magic link goes to\n * every one of them (Crysta 2026-08-23, restated 2026-10-14), at its PREFERRED\n * email (pl-e98; the view's `email`). The same email tagged on two subjects is\n * one recipient.\n *\n * With `includeOwnPendingFor` (Nate 2026-10-15), the advocate also sees their\n * own pending in-app adds on the partner, so a contact they just added can be\n * picked before HTI Labs confirms it (pending, marked, after the confirmed\n * recipients; an email a confirmed recipient already has is not repeated).\n * Confidential rows stay out of `recipients` and `unreachable`; they are\n * counted (`confidentialCount`, pl-iza) and reached only through\n * {@link resolveMagicLinkRecipients}. The partner has a\n * magic-link holder when `recipients.length + confidentialCount > 0`.\n */\nexport async function listReferralContactsForPartner(\n db: PocDbLike,\n partner: PocPartnerSelector,\n opts: ReferralContactsOptions,\n): Promise<ReferralContactsResult> {\n const holders = await readReferralHolders(db, partner, opts);\n return {\n recipients: holders.recipients,\n unreachable: holders.unreachable,\n confidentialCount: holders.confidentialAddresses.length,\n };\n}\n\n/** What a send needs: the visible recipients, plus the confidential holders behind a count. */\nexport interface MagicLinkSendList {\n /** As {@link ReferralContactsResult.recipients}. */\n recipients: ReferralRecipient[];\n /** As {@link ReferralContactsResult.unreachable}: visible contacts only. */\n unreachable: string[];\n /** The confidential holders: a count, and a `deliver` that alone touches their addresses. */\n confidential: ConfidentialReferralRecipients;\n /**\n * SERVER-SIDE diagnostic, never returned to a sender: the confidential\n * holder rows that cannot be sent to (no email, a seat with none or not\n * found), plus skipped rows that do not match the contract and may be\n * confidential (their error would name their id). A count, never an id.\n */\n confidentialUnreachableCount: number;\n}\n\n/**\n * SEND-ONLY (pl-iza). The same read as {@link listReferralContactsForPartner},\n * with the confidential holders as a {@link ConfidentialReferralRecipients}\n * instead of a bare count. Call it at send time, server-side, and hand\n * `confidential.deliver` the mailer; never return the result to a browser\n * beyond `confidential.count` (its `toJSON` is `{ count }`). This is the only\n * way to obtain a `ConfidentialReferralRecipients` (the implementation is\n * not exported).\n *\n * Canon: CVC-338 `REFERRALS_MAGIC_LINK` (prototype\n * `data/cvcs/core_contact_purpose.yaml` @ 184893b6 L95): \"A confidential\n * holder still receives it; the sender never sees the address.\"\n */\nexport async function resolveMagicLinkRecipients(\n db: PocDbLike,\n partner: PocPartnerSelector,\n opts: ReferralContactsOptions,\n): Promise<MagicLinkSendList> {\n const holders = await readReferralHolders(db, partner, opts);\n return {\n recipients: holders.recipients,\n unreachable: holders.unreachable,\n confidential: new ConfidentialHolders(holders.confidentialAddresses),\n confidentialUnreachableCount: holders.confidentialUnreachableCount,\n };\n}\n\n/**\n * Sends one magic link to one address. It must THROW (or reject) on failure;\n * returning normally counts as delivered. It must not log, persist or return\n * `address`.\n */\nexport type ConfidentialSendOne = (address: string) => void | Promise<void>;\n\nexport interface ConfidentialDeliverOptions {\n /** At most this many sends (a non-negative integer); the rest are `overflow`. Unlimited when omitted. */\n capacity?: number;\n}\n\n/**\n * A confidential delivery's outcome: numbers and an error class name, never an\n * address. SERVER-SIDE, for audit only: a sender may see `count`, or one\n * all-or-nothing status derived from it, never `delivered`, `failed`,\n * `overflow` or `firstErrorName`.\n */\nexport interface ConfidentialDeliveryResult {\n /** The holder count (`delivered + failed + overflow`). */\n count: number;\n delivered: number;\n failed: number;\n /** Holders beyond `capacity`, not sent: `max(0, count - capacity)`. */\n overflow: number;\n /** The first failed send's `err.name` (never its message, which can echo the address), or null. */\n firstErrorName: string | null;\n}\n\nconst SAFE_ERROR_NAME = /^[A-Za-z_$][\\w$.-]{0,63}$/;\n\n/**\n * An error's class name only. Anything that is not a plain identifier, or a\n * `name` that cannot be read (a throwing getter, a revoked proxy), reads \"Error\".\n */\nfunction errorName(err: unknown): string {\n try {\n if (err === null || (typeof err !== \"object\" && typeof err !== \"function\")) return \"Error\";\n const name: unknown = (err as { name?: unknown }).name;\n return typeof name === \"string\" && SAFE_ERROR_NAME.test(name) ? name : \"Error\";\n } catch {\n return \"Error\";\n }\n}\n\n/**\n * A partner's confidential Referrals (magic link) holders (pl-iza). It carries\n * their addresses privately and exposes only `count`: `toJSON()` is\n * `{ count }`, `util.inspect` draws `ConfidentialReferralRecipients(n)`, and\n * no public member returns an address. Only {@link deliver} touches them,\n * handing each to the caller's `sendOne`.\n *\n * An interface, exported as a type only. The implementation is not\n * exported: obtain values only via {@link resolveMagicLinkRecipients}.\n */\nexport interface ConfidentialReferralRecipients {\n readonly count: number;\n /**\n * Sends to the first `capacity` holders (all when omitted), one at a time.\n * The outcome depends only on the holders, `capacity` and each send's\n * result, never on any address the caller handled: an address the sender\n * also typed is sent again, so nothing observable moves when one matches.\n * Never rejects for a failed send: each error is caught and only its `name`\n * is kept (a provider's message can echo the address). The result is\n * server-side only (see {@link ConfidentialDeliveryResult}).\n */\n deliver(\n sendOne: ConfidentialSendOne,\n opts?: ConfidentialDeliverOptions,\n ): Promise<ConfidentialDeliveryResult>;\n /** `{ count }`: what a response, a record or an event may carry. */\n toJSON(): { count: number };\n /** `ConfidentialReferralRecipients(n)`. */\n toString(): string;\n}\n\n/** The one implementation (not exported). */\nclass ConfidentialHolders implements ConfidentialReferralRecipients {\n readonly count: number;\n readonly #addresses: readonly string[];\n\n constructor(addresses: readonly string[]) {\n this.#addresses = Object.freeze([...addresses]);\n this.count = this.#addresses.length;\n Object.freeze(this);\n }\n\n /** See {@link ConfidentialReferralRecipients.deliver}. */\n async deliver(\n sendOne: ConfidentialSendOne,\n opts: ConfidentialDeliverOptions = {},\n ): Promise<ConfidentialDeliveryResult> {\n const { capacity } = opts;\n if (capacity !== undefined && !(Number.isInteger(capacity) && capacity >= 0)) {\n throw new TypeError(\"points-of-contact: capacity must be a non-negative integer\");\n }\n const toSend = capacity === undefined ? this.#addresses : this.#addresses.slice(0, capacity);\n const out: ConfidentialDeliveryResult = {\n count: this.count,\n delivered: 0,\n failed: 0,\n overflow: this.count - toSend.length,\n firstErrorName: null,\n };\n for (const address of toSend) {\n try {\n await sendOne(address);\n out.delivered++;\n } catch (err) {\n out.failed++;\n out.firstErrorName ??= errorName(err);\n }\n }\n return out;\n }\n\n /** `{ count }`: what a response, a record or an event may carry. */\n toJSON(): { count: number } {\n return { count: this.count };\n }\n\n toString(): string {\n return `ConfidentialReferralRecipients(${this.count})`;\n }\n\n [Symbol.for(\"nodejs.util.inspect.custom\")](): string {\n return this.toString();\n }\n}\n\n/** An outstanding in-app add, visible to its own adder only (and never when confidential). */\nconst OWN_PENDING_IN_APP = {\n active: true,\n status: \"pending\",\n origin: \"in_app\",\n is_confidential: { $ne: true },\n} as const;\n\nconst isOwnPendingInApp = (d: PointOfContactDoc, sub: string) =>\n d.active &&\n d.status === \"pending\" &&\n d.origin === \"in_app\" &&\n !d.is_confidential &&\n !d.user_id &&\n d.createdBy === sub &&\n d.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE);\n\n/** A confidential holder that receives magic links (pl-iza): active, confirmed, confidential. */\nconst CONFIDENTIAL_CONFIRMED = { active: true, status: \"confirmed\", is_confidential: true } as const;\n\nconst isConfidentialHolder = (d: PointOfContactDoc) =>\n d.active &&\n d.status === \"confirmed\" &&\n d.is_confidential &&\n d.purposes.includes(REFERRALS_MAGIC_LINK_PURPOSE);\n\n/** One contact as other organizations see it, or null (absent or not network-visible). */\nexport async function getContact(\n db: PocDbLike,\n id: string,\n opts: { resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactNetworkView | null> {\n const raw = await db.collection(POINTS_OF_CONTACT_COLLECTION).findOne({ id: requireId(\"id\", id) });\n if (!raw) return null;\n const d = normalizePointOfContact(rowOf(raw));\n return networkViews([d], await seatsFor([d], opts.resolveSeats))[0] ?? null;\n}\n\n/**\n * The OWNER read: every contact on the subject, unmasked, every status\n * (pending included), confidential included, seats resolved; inactive rows\n * only when asked. Callers gate it on the actor owning the subject.\n */\nexport async function listOwnerContactsForSubject(\n db: PocDbLike,\n subject: PocSubjectRef,\n opts: { includeInactive?: boolean; resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactOwnerView[]> {\n const docs = await findDocs(db, {\n ...subjectFilter(subject),\n ...(opts.includeInactive ? {} : { active: true }),\n });\n const seats = await seatsFor(docs, opts.resolveSeats);\n return docs.map((d) => toOwnerView(d, seatOf(d, seats)));\n}\n\n/** The STEWARD's review queue: every pending contact, seats resolved. */\nexport async function listPendingContacts(\n db: PocDbLike,\n opts: { resolveSeats?: SeatResolver } = {},\n): Promise<PointOfContactStewardView[]> {\n const docs = await findDocs(db, { status: \"pending\" });\n const seats = await seatsFor(docs, opts.resolveSeats);\n return docs.map((d) => toStewardView(d, seatOf(d, seats)));\n}\n","/**\n * The in-app partner add, shared (pl-bt1, pl-e98): an advocate in Thread, PAVE\n * or LEADS names a partner on a share and the contact they type lands in\n * platform-db `pointsofcontact` as a PENDING Point of contact tagged Referrals\n * (magic link). Every app runs THIS implementation against its own platform-db\n * handle; there is no HTTP hop. It is the platform's `addPartnerContact`\n * (platform `lib/points-of-contact/repository.ts`, the store behind\n * `POST /api/partner-contacts`) and the internals it uses from\n * `lib/points-of-contact/core.ts` (`resolveOwner` for an agency or org\n * subject, `insertContact`, the index set, the duplicate-key mapping) and\n * `lib/sharing-settings/recipient-id.ts` (`resolveRecipientId`), moved here\n * with the same rules, the same order of checks and the same refusal codes.\n *\n * ## What it does, in order\n *\n * 1. The actor names the advocate (`actor_required`), the app is one of\n * {@link POC_PARTNER_ADD_APPS} (`invalid_app`), the contact is a strict\n * {@link PocInAppSchema} body (`invalid_contact`), always tagged Referrals\n * (magic link) first.\n * 2. The partner is a strict {@link PartnerContactSelectorSchema} selector\n * (`invalid_partner`), resolved to its owner (decision D1): an agency in any\n * accepted form (`entity_id`, `id`, `_id` in either stored shape, a mapped\n * `registry_agencies` row) becomes `String(agencies._id)`; an org is\n * `String(organizations._id)`. An org whose org GENUINELY mirrors an\n * agency puts the contact on that agency (kickoff D1). Unresolved:\n * `owner_not_found`; an agency and org that are not one partner:\n * `owner_mismatch`. A canonical singleton org (`canonical_org`) or a PAVE\n * 2.0-shape org (`foreign_row_shape`) is refused.\n * 3. What already exists answers the add, looking only at rows the caller may\n * know about, matched on the package identity rule ({@link pocIdentityKey}:\n * `writein:<name>|<preferred email>`), never on a shared email: a visible\n * tagged contact, else the caller's own pending add (both `created:\n * false`, no write); the caller's own add that the partner removed is\n * refused (`contact_deactivated`).\n * 4. The caller's outstanding pending adds are capped per partner\n * ({@link POC_IN_APP_PENDING_CAP_PER_PARTNER}) and across the network\n * ({@link POC_IN_APP_PENDING_CAP_PER_ACTOR}): `too_many_pending_adds`.\n * 5. The row is inserted `pending`, `origin: in_app`, `added_in_app: <app>`,\n * version 1, after the whole-contact rules ({@link pocRuleViolations})\n * and the index check ({@link checkPocIndexes}: the writer never creates\n * an index; a missing one is `indexes_missing`, 503). A simultaneous\n * identical add that won the insert (`duplicate_pending_add`) answers with\n * the winner's row; an add that finds a cap exceeded after its insert\n * withdraws itself (429).\n *\n * ## The caller's part\n *\n * The full contract is the package README (\"Caller contract\"). In short:\n * `actor.id` is the advocate's Auth0 `sub`, taken server-side from the\n * verified token, never from a request body; `app` is the caller's own server\n * constant and the caller checks the advocate's `allowed_apps` for it; the\n * handle is the deployment's own platform-db, long-lived, reading from the\n * primary; `now` is never taken from a request. The platform's own write\n * guard (`read_only_registry`) is not here.\n *\n * ## No driver import, no logging\n *\n * Like the reads, the handle is typed structurally ({@link PocWriteDbLike}):\n * a `mongodb` `Db` or a mongoose connection's `.db` fits. The driver's\n * `ObjectId` class is passed in ({@link PocWriterDriver}): it builds the\n * ObjectId form of a 24-hex id (production `agencies._id` and\n * `organizations._id` are ObjectIds) and mints the `poc-<hex>` id. Nothing is\n * logged: a domain refusal is a returned code, never a throw, and no message\n * carries a stored value (a contact's email, a driver error's duplicate key).\n * A read or write ERROR (an outage, a stored row that does not parse,\n * `PointOfContactShapeError`) propagates.\n */\n\nimport { z } from \"zod\";\n\nimport { isAgencyOwnOrganization } from \"../orgDirectory/rules.js\";\nimport {\n AGENCIES_COLLECTION,\n ORGANIZATIONS_COLLECTION,\n readAgencyOwnOrganization,\n readDirectoryOrganization,\n type OrgDirectoryReadOptions,\n} from \"../orgDirectory/read.js\";\nimport type { PocDbLike } from \"./reader.js\";\nimport { normalizePointOfContact } from \"./readRules.js\";\nimport {\n POC_IDENTITY_INDEX_FILTER,\n POC_IN_APP_PENDING_INDEX_FILTER,\n POC_IN_APP_PENDING_INDEX_KEY,\n POC_PRIMARY_INDEX_FILTER,\n POINTS_OF_CONTACT_COLLECTION,\n POINT_OF_CONTACT_INDEXES,\n PocInAppSchema,\n pocIdentityKey,\n pocRuleViolations,\n type PocInApp,\n type PocInAppInput,\n type PocOwner,\n type PointOfContactDoc,\n} from \"./schemas.js\";\nimport {\n POC_ADDED_IN_APPS,\n REFERRALS_MAGIC_LINK_PURPOSE,\n pocInitialStatus,\n type PocAddedInApp,\n type PocStatus,\n} from \"./vocabulary.js\";\n\n// ─── Handle and driver ───────────────────────────────────────────────\n\n/** The slice of a driver cursor the writer uses. */\nexport interface PocWriteCursorLike {\n toArray(): Promise<unknown[]>;\n}\n\n/** One entry of a driver `indexes()` (`listIndexes`) listing. */\nexport interface PocIndexInfoLike {\n name?: unknown;\n key?: unknown;\n unique?: unknown;\n partialFilterExpression?: unknown;\n}\n\n/** The options the writer passes to `createIndex`. */\nexport interface PocCreateIndexOptions {\n name: string;\n unique?: boolean;\n partialFilterExpression?: Record<string, unknown>;\n}\n\n/** The slice of a driver `Collection` the writer uses. */\nexport interface PocWriteCollectionLike {\n find(filter: Record<string, unknown>, options?: Record<string, unknown>): PocWriteCursorLike;\n findOne(filter: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;\n countDocuments(filter: Record<string, unknown>): Promise<number>;\n insertOne(doc: Record<string, unknown>): Promise<unknown>;\n deleteOne(filter: Record<string, unknown>): Promise<unknown>;\n /** Used by the platform's {@link ensurePocIndexes} only; the writer never creates an index. */\n createIndex(key: Record<string, 1 | -1>, options: PocCreateIndexOptions): Promise<unknown>;\n indexes(): Promise<PocIndexInfoLike[]>;\n}\n\n/** The slice of a driver `Db` the writer uses: a platform-db handle the caller may write. */\nexport interface PocWriteDbLike {\n collection(name: string): PocWriteCollectionLike;\n}\n\n/** The driver's ObjectId class (`mongodb`'s `ObjectId`, or `mongoose.Types.ObjectId`). */\nexport interface PocObjectIdClass {\n new (hex?: string): { toHexString(): string };\n}\n\n/** What the writer needs from the caller's driver. */\nexport interface PocWriterDriver {\n ObjectId: PocObjectIdClass;\n}\n\n// ─── Vocabulary of the in-app add ────────────────────────────────────\n\n/** The apps an in-app add may come from: {@link POC_ADDED_IN_APPS} less `platform`. */\nexport type PocPartnerAddApp = Exclude<PocAddedInApp, \"platform\">;\nexport const POC_PARTNER_ADD_APPS = POC_ADDED_IN_APPS.filter(\n (a): a is PocPartnerAddApp => a !== \"platform\",\n) as readonly PocPartnerAddApp[];\n\nconst directoryId = z.string().trim().min(1).max(200);\n\n/**\n * The partner the advocate picked or created, in the directory id universe\n * (D1): `agency_id` = `String(agencies._id)` or any form that resolves to it,\n * `org_id` = `String(organizations._id)`. One key, or both when they are a\n * genuine mirror pair. The same keys as `listReferralContactsForPartner`, so\n * an app writes and reads one partner the same way. Strict: a subject the\n * body picks is refused.\n */\nexport const PartnerContactSelectorSchema = z\n .object({ agency_id: directoryId.optional(), org_id: directoryId.optional() })\n .strict()\n .refine((p) => Boolean(p.agency_id || p.org_id), {\n message: \"Name the partner's agency_id or org_id.\",\n });\nexport type PartnerContactSelector = z.infer<typeof PartnerContactSelectorSchema>;\nexport type PartnerContactSelectorInput = z.input<typeof PartnerContactSelectorSchema>;\n\n/** Outstanding (pending, active) in-app adds one adder may have across the network. */\nexport const POC_IN_APP_PENDING_CAP_PER_ACTOR = 25;\n/** Outstanding (pending, active) in-app adds one adder may have on one partner. */\nexport const POC_IN_APP_PENDING_CAP_PER_PARTNER = 5;\n\n// ─── Indexes ─────────────────────────────────────────────────────────\n\n/**\n * One outstanding in-app add per adder, per subject and identity\n * ({@link POC_IN_APP_PENDING_INDEX_KEY}: the stored `identity_key`, name +\n * preferred email). Two simultaneous identical first adds race to the insert;\n * the loser's E11000 maps to `duplicate_pending_add`, which\n * {@link mintPartnerContact} answers with the winner's row: the index and the\n * matcher ({@link pocRowsWithIdentity}) use the same key, so the re-read always\n * finds the winner.\n *\n * Not keyed on emails: people share mailboxes (`intake@`), and a\n * \"shares ANY email\" rule (an interim 0.30.0 platform build, multikey on\n * `emails.value`) answered one person's add with another's row and let a\n * removed row block every later add sharing a secondary mailbox.\n */\nexport const POC_IN_APP_PENDING_INDEX = POINT_OF_CONTACT_INDEXES.inAppPending;\n/** The steward's review queue, paged oldest first (platform `listPendingContacts`). */\nexport const POC_PENDING_QUEUE_INDEX = POINT_OF_CONTACT_INDEXES.pendingQueue;\n\nconst indexRuns = new WeakMap<object, Promise<void>>();\n\n/**\n * FOR THE PLATFORM (its deploy or boot), never an app's writer: Thread and\n * PAVE hold no index privilege, and {@link mintPartnerContact} only checks\n * the indexes ({@link checkPocIndexes}). The platform must deploy and run this\n * before any app writes.\n *\n * Create the `pointsofcontact` indexes, the platform's full set: plain\n * `createIndex` calls, idempotent (memoized per handle, retried after a\n * failure; a failure propagates). No migration: no data or index existed\n * before 0.30.0. The partial unique indexes are the store's uniqueness rules:\n * no twin of one person among a subject's visible rows, at most one visible\n * primary per subject, and one outstanding in-app add per adder, subject and\n * identity ({@link POC_IN_APP_PENDING_INDEX}). Pass a long-lived handle: the\n * memo is keyed on it.\n */\nexport function ensurePocIndexes(db: PocWriteDbLike): Promise<void> {\n const memo = indexRuns.get(db);\n if (memo) return memo;\n const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);\n const ix = POINT_OF_CONTACT_INDEXES;\n const run = (async () => {\n await coll.createIndex({ id: 1 }, { name: ix.id, unique: true });\n await coll.createIndex({ subject_type: 1, subject_id: 1, active: 1 }, { name: ix.subject });\n await coll.createIndex({ agency_id: 1, purposes: 1, active: 1 }, { name: ix.agencyPurpose });\n await coll.createIndex({ org_id: 1, purposes: 1, active: 1 }, { name: ix.orgPurpose });\n await coll.createIndex({ status: 1 }, { name: ix.status });\n await coll.createIndex(\n { agency_id: 1, subject_type: 1, subject_id: 1, identity_key: 1 },\n {\n name: ix.identity,\n unique: true,\n partialFilterExpression: { ...POC_IDENTITY_INDEX_FILTER },\n },\n );\n await coll.createIndex(\n { agency_id: 1, subject_type: 1, subject_id: 1 },\n { name: ix.primary, unique: true, partialFilterExpression: { ...POC_PRIMARY_INDEX_FILTER } },\n );\n await coll.createIndex(\n { ...POC_IN_APP_PENDING_INDEX_KEY },\n {\n name: POC_IN_APP_PENDING_INDEX,\n unique: true,\n partialFilterExpression: { ...POC_IN_APP_PENDING_INDEX_FILTER },\n },\n );\n await coll.createIndex({ status: 1, createdAt: 1, id: 1 }, { name: POC_PENDING_QUEUE_INDEX });\n })().catch((err) => {\n indexRuns.delete(db);\n throw err;\n });\n indexRuns.set(db, run);\n return run;\n}\n\nconst indexesChecked = new WeakMap<object, true>();\n\nconst codeOf = (err: unknown) =>\n err && typeof err === \"object\" ? (err as { code?: unknown }).code : undefined;\n/** NamespaceNotFound: `listIndexes` on a collection that does not exist. */\nconst NAMESPACE_NOT_FOUND = 26;\n\nconst sameKey = (got: unknown, want: Record<string, number>) => {\n if (!got || typeof got !== \"object\") return false;\n const g = Object.entries(got);\n const w = Object.entries(want);\n return g.length === w.length && w.every(([k, v], i) => g[i][0] === k && Number(g[i][1]) === v);\n};\n\nconst sameFilter = (got: unknown, want: Record<string, unknown> | undefined) => {\n if (!want) return got === undefined || got === null;\n if (!got || typeof got !== \"object\") return false;\n const sorted = (o: object) =>\n JSON.stringify(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : 1)));\n return sorted(got) === sorted(want);\n};\n\n/** The indexes the writer's guarantees rest on: the `id` and in-app pending unique indexes. */\nconst REQUIRED_INDEXES: { key: Record<string, number>; filter?: Record<string, unknown> }[] = [\n { key: { id: 1 } },\n { key: { ...POC_IN_APP_PENDING_INDEX_KEY }, filter: { ...POC_IN_APP_PENDING_INDEX_FILTER } },\n];\n\n/**\n * Whether the indexes the writer relies on exist, read through `listIndexes`\n * (the writer never creates one: least privilege; the platform creates them\n * with {@link ensurePocIndexes}). Each required index must exist with exactly\n * its key (fields, order, direction), `unique: true` and exactly its partial\n * filter (under any name): `id` unique, and {@link POC_IN_APP_PENDING_INDEX}\n * (the race recovery and the dedupe depend on it). A missing collection\n * (NamespaceNotFound) or index refuses the write, `indexes_missing` (503):\n * fail closed. A pass is memoized per handle; a refusal is not, so the next\n * add re-checks. Any other read error propagates.\n */\nexport async function checkPocIndexes(db: PocWriteDbLike): Promise<PartnerContactFailure | null> {\n if (indexesChecked.has(db)) return null;\n let listed: PocIndexInfoLike[];\n try {\n listed = await db.collection(POINTS_OF_CONTACT_COLLECTION).indexes();\n } catch (err) {\n if (codeOf(err) === NAMESPACE_NOT_FOUND) return INDEXES_MISSING;\n throw err;\n }\n const present = REQUIRED_INDEXES.every((want) =>\n listed.some(\n (ix) =>\n ix.unique === true &&\n sameKey(ix.key, want.key) &&\n sameFilter(ix.partialFilterExpression, want.filter),\n ),\n );\n if (!present) return INDEXES_MISSING;\n indexesChecked.set(db, true);\n return null;\n}\n\n// ─── Results ─────────────────────────────────────────────────────────\n\n/** Every refusal {@link mintPartnerContact} can return, as the platform route answers them. */\nexport const PARTNER_CONTACT_FAILURE_REASONS = [\n \"actor_required\",\n \"invalid_app\",\n \"invalid_contact\",\n \"invalid_partner\",\n \"owner_not_found\",\n \"owner_mismatch\",\n \"canonical_org\",\n \"foreign_row_shape\",\n \"contact_deactivated\",\n \"too_many_pending_adds\",\n \"duplicate_pending_add\",\n \"duplicate_contact\",\n \"primary_exists\",\n \"duplicate_contact_id\",\n \"duplicate_key\",\n \"user_id_xor_person_id\",\n \"seat_contact_has_own_reach\",\n \"display_name_required\",\n \"referral_contact_needs_email\",\n \"indexes_missing\",\n] as const;\nexport type PartnerContactFailureReason = (typeof PARTNER_CONTACT_FAILURE_REASONS)[number];\n\n/**\n * A domain refusal: `status` is the HTTP status the platform route answers it\n * with, `reason` its code, `message` a fixed human sentence, or for\n * `invalid_contact` / `invalid_partner` the schema's issue list (paths and\n * rule messages). Never a stored value.\n */\nexport interface PartnerContactFailure {\n ok: false;\n status: 400 | 409 | 429 | 503;\n reason: PartnerContactFailureReason;\n message?: string;\n}\n\n/** What an in-app add returns to the app: the contact's id and status, never another org's contact details. */\nexport interface PartnerContactReceipt {\n id: string;\n status: PocStatus;\n /** False when an equivalent contact already existed and nothing was written. */\n created: boolean;\n /** Where the store put it: the partner's agency when the org has a genuine-mirror agency (kickoff D1), else the org. */\n subject_type: PocOwner[\"subject_type\"];\n subject_id: string;\n agency_id: string | null;\n org_id: string | null;\n}\n\nexport type PartnerContactResult =\n | { ok: true; value: PartnerContactReceipt }\n | PartnerContactFailure;\n\nfunction fail(\n status: PartnerContactFailure[\"status\"],\n reason: PartnerContactFailureReason,\n message?: string,\n): PartnerContactFailure {\n return { ok: false, status, reason, ...(message ? { message } : {}) };\n}\n\nconst INDEXES_MISSING = fail(\n 503,\n \"indexes_missing\",\n \"The points-of-contact indexes are not in place; the platform must create them (ensurePocIndexes) before an app writes.\",\n);\n\nconst isFailure = (v: unknown): v is PartnerContactFailure =>\n !!v && typeof v === \"object\" && (v as { ok?: unknown }).ok === false;\n\nfunction invalid(\n err: z.ZodError,\n reason: \"invalid_contact\" | \"invalid_partner\",\n): PartnerContactFailure {\n const issues = err.issues.map((i) => `${i.path.map(String).join(\".\") || \"(body)\"}: ${i.message}`);\n return fail(400, reason, issues.join(\"; \"));\n}\n\n// ─── Ids ─────────────────────────────────────────────────────────────\n\nconst HEX_24 = /^[0-9a-fA-F]{24}$/;\n/** A 24-hex id in one spelling (lowercase), as `String(ObjectId)` prints it. */\nconst canonicalId = (v: string): string => (HEX_24.test(v) ? v.toLowerCase() : v);\nconst idOf = (v: unknown): string | null =>\n v === null || v === undefined || v === \"\" ? null : String(v);\n\ninterface Ids {\n /** Every stored form of one id: the string, plus its ObjectId when 24-hex. Feed to `$in`. */\n forms(value: string): unknown[];\n /** The org-directory reads' ObjectId factory. */\n read: OrgDirectoryReadOptions;\n /** A fresh `poc-<24 hex>` id. */\n newId(): string;\n}\n\nfunction idsOf(driver: PocWriterDriver): Ids {\n const { ObjectId } = driver;\n return {\n forms: (value) => (HEX_24.test(value) ? [value, new ObjectId(value)] : [value]),\n read: { toObjectId: (hex) => new ObjectId(hex) },\n newId: () => `poc-${new ObjectId().toHexString()}`,\n };\n}\n\n// ─── Agency resolution (platform `resolveRecipientId`) ───────────────\n\nconst REGISTRY_AGENCIES_COLLECTION = \"registry_agencies\";\nconst AGENCY_PROJECTION = { projection: { _id: 1, entity_id: 1, id: 1 } };\n\ninterface AgencyRowLike {\n _id?: unknown;\n entity_id?: unknown;\n id?: unknown;\n}\n\n/** Every string form that names a row: `entity_id`, `id`, `String(_id)`. */\nfunction formsOf(row: AgencyRowLike): string[] {\n const out: string[] = [];\n if (typeof row.entity_id === \"string\" && row.entity_id !== \"\") out.push(row.entity_id);\n if (typeof row.id === \"string\" && row.id !== \"\") out.push(row.id);\n if (row._id !== undefined && row._id !== null) out.push(String(row._id));\n return [...new Set(out)];\n}\n\n/** The three-id-universe agency match: `entity_id`, `id`, or `_id` in either stored form. */\nconst agencyIdFilter = (ids: Ids, agencyId: string): Record<string, unknown> => ({\n $or: [{ entity_id: agencyId }, { id: agencyId }, { _id: { $in: ids.forms(agencyId) } }],\n});\n\n/** First an `agencies` row the form names; else a registry row it names, mapped to the `agencies` row carrying one of its forms. */\nfunction resolveRecipient(\n form: string,\n agencies: readonly AgencyRowLike[],\n registry: readonly AgencyRowLike[],\n): string | null {\n const direct = agencies.find((a) => formsOf(a).includes(form));\n if (direct) return String(direct._id);\n const reg = registry.find((r) => formsOf(r).includes(form));\n if (!reg) return null;\n const regForms = formsOf(reg);\n const mapped = agencies.find((a) => formsOf(a).some((f) => regForms.includes(f)));\n return mapped ? String(mapped._id) : null;\n}\n\n/**\n * `String(_id)` of the platform-db `agencies` row a form names, or null. The\n * registry (`registry_agencies`) is read from the same handle: the platform\n * writes only when its registry handle IS platform-db. Read errors propagate.\n */\nasync function resolveAgencyId(db: PocWriteDbLike, ids: Ids, form: string): Promise<string | null> {\n const agencies = db.collection(AGENCIES_COLLECTION);\n const direct = (await agencies\n .find(agencyIdFilter(ids, form), AGENCY_PROJECTION)\n .toArray()) as AgencyRowLike[];\n if (direct.length > 0) return resolveRecipient(form, direct, []);\n const registry = (await db\n .collection(REGISTRY_AGENCIES_COLLECTION)\n .find(agencyIdFilter(ids, form), AGENCY_PROJECTION)\n .toArray()) as AgencyRowLike[];\n if (registry.length === 0) return null;\n const regForms = formsOf(registry[0]);\n const mapped = (await agencies\n .find({ $or: regForms.map((f) => agencyIdFilter(ids, f)) }, AGENCY_PROJECTION)\n .toArray()) as AgencyRowLike[];\n return resolveRecipient(form, mapped, registry);\n}\n\n/** The stored agency key of a form, canonical, or null. */\nasync function agencyKey(db: PocWriteDbLike, ids: Ids, form: string): Promise<string | null> {\n const id = await resolveAgencyId(db, ids, canonicalId(form));\n return id ? canonicalId(id) : null;\n}\n\n// ─── Owner (platform `resolveOwner`, agency and org subjects) ────────\n\nconst OWNER_NOT_FOUND = fail(\n 400,\n \"owner_not_found\",\n \"The contact's owner does not resolve to a platform agency or organization.\",\n);\nconst OWNER_MISMATCH = fail(\n 400,\n \"owner_mismatch\",\n \"The agency and organization named are not the same partner.\",\n);\n\n/** The agency whose OWN organization `org` is (both halves of the pair), or null. */\nasync function genuineMirrorAgency(\n db: PocWriteDbLike,\n ids: Ids,\n org: Record<string, unknown>,\n): Promise<string | null> {\n const declared = idOf(org.agencyId);\n if (!declared) return null;\n const agency = (await db\n .collection(AGENCIES_COLLECTION)\n .findOne(\n { _id: { $in: ids.forms(canonicalId(declared)) } },\n { projection: { _id: 1, organizationId: 1 } },\n )) as { _id?: unknown; organizationId?: unknown } | null;\n if (!agency || !isAgencyOwnOrganization(org, agency)) return null;\n return agencyKey(db, ids, String(agency._id));\n}\n\n/**\n * The selector → the stored owner. An agency names the agency subject (an org\n * named with it must be its genuine mirror); an org alone names the org\n * subject, rewritten to its genuine-mirror agency when it has one (kickoff\n * D1). Rows carry the other key only when the pair is a genuine mirror.\n */\nasync function resolvePartnerOwner(\n db: PocWriteDbLike,\n ids: Ids,\n p: PartnerContactSelector,\n): Promise<PocOwner | PartnerContactFailure> {\n let agencyId: string | null = null;\n if (p.agency_id) {\n agencyId = await agencyKey(db, ids, p.agency_id);\n if (!agencyId) return OWNER_NOT_FOUND;\n }\n\n let org: Record<string, unknown> | null = null;\n if (p.org_id) {\n org = (await db\n .collection(ORGANIZATIONS_COLLECTION)\n .findOne(\n { _id: { $in: ids.forms(canonicalId(p.org_id)) } },\n { projection: { _id: 1, agencyId: 1 } },\n )) as Record<string, unknown> | null;\n if (!org) return OWNER_NOT_FOUND;\n }\n const orgId = org ? canonicalId(String(org._id)) : null;\n\n if (!agencyId) {\n if (!org || !orgId) return OWNER_NOT_FOUND;\n const mirrorAgency = await genuineMirrorAgency(db, ids, org);\n if (mirrorAgency) {\n return {\n subject_type: \"agency\",\n subject_id: mirrorAgency,\n agency_id: mirrorAgency,\n org_id: orgId,\n };\n }\n return { subject_type: \"org\", subject_id: orgId, agency_id: null, org_id: orgId };\n }\n\n const own = await readAgencyOwnOrganization(db, agencyId, ids.read);\n const mirrorOrg = own ? canonicalId(own.id) : null;\n if (orgId && orgId !== mirrorOrg) return OWNER_MISMATCH;\n return { subject_type: \"agency\", subject_id: agencyId, agency_id: agencyId, org_id: mirrorOrg };\n}\n\n/**\n * The partner's organization row must be one an in-app add may name: never a\n * canonical singleton (Unknown, Anonymous) and never a PAVE 2.0-shape row, the\n * shapes the org directory also refuses (`organizationRowShape`).\n */\nasync function refuseForeignPartnerOrg(\n db: PocWriteDbLike,\n ids: Ids,\n orgId: string | null,\n): Promise<PartnerContactFailure | null> {\n if (!orgId) return null;\n const org = await readDirectoryOrganization(db, orgId, ids.read);\n if (org?.shape === \"canonical\") {\n return fail(409, \"canonical_org\", \"A canonical singleton organization is not a partner.\");\n }\n if (org?.shape === \"pave\") {\n return fail(\n 409,\n \"foreign_row_shape\",\n \"This organization is a PAVE 2.0-shape row; an in-app contact is not added to it.\",\n );\n }\n return null;\n}\n\n// ─── Existing rows ───────────────────────────────────────────────────\n\n/**\n * The rows on the resolved subject with this identity ({@link pocIdentityKey},\n * as stored in `identity_key`), any status or activity: the same key as\n * {@link POC_IN_APP_PENDING_INDEX}, so a raced add always finds the row that\n * won. The index and this matcher must agree, which is why both live here.\n * A row that does not parse throws.\n */\nexport async function pocRowsWithIdentity(\n db: PocDbLike,\n owner: Pick<PocOwner, \"agency_id\" | \"subject_type\" | \"subject_id\">,\n identityKey: string,\n): Promise<PointOfContactDoc[]> {\n const raw = await db\n .collection(POINTS_OF_CONTACT_COLLECTION)\n .find({\n agency_id: owner.agency_id,\n subject_type: owner.subject_type,\n subject_id: owner.subject_id,\n identity_key: identityKey,\n })\n .toArray();\n return raw\n .map((r) => normalizePointOfContact(r as Record<string, unknown>))\n .filter((d) => d.identity_key === identityKey);\n}\n\n/** The add's identity: a write-in, keyed on its name and preferred email. */\nconst identityOf = (body: PocInApp) =>\n pocIdentityKey({\n user_id: null,\n person_id: null,\n display_name: body.display_name,\n emails: body.emails,\n });\n\nconst ownInApp = (d: PointOfContactDoc, actorId: string) =>\n d.origin === \"in_app\" && d.createdBy === actorId;\n\n/**\n * What an in-app add of `body` on the resolved subject already is, looking\n * only at rows the caller may know about (no oracle for the rest):\n * - `visible`: an active, confirmed, not confidential contact with the same\n * identity that already carries every purpose asked for. Preferred.\n * - `own_pending`: the caller's own outstanding in-app add of the identity.\n * - `own_deactivated`: the caller's own in-app add of the identity that the\n * partner (or the steward) has since removed. Re-adding it is refused.\n * Another adder's pending row, a confidential contact, a contact without the\n * purposes and a contact someone else removed never match: such an add lands\n * as a new pending row, the steward's duplicate to resolve.\n */\nfunction classifyExisting(rows: PointOfContactDoc[], body: PocInApp, actorId: string) {\n const visible = rows.find(\n (d) =>\n d.active &&\n d.status === \"confirmed\" &&\n !d.is_confidential &&\n body.purposes.every((p) => d.purposes.includes(p)),\n );\n if (visible) return { kind: \"visible\" as const, doc: visible };\n const pending = rows.find((d) => d.active && d.status === \"pending\" && ownInApp(d, actorId));\n if (pending) return { kind: \"own_pending\" as const, doc: pending };\n const removed = rows.find((d) => !d.active && ownInApp(d, actorId));\n if (removed) return { kind: \"own_deactivated\" as const, doc: removed };\n return null;\n}\n\n// ─── Caps ────────────────────────────────────────────────────────────\n\n/** The adder's two caps: outstanding pending in-app adds on this partner, and across the network. */\nfunction pendingCaps(owner: PocOwner, actorId: string) {\n const mine = { createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER };\n return [\n {\n filter: {\n ...mine,\n agency_id: owner.agency_id,\n subject_type: owner.subject_type,\n subject_id: owner.subject_id,\n },\n cap: POC_IN_APP_PENDING_CAP_PER_PARTNER,\n refusal: fail(\n 429,\n \"too_many_pending_adds\",\n `At most ${POC_IN_APP_PENDING_CAP_PER_PARTNER} contacts you added to one partner can wait for HTI Labs at a time.`,\n ),\n },\n {\n filter: mine,\n cap: POC_IN_APP_PENDING_CAP_PER_ACTOR,\n refusal: fail(\n 429,\n \"too_many_pending_adds\",\n `At most ${POC_IN_APP_PENDING_CAP_PER_ACTOR} contacts you added can wait for HTI Labs at a time.`,\n ),\n },\n ];\n}\n\n/** The early refusal: the adder is already at a cap before inserting. */\nasync function checkPendingCaps(\n db: PocWriteDbLike,\n owner: PocOwner,\n actorId: string,\n): Promise<PartnerContactFailure | null> {\n const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);\n for (const c of pendingCaps(owner, actorId)) {\n if ((await coll.countDocuments(c.filter)) >= c.cap) return c.refusal;\n }\n return null;\n}\n\n/**\n * The binding check, after the insert: the count above and the insert are\n * not atomic, so parallel adds can all pass it. Each new row counts the\n * adder's pending rows (per partner, then across the network) AFTER its own\n * insert; over the cap, it deletes itself and the add is 429. This bounds\n * the outcome at the cap: every surviving row counted at most `cap` rows, and\n * the survivor that counted last counted every survivor (each was inserted\n * before its own count), so no more than `cap` survive. The price is a\n * spurious 429 under contention (a burst may withdraw rows that would have\n * fit; a retry then lands). It holds only if every count reads the primary\n * (README \"Caller contract\"). The row was never acknowledged to anyone, so\n * this is not the \"deactivate, never delete\" removal of a contact.\n */\nasync function overCapAfterInsert(\n db: PocWriteDbLike,\n owner: PocOwner,\n actorId: string,\n id: string,\n): Promise<PartnerContactFailure | null> {\n const coll = db.collection(POINTS_OF_CONTACT_COLLECTION);\n for (const c of pendingCaps(owner, actorId)) {\n if ((await coll.countDocuments(c.filter)) > c.cap) {\n await coll.deleteOne({ id, createdBy: actorId, ...POC_IN_APP_PENDING_INDEX_FILTER });\n return c.refusal;\n }\n }\n return null;\n}\n\n// ─── Insert ──────────────────────────────────────────────────────────\n\n/**\n * A duplicate-key error → the refusal for the index it hit, or null when the\n * error is not a duplicate key (the caller rethrows). Mapped per index by\n * name, then by key pattern. The driver's message is never returned: it\n * echoes the duplicate key, i.e. the contact's email.\n */\nexport function pocDuplicateKeyFailure(err: unknown): PartnerContactFailure | null {\n if (!err || typeof err !== \"object\") return null;\n const e = err as { code?: unknown; message?: unknown; keyPattern?: Record<string, unknown> };\n const msg = typeof e.message === \"string\" ? e.message : \"\";\n if (e.code !== 11000 && !/E11000/.test(msg)) return null;\n const ix = POINT_OF_CONTACT_INDEXES;\n const keys = Object.keys(e.keyPattern ?? {}).join(\",\");\n if (msg.includes(POC_IN_APP_PENDING_INDEX) || keys.includes(\"createdBy\")) {\n return fail(\n 409,\n \"duplicate_pending_add\",\n \"This adder already has a pending add of this person on this subject.\",\n );\n }\n if (msg.includes(ix.primary) || keys === \"agency_id,subject_type,subject_id\") {\n return fail(\n 409,\n \"primary_exists\",\n \"The subject already has a primary contact. Use setPrimary to move it.\",\n );\n }\n if (msg.includes(ix.identity) || keys.includes(\"identity_key\")) {\n return fail(409, \"duplicate_contact\", \"This person is already an active contact on this subject.\");\n }\n if (msg.includes(ix.id) || keys === \"id\") {\n return fail(409, \"duplicate_contact_id\", \"A contact with this id exists.\");\n }\n return fail(409, \"duplicate_key\", \"The contact collides with a unique index.\");\n}\n\n/**\n * Build, check and insert one in-app contact: `active`, version 1, `pending`\n * (D3: `pocInitialStatus(\"in_app\")`), unstamped, no seat or person link, not\n * primary, not confidential, no notes.\n */\nasync function insertInAppContact(\n db: PocWriteDbLike,\n f: {\n id: string;\n owner: PocOwner;\n body: PocInApp;\n app: PocPartnerAddApp;\n actorId: string;\n now: Date;\n },\n): Promise<{ ok: true; value: PointOfContactDoc } | PartnerContactFailure> {\n const at = f.now.toISOString();\n const base = {\n user_id: null,\n person_id: null,\n display_name: f.body.display_name,\n emails: f.body.emails,\n phones: f.body.phones ?? [],\n };\n const doc: PointOfContactDoc = {\n id: f.id,\n subject_type: f.owner.subject_type,\n subject_id: f.owner.subject_id,\n agency_id: f.owner.agency_id,\n org_id: f.owner.org_id,\n ...base,\n purposes: f.body.purposes,\n urgent_methods: f.body.urgent_methods ?? [],\n is_primary: false,\n is_confidential: false,\n active: true,\n notes: null,\n status: pocInitialStatus(\"in_app\"),\n origin: \"in_app\",\n added_in_app: f.app,\n identity_key: pocIdentityKey(base),\n confirmed_by: null,\n confirmed_at: null,\n deactivated_by: null,\n deactivated_at: null,\n version: 1,\n createdBy: f.actorId,\n createdAt: at,\n updatedBy: f.actorId,\n updatedAt: at,\n };\n\n const [broken] = pocRuleViolations(doc);\n if (broken) return fail(400, broken.reason, broken.message);\n\n const noIndexes = await checkPocIndexes(db);\n if (noIndexes) return noIndexes;\n try {\n await db.collection(POINTS_OF_CONTACT_COLLECTION).insertOne({ ...doc });\n } catch (err) {\n const dup = pocDuplicateKeyFailure(err);\n if (dup) return dup;\n throw err;\n }\n return { ok: true, value: doc };\n}\n\n// ─── The writer ──────────────────────────────────────────────────────\n\n/** Who is adding: the advocate. Never a steward here. */\nexport interface PocInAppActor {\n /**\n * The advocate's Auth0 `sub`, taken SERVER-SIDE from the verified token\n * (as the platform route takes `auth0Sub`), never from a request body or a\n * client-supplied header. Stored as `createdBy`; the adder's dedupe, caps and\n * removed-add refusal key on it.\n */\n id: string;\n}\n\nexport interface MintPartnerContactArgs {\n /** The app the advocate is adding from. */\n app: PocPartnerAddApp;\n /** The partner, by directory id ({@link PartnerContactSelectorSchema}). */\n partner: PartnerContactSelectorInput;\n /** The contact ({@link PocInAppSchema}: a name and at least one email; phones optional). */\n contact: PocInAppInput;\n actor: PocInAppActor;\n /** The mint time (`createdAt`); defaults to now. Server time only, never from a request. */\n now?: Date;\n}\n\n/**\n * An in-app add is ALWAYS tagged Referrals (magic link) (Crysta 2026-10-14;\n * kickoff D1): an explicit `[]` or a list without it gets it added in front;\n * any other purposes asked for are kept.\n */\nfunction withReferralTag(purposes: PocInApp[\"purposes\"]): PocInApp[\"purposes\"] {\n return [\n REFERRALS_MAGIC_LINK_PURPOSE,\n ...purposes.filter((p) => p !== REFERRALS_MAGIC_LINK_PURPOSE),\n ];\n}\n\n/**\n * The in-app partner add, written straight to platform-db (module comment).\n * Every argument is validated at run time as well as typed. Returns a\n * {@link PartnerContactReceipt} (`created: true` for a new pending row,\n * `false` when an equivalent contact answered and nothing was written) or a\n * {@link PartnerContactFailure}; never throws a domain refusal.\n */\nexport async function mintPartnerContact(\n db: PocWriteDbLike,\n args: MintPartnerContactArgs,\n driver: PocWriterDriver,\n): Promise<PartnerContactResult> {\n const actor = args.actor as unknown;\n const actorId =\n actor && typeof actor === \"object\" ? (actor as { id?: unknown }).id : undefined;\n if (typeof actorId !== \"string\" || actorId.trim().length === 0) {\n return fail(400, \"actor_required\", \"An in-app add names the advocate (their Auth0 sub).\");\n }\n if (!(POC_PARTNER_ADD_APPS as readonly unknown[]).includes(args.app)) {\n return fail(400, \"invalid_app\", `An in-app add names its app: ${POC_PARTNER_ADD_APPS.join(\", \")}.`);\n }\n const parsed = PocInAppSchema.safeParse(args.contact);\n if (!parsed.success) return invalid(parsed.error, \"invalid_contact\");\n const body: PocInApp = { ...parsed.data, purposes: withReferralTag(parsed.data.purposes) };\n const partner = PartnerContactSelectorSchema.safeParse(args.partner);\n if (!partner.success) return invalid(partner.error, \"invalid_partner\");\n\n const ids = idsOf(driver);\n const owner = await resolvePartnerOwner(db, ids, partner.data);\n if (isFailure(owner)) return owner;\n const foreign = await refuseForeignPartnerOrg(db, ids, owner.org_id);\n if (foreign) return foreign;\n\n const receipt = (d: PointOfContactDoc, created: boolean): PartnerContactResult => ({\n ok: true,\n value: {\n id: d.id,\n status: d.status,\n created,\n subject_type: owner.subject_type,\n subject_id: owner.subject_id,\n agency_id: owner.agency_id,\n org_id: owner.org_id,\n },\n });\n const existingNow = async () =>\n classifyExisting(await pocRowsWithIdentity(db, owner, identityOf(body)), body, actorId);\n\n const existing = await existingNow();\n if (existing?.kind === \"own_deactivated\") {\n return fail(\n 409,\n \"contact_deactivated\",\n \"You added this contact before and it has since been removed from the partner; it is not added again.\",\n );\n }\n if (existing) return receipt(existing.doc, false);\n\n const capped = await checkPendingCaps(db, owner, actorId);\n if (capped) return capped;\n\n const r = await insertInAppContact(db, {\n id: ids.newId(),\n owner,\n body,\n app: args.app,\n actorId,\n now: args.now ?? new Date(),\n });\n if (!r.ok) {\n if (r.reason !== \"duplicate_pending_add\") return r;\n // A simultaneous identical add won the insert: answer with its row.\n const raced = await existingNow();\n return raced && raced.kind !== \"own_deactivated\" ? receipt(raced.doc, false) : r;\n }\n const overCap = await overCapAfterInsert(db, owner, actorId, r.value.id);\n if (overCap) return overCap;\n return receipt(r.value, true);\n}\n","/**\n * The stored program row of `organizations.programs[]`, as a Zod schema for\n * readers. The Mongoose definition (`schemas/organization-program.ts`,\n * `organizationProgramSchemaDefinition`) is the write-side twin; a test holds\n * the key lists equal.\n */\n\nimport { z } from \"zod\";\n\nimport { PROGRAM_REVIEW_STATUS_VALUES } from \"./vocabulary.js\";\n\n/** The program row's keys, in the fragment's declaration order. */\nexport const ORGANIZATION_PROGRAM_ROW_KEYS = Object.freeze([\n \"programId\",\n \"name\",\n \"description\",\n \"status\",\n \"defaultSharingPolicy\",\n \"reviewStatus\",\n \"addedBy\",\n \"addedInApp\",\n \"addedInSession\",\n \"programType\",\n \"serviceArea\",\n \"providesRelevantServices\",\n \"operatingStartDate\",\n \"operatingEndDate\",\n \"locationId\",\n \"notes\",\n \"teamId\",\n \"teamIds\",\n] as const);\n\nexport type OrganizationProgramRowKey = (typeof ORGANIZATION_PROGRAM_ROW_KEYS)[number];\n\nconst optionalText = z.string().nullish();\n/**\n * A detail field of the Program record. A value of the wrong kind reads as not\n * on record (`undefined`) rather than failing the row: a malformed detail must\n * never hide a program from a picker. `./programDetails.ts` shapes the values.\n */\nconst detailText = z.string().nullish().catch(undefined);\n\n/**\n * One stored program row. `programId` + `name` are required; the rest are\n * optional and may be null. Unknown keys are stripped (a reader never relies\n * on a key outside the fragment). The seven Program-record detail keys\n * (`programType` … `notes`, 0.76.0) and the team link (`teamId`, `teamIds`,\n * 0.86.0) never fail the row: a value of the wrong kind reads as not on record.\n */\nexport const OrganizationProgramRowSchema = z.object({\n programId: z.string().min(1),\n name: z.string().min(1),\n description: optionalText,\n status: optionalText,\n defaultSharingPolicy: optionalText,\n reviewStatus: z\n .enum(PROGRAM_REVIEW_STATUS_VALUES as unknown as [\"pending\", \"confirmed\", \"rejected\"])\n .nullish(),\n addedBy: optionalText,\n addedInApp: optionalText,\n addedInSession: optionalText,\n programType: detailText,\n serviceArea: detailText,\n providesRelevantServices: z.boolean().nullish().catch(undefined),\n operatingStartDate: detailText,\n operatingEndDate: detailText,\n locationId: detailText,\n notes: detailText,\n /** The first team that works for the program (canon `team_id`). */\n teamId: detailText,\n /** Every team that works for the program (canon `team_ids`). */\n teamIds: z.array(z.string()).nullish().catch(undefined),\n});\n\nexport type OrganizationProgramRow = z.infer<typeof OrganizationProgramRowSchema>;\n","/**\n * The program-row vocabulary of `organizations.programs[]`: the review\n * lifecycle, the lifecycle codes, the live rule and the name key. Pure (no\n * mongoose): `schemas/organization-program.ts` re-exports these, so the\n * Mongoose fragment and the `org-directory` read contract share one source.\n */\n\n// ─── Review status ──────────────────────────────────────────────────\n\n/**\n * Review lifecycle of a program named inside an app (UDD Program\n * `review_status`). The sheet's own words — a lane's `pending_steward` /\n * `declined` never reach the stored row.\n */\nexport const PROGRAM_REVIEW_STATUS = {\n PENDING: \"pending\",\n CONFIRMED: \"confirmed\",\n REJECTED: \"rejected\",\n} as const;\n\nexport type ProgramReviewStatus =\n (typeof PROGRAM_REVIEW_STATUS)[keyof typeof PROGRAM_REVIEW_STATUS];\n\n/** The three values, for `enum:` declarations and Zod `z.enum`. */\nexport const PROGRAM_REVIEW_STATUS_VALUES = Object.freeze([\n PROGRAM_REVIEW_STATUS.PENDING,\n PROGRAM_REVIEW_STATUS.CONFIRMED,\n PROGRAM_REVIEW_STATUS.REJECTED,\n] as const);\n\nexport function isProgramReviewStatus(value: unknown): value is ProgramReviewStatus {\n return (\n typeof value === \"string\" && (PROGRAM_REVIEW_STATUS_VALUES as readonly string[]).includes(value)\n );\n}\n\n// ─── Lifecycle status ───────────────────────────────────────────────\n\n/**\n * The program lifecycle codes the writers store. `active` is what PAVE 2.0's\n * `POST /organizations/:id/programs` writes; `retired` takes a program out of\n * every picker. Absent reads as active.\n */\nexport const PROGRAM_STATUS = {\n ACTIVE: \"active\",\n RETIRED: \"retired\",\n} as const;\n\nexport type ProgramStatus = (typeof PROGRAM_STATUS)[keyof typeof PROGRAM_STATUS];\n\nexport const PROGRAM_STATUS_VALUES = Object.freeze([\n PROGRAM_STATUS.ACTIVE,\n PROGRAM_STATUS.RETIRED,\n] as const);\n\n// ─── Live rule and name key ─────────────────────────────────────────\n\n/**\n * Whether a program row may be OFFERED (and matched by name on an add).\n * A retired or rejected program is not a place anyone can be enrolled today,\n * so pickers do not list it and typing its name mints a new row rather than\n * binding to it (the prototype's independent pre-review catch, 2026-10-06).\n */\nexport function isLiveOrganizationProgram(row: {\n status?: string | null | undefined;\n reviewStatus?: string | null | undefined;\n}): boolean {\n return (\n row.status !== PROGRAM_STATUS.RETIRED && row.reviewStatus !== PROGRAM_REVIEW_STATUS.REJECTED\n );\n}\n\n/**\n * The key two program names match on: trimmed, lower-cased. Canon:\n * `directoryProgramFor` (platform-prototype `src/surveys.jsx` L4233 @\n * `0fa04c1`); PAVE 2.0's `POST /organizations/:id/programs` dedupes the same\n * way.\n */\nexport function programNameKey(name: string): string {\n return name.trim().toLowerCase();\n}\n","/**\n * The Org record: the ONE definition of what an `organizations` row holds\n * about an organization, for every app that reads or writes the platform-wide\n * registry (Thread, PAVE, the Platform, auth). Pure: no mongoose, no driver.\n * The Mongoose twin is `schemas/organization.ts` (`addOrgRecordFields`); a\n * package test holds the two key lists equal.\n *\n * ## Canon\n *\n * UDD Org Data Object (Notion `7d71ef14abcd832fa3a6816ebe7a5dd9`, § 1 and § 5;\n * schema of record hti-features `udd-schemas/org/Org.v1.json`): an Org is one\n * real-world organization in the one platform-wide registry. It holds its name\n * (legal and common), its acronym, its required type, its parent when it is a\n * unit of a larger one, the two HMIS victim-service-provider answers, and how\n * it arrived and whether HTI Labs has reviewed it. Crysta, 2026-11-10: \"It\n * shouldn't be different in thread vs. pave. And the data objects for Org need\n * to be the same in both apps.\"\n *\n * ## Stored names\n *\n * The UDD spells these snake_case (`legal_name`, `parent_org_id`, ...). The\n * live platform-db writers use camelCase, so the stored names are the UDD's in\n * camelCase, as for the org-type fields (`schemas/agency.ts`) and the program\n * row (`schemas/organization-program.ts`). Two exceptions. The UDD `acronym` is\n * stored as `shortName`: a top-level `acronym` key marks a pre-pl-958 PAVE row\n * (`organizationRowShape`), and PAVE 2.0 already writes `shortName`. And the\n * UDD `id` (the Org's one identifier, a slug such as `the_spring`) is stored as\n * `key`: Mongoose gives every document an `id` of its own (the `_id` as a\n * string), and the Admin Hub's curated store already names it `key`.\n *\n * ## What is NOT here\n *\n * - `name` and `type`: every writer already stores them. `type` is mid-move\n * from the IC-58 number to the CVC-48 key and each app validates the\n * transition form itself until the migration has run.\n * - The row's tenancy and plumbing (`agencyScope`, `agencyId`, `community`,\n * `canonicalKey`, `status`, `programs`, contact fields): unchanged by this\n * module. {@link ORGANIZATION_ROW_KEYS} lists them so a model can be checked\n * against the whole row.\n */\nimport { z } from \"zod\";\n\nimport {\n PROGRAM_REVIEW_STATUS,\n PROGRAM_REVIEW_STATUS_VALUES,\n type ProgramReviewStatus,\n} from \"./vocabulary.js\";\n\n// ─── Review status ──────────────────────────────────────────────────\n\n/**\n * Review lifecycle of an organization added from inside an app. The same three\n * words, and the same lifecycle, as a program named inside an app (UDD Org\n * § 5 \"how it arrived\"; census item 2: \"the same lifecycle a program named\n * inside an app has\"). Absent on a steward row: nothing to review.\n */\nexport const ORG_REVIEW_STATUS = PROGRAM_REVIEW_STATUS;\nexport const ORG_REVIEW_STATUS_VALUES = PROGRAM_REVIEW_STATUS_VALUES;\nexport type OrgReviewStatus = ProgramReviewStatus;\n\n// ─── Lifecycle status ───────────────────────────────────────────────\n\n/**\n * `organizations.status`: 1 active, 2 inactive (soft-deleted; never removed).\n * The codes auth, Thread and PAVE already store.\n */\nexport const ORGANIZATION_STATUS = { ACTIVE: 1, INACTIVE: 2 } as const;\nexport type OrganizationStatus = (typeof ORGANIZATION_STATUS)[keyof typeof ORGANIZATION_STATUS];\n\n/**\n * Whether an organization may be OFFERED in a picker: active (an absent\n * `status` reads active, as legacy rows carry none) and not declined by HTI\n * Labs. A pending organization IS offered: an organization added inside an app\n * is available everywhere from the moment it is added (UDD Org § 2 scenario 1).\n * A stored reference to an organization that is no longer offered still\n * resolves by id.\n */\nexport function isListedOrganization(row: {\n status?: number | null | undefined;\n reviewStatus?: string | null | undefined;\n}): boolean {\n const active = row.status == null || row.status === ORGANIZATION_STATUS.ACTIVE;\n return active && row.reviewStatus !== ORG_REVIEW_STATUS.REJECTED;\n}\n\n// ─── The record's fields ────────────────────────────────────────────\n\n/**\n * The Org definition's fields beyond `name` and `type`, in the Mongoose\n * fragment's declaration order (`orgRecordSchemaDefinition`).\n */\nexport const ORG_RECORD_FIELD_NAMES = Object.freeze([\n \"key\",\n \"legalName\",\n \"commonName\",\n \"shortName\",\n \"website\",\n \"parentOrgId\",\n \"vsp\",\n \"vspPrivateNonprofit\",\n \"reviewStatus\",\n \"addedInApp\",\n \"addedBy\",\n] as const);\nexport type OrgRecordFieldName = (typeof ORG_RECORD_FIELD_NAMES)[number];\n\n/**\n * Stored on the row today and NOT part of the Org definition (UDD Org § 5,\n * \"As built today, and not part of this definition\"; Org.v1's runtime-overlay\n * five: `isCustom`, `added_in_session`, `added_by_user_id`, `type_override`,\n * `division`). PAVE 2.0 writes them; every model declares\n * them so no app silently drops another app's value. `typeKey` is the CVC-48\n * key PAVE writes beside a numeric `type` and retires with the type migration.\n */\nexport const ORG_AS_BUILT_FIELD_NAMES = Object.freeze([\n \"requiresROI\",\n \"isCustom\",\n \"addedByUserId\",\n \"addedInSession\",\n \"division\",\n \"typeOverride\",\n \"typeKey\",\n] as const);\nexport type OrgAsBuiltFieldName = (typeof ORG_AS_BUILT_FIELD_NAMES)[number];\n\n/** The row's keys every writer already stored before this module. */\nexport const ORGANIZATION_BASE_ROW_KEYS = Object.freeze([\n \"name\",\n \"type\",\n \"phones\",\n \"emails\",\n \"address\",\n \"notes\",\n \"status\",\n \"agencyScope\",\n \"agencyId\",\n \"community\",\n \"canonicalKey\",\n \"isAnonymous\",\n \"programs\",\n] as const);\n\n/**\n * Every top-level key of a shared-shape `organizations` row, the record\n * envelope aside. A model that declares exactly these is the same data object\n * as every other app's (`organizationSchemaIssues`, `schemas/organization.ts`).\n */\nexport const ORGANIZATION_ROW_KEYS = Object.freeze([\n ...ORGANIZATION_BASE_ROW_KEYS,\n ...ORG_RECORD_FIELD_NAMES,\n ...ORG_AS_BUILT_FIELD_NAMES,\n] as const);\nexport type OrganizationRowKey = (typeof ORGANIZATION_ROW_KEYS)[number];\n\n/** The record envelope each app's base document adds; never Org facts. */\nexport const ORGANIZATION_ENVELOPE_KEYS = Object.freeze([\n \"_id\",\n \"__v\",\n \"_schemaVersion\",\n \"createdUser\",\n \"createdTime\",\n \"updatedUser\",\n \"updatedTime\",\n] as const);\n\n// ─── The identifier ─────────────────────────────────────────────────\n\n/**\n * The Org's identifier (UDD Org `id`; stored as `key`): the one value that\n * names the same organization in every database, where `_id` is each\n * database's own. A lower-case slug: `the_spring`, `ascension_stjohn`,\n * `org-custom-8daxtira`, `org-6a1f5dadd0c33a5a149f3413`.\n *\n * Rules (the curated store's, Kickoff 13 item 3): unique; never changes once\n * set; never taken from a request body (`OrgIdentityWriteSchema` is strict and\n * does not name it); a new organization's key never encodes its name\n * ({@link mintOrgKey}). A row written before 0.65.0 has none until the\n * registry fill stamps one from a reviewed sheet.\n */\nexport const ORG_KEY_PATTERN = /^[a-z0-9][a-z0-9_-]{0,119}$/;\n\n/** Whether a value is a well-formed Org identifier. */\nexport function isOrgKey(value: unknown): value is string {\n return typeof value === \"string\" && ORG_KEY_PATTERN.test(value);\n}\n\n/**\n * The identifier for an organization created without one (added inside an\n * app, or by a steward typing a new organization): `org-<its _id>`. It encodes\n * no name, so a later rename never makes it wrong.\n */\nexport function mintOrgKey(id: string | { toHexString(): string }): string {\n const hex = (typeof id === \"string\" ? id : id.toHexString()).trim().toLowerCase();\n if (!/^[0-9a-f]{24}$/.test(hex)) {\n throw new Error(\"mintOrgKey: needs the organization's 24-hex _id\");\n }\n return `org-${hex}`;\n}\n\n// ─── Write shape ────────────────────────────────────────────────────\n\n/** A trimmed, non-empty line of text, or null to clear the field. */\nconst line = (max: number) => z.string().trim().min(1).max(max).nullable();\n\n/** The two-step message; the same sentence the Mongoose mount throws. */\nexport const ORG_VSP_TWO_STEP_MESSAGE =\n \"vspPrivateNonprofit is step 2 of the HMIS VSP two-step and requires vsp: true\";\n\n/**\n * The identity half of the record, as a request body may carry it. Every key\n * is optional (a PATCH names only what it changes); `null` clears a field.\n * Strict: an unknown key is refused, so a snake_case spelling never passes as\n * a silent no-op.\n */\nexport const OrgIdentityWriteSchema = z\n .object({\n legalName: line(300),\n commonName: line(300),\n shortName: line(60),\n website: line(500),\n /** Another organization's id (24-hex or a seed slug). Self-reference is the writer's check. */\n parentOrgId: line(120),\n })\n .partial()\n .strict();\nexport type OrgIdentityWrite = z.infer<typeof OrgIdentityWriteSchema>;\n\n/**\n * The two HMIS victim-service-provider answers. Tri-state: `null` is \"not yet\n * captured\", never a coerced false. Step 2 may be answered only with step 1\n * `true` in the same body (an update cannot see the stored row), and a body\n * that sets step 1 to `false` or `null` clears step 2 with it. Only HTI Labs\n * sets them (UDD Org rulings 2026-10-08 and 2026-10-09); the route decides who\n * that is.\n */\nexport const OrgVspWriteSchema = z\n .object({\n vsp: z.boolean().nullable(),\n vspPrivateNonprofit: z.boolean().nullable(),\n })\n .partial()\n .strict()\n .refine((v) => v.vspPrivateNonprofit == null || v.vsp === true, {\n message: ORG_VSP_TWO_STEP_MESSAGE,\n path: [\"vspPrivateNonprofit\"],\n })\n // Step 1 set to anything but `true` clears step 2 in the same write, so a\n // stored \"yes\" on step 2 can never outlive its step 1.\n .transform((v) => (\"vsp\" in v && v.vsp !== true ? { ...v, vspPrivateNonprofit: null } : v));\nexport type OrgVspWrite = z.infer<typeof OrgVspWriteSchema>;\n\n/**\n * How an organization arrived. Never taken from a request body: the server\n * stamps it from the authenticated caller ({@link orgArrivalStamp}).\n *\n * The same three facts, under the same names, as a Program, a Service Listing\n * and a Point of contact carry (`added_by` · `added_in_app` · `review_status`;\n * UDD ratification request R17, \"how an organization arrived\"). The older\n * runtime-overlay names on the row (`addedByUserId`, `isCustom`) are as-built\n * extras; `addedInSession` is carried as on the program row.\n */\nexport interface OrgArrival {\n reviewStatus: OrgReviewStatus;\n /** The app the organization was added in: `thread`, `pave`, `leads`, `platform`. */\n addedInApp: string;\n /** The adding user's platform `users._id`, as a string. */\n addedBy: string;\n /** The session it was added in, when there was one. */\n addedInSession?: string;\n}\n\n/**\n * The arrival stamp for an organization a user adds from inside an app: it is\n * on the list at once and waits for HTI Labs' review (UDD Org § 2 scenario 5;\n * census item 2). A steward's own add carries no stamp.\n */\nexport function orgArrivalStamp(input: {\n app: string;\n userId: string;\n sessionId?: string | null | undefined;\n}): OrgArrival {\n const app = input.app.trim().toLowerCase();\n const userId = input.userId.trim();\n if (!app) throw new Error(\"orgArrivalStamp: app is required\");\n if (!userId) throw new Error(\"orgArrivalStamp: userId is required\");\n const session = input.sessionId?.trim();\n return {\n reviewStatus: ORG_REVIEW_STATUS.PENDING,\n addedInApp: app,\n addedBy: userId,\n ...(session ? { addedInSession: session } : {}),\n };\n}\n\n// ─── Naming rules ───────────────────────────────────────────────────\n\ninterface OrgNames {\n name?: string | null | undefined;\n commonName?: string | null | undefined;\n legalName?: string | null | undefined;\n shortName?: string | null | undefined;\n}\n\nconst clean = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\");\n\n/**\n * The name to use when a sentence or a label names an organization: its common\n * name when it has one, else its name. Canon: the prototype's contact-history\n * register and referral wording (`org.common_name || org.name`).\n */\nexport function orgCommonName(org: OrgNames | null | undefined): string {\n return clean(org?.commonName) || clean(org?.name);\n}\n\n/**\n * The name a report to a funder or HMIS uses: the legal name when captured,\n * else the name (Org.v1 `legal_name`: \"consumers fall back to name when blank\").\n */\nexport function orgLegalName(org: OrgNames | null | undefined): string {\n return clean(org?.legalName) || clean(org?.name);\n}\n\n/** Whether a row's name is nothing but its short name (\"ASJS\" named \"ASJS\"). */\nexport function isShortNameOnly(org: OrgNames | null | undefined): boolean {\n const n = clean(org?.name);\n const a = clean(org?.shortName);\n return !n || (!!a && n.toLowerCase() === a.toLowerCase());\n}\n\n/**\n * How a unit of a larger organization reads: its own name, and \"<parent> unit\"\n * beneath it when the unit has no name beyond its short name (Crysta\n * 2026-09-03, \"No names yet — show the parent\"). A row with a real name keeps\n * it. Canon: the prototype's one resolver, `orgDisplayParts`.\n */\nexport function orgDisplayParts(\n org: OrgNames | null | undefined,\n parent: OrgNames | null | undefined,\n): { name: string; sub: string } {\n const name = clean(org?.name) || clean(org?.shortName);\n const parentName = clean(parent?.name) || clean(parent?.shortName);\n const sub = parentName && isShortNameOnly(org) ? `${parentName} unit` : \"\";\n return { name, sub };\n}\n\n/** {@link orgDisplayParts} on one line: \"ASJS · Ascension St. John Medical Center unit\". */\nexport function orgDisplayName(\n org: OrgNames | null | undefined,\n parent?: OrgNames | null | undefined,\n): string {\n const d = orgDisplayParts(org, parent);\n return d.sub ? `${d.name} · ${d.sub}` : d.name;\n}\n\n/**\n * Why `parentOrgId` may not be set to this value, or null when it may. One\n * level only (the picker folds units under their organization): an\n * organization is never its own parent, a parent is not itself a unit, and an\n * organization that has units cannot become one.\n */\nexport function orgParentIssue(input: {\n orgId: string | null | undefined;\n parentOrgId: string | null | undefined;\n /** The proposed parent's own `parentOrgId`, when the parent row was read. */\n parentsParentOrgId?: string | null | undefined;\n /** Whether any organization already names `orgId` as its parent. */\n hasUnits?: boolean | undefined;\n}): \"self\" | \"parent_is_unit\" | \"org_has_units\" | null {\n const parent = clean(input.parentOrgId).toLowerCase();\n if (!parent) return null;\n if (clean(input.orgId).toLowerCase() === parent) return \"self\";\n if (clean(input.parentsParentOrgId)) return \"parent_is_unit\";\n if (input.hasUnits) return \"org_has_units\";\n return null;\n}\n","/**\n * The Program record's own fields beyond its name, on a stored\n * `organizations.programs[]` row: what kind of program it is, where it\n * serves, whether it provides direct services to victims, when it operates,\n * which of its organization's sites it works from, and notes.\n *\n * Canon: the UDD Program Data Object (`program_type` · `service_area` ·\n * `provides_relevant_services` · `operating_start_date` ·\n * `operating_end_date` · `location_id` · `notes`; profile confirmed by Crysta\n * 2026-10-05) and the Admin Hub's program editor (platform-prototype\n * `src/screens.jsx`, `OrgProgramFields`). Stored camelCase, like the rest of\n * the row. The Platform's program editor has written these since 2026-11-11\n * (platform #148, #155); this module is the Platform's own reader and write\n * shapes (`lib/org-directory/program-details.ts`) made shared, so Thread, PAVE\n * and the Platform read and validate one program the same way.\n *\n * The rules it carries:\n *\n * - NOT ON RECORD IS NULL. Every field is optional. A value of the wrong\n * kind reads as not on record; it never fails the program row.\n * - `providesRelevantServices` has three states: true, false, and null\n * (never asked). Null is never coerced to No.\n * - A date is a real calendar day, `YYYY-MM-DD`, stored as a string.\n * - `programType` is a key of the organization-type codebook (CVC-48\n * `core-referral_entity_category`). This subpath stays free of the\n * codebook, so the reader returns the stored string and the write check\n * takes the caller's type rule: resolve a read with `resolveOrgTypeKey`\n * (`@htilabs/platform-common-models/constants`) and offer only\n * `ORG_TYPE_SELECTABLE_KEYS`.\n * - `locationId` names a site of the program's OWN organization. Whether it\n * is one is the writer's check (it needs the database); the write check\n * here only bounds the string.\n *\n * NO ZOD HERE, on purpose. This package is built with zod 3; the Platform and\n * Thread run zod 4, and a zod-3 field cannot be nested in a zod-4 object. So\n * the write rules are plain data (`PROGRAM_DETAIL_RULES`) and one plain\n * function (`checkProgramDetails`) that any app wraps in its own schema\n * library.\n *\n * Pure: no mongoose, no driver, no codebook import, no schema library.\n */\n\n/** The detail keys, in the program editor's field order. */\nexport const PROGRAM_DETAIL_KEYS = Object.freeze([\n \"programType\",\n \"serviceArea\",\n \"providesRelevantServices\",\n \"operatingStartDate\",\n \"operatingEndDate\",\n \"locationId\",\n \"notes\",\n] as const);\nexport type ProgramDetailKey = (typeof PROGRAM_DETAIL_KEYS)[number];\n\n/** A program's detail fields as a reader sees them (`null` = not on record). */\nexport interface ProgramDetails {\n /** The stored organization-type key (CVC-48), unresolved; null when absent. */\n programType: string | null;\n /** Free text: the service area or jurisdiction. */\n serviceArea: string | null;\n /** Direct services to victims: true, false, or null (never asked; not a No). */\n providesRelevantServices: boolean | null;\n /** A calendar day, `YYYY-MM-DD`. */\n operatingStartDate: string | null;\n /** A calendar day, `YYYY-MM-DD`. */\n operatingEndDate: string | null;\n /** The id of the organization's site the program works from, or null. */\n locationId: string | null;\n notes: string | null;\n}\n\n/** The longest service area the editor stores. */\nexport const PROGRAM_SERVICE_AREA_MAX = 200;\n/** The longest program note the editor stores. */\nexport const PROGRAM_NOTES_MAX = 4000;\n/** The longest site id a program row stores. */\nexport const PROGRAM_LOCATION_ID_MAX = 200;\n\nconst DAY = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** A real calendar day in `YYYY-MM-DD` (what a date input sends). */\nexport function isCalendarDay(v: unknown): v is string {\n if (typeof v !== \"string\" || !DAY.test(v)) return false;\n const [y, m, d] = v.split(\"-\").map(Number) as [number, number, number];\n const t = new Date(Date.UTC(y, m - 1, d));\n return t.getUTCFullYear() === y && t.getUTCMonth() === m - 1 && t.getUTCDate() === d;\n}\n\nconst text = (v: unknown): string | null =>\n typeof v === \"string\" && v.trim() ? v.trim() : null;\n\n/**\n * One stored row's detail fields. A value of the wrong kind (a date that is\n * not a calendar day, a non-boolean answer, a blank string) reads as not on\n * record. `programType` is returned as stored (trimmed), not resolved.\n */\nexport function programDetailsOf(raw: unknown): ProgramDetails {\n const r = raw && typeof raw === \"object\" ? (raw as Record<string, unknown>) : {};\n return {\n programType: text(r.programType),\n serviceArea: text(r.serviceArea),\n providesRelevantServices:\n typeof r.providesRelevantServices === \"boolean\" ? r.providesRelevantServices : null,\n operatingStartDate: isCalendarDay(r.operatingStartDate) ? r.operatingStartDate : null,\n operatingEndDate: isCalendarDay(r.operatingEndDate) ? r.operatingEndDate : null,\n locationId: text(r.locationId),\n notes: text(r.notes),\n };\n}\n\n// ─── Write rules (plain data and one plain function; no schema library) ─────\n\n/** What kind of value a detail field holds. */\nexport type ProgramDetailKind = \"orgType\" | \"text\" | \"yesNo\" | \"calendarDay\" | \"siteId\";\n\n/** One detail field's write rule. `maxLength` is counted after trimming. */\nexport interface ProgramDetailRule {\n readonly kind: ProgramDetailKind;\n readonly maxLength?: number;\n}\n\n/**\n * The write rule of every detail field. On every field: an ADD may leave the\n * key out (not on record) and may not send `null`; an EDIT may leave the key\n * out (unchanged) or send `null` (clear the field). Text is trimmed and may\n * not be blank.\n */\nexport const PROGRAM_DETAIL_RULES: Readonly<Record<ProgramDetailKey, ProgramDetailRule>> =\n Object.freeze({\n programType: Object.freeze({ kind: \"orgType\" }),\n serviceArea: Object.freeze({ kind: \"text\", maxLength: PROGRAM_SERVICE_AREA_MAX }),\n providesRelevantServices: Object.freeze({ kind: \"yesNo\" }),\n operatingStartDate: Object.freeze({ kind: \"calendarDay\" }),\n operatingEndDate: Object.freeze({ kind: \"calendarDay\" }),\n locationId: Object.freeze({ kind: \"siteId\", maxLength: PROGRAM_LOCATION_ID_MAX }),\n notes: Object.freeze({ kind: \"text\", maxLength: PROGRAM_NOTES_MAX }),\n } as const);\n\n/** `create`: a program ADD. `patch`: a program EDIT, where `null` clears. */\nexport type ProgramDetailsWriteMode = \"create\" | \"patch\";\n\nexport type ProgramDetailErrorCode =\n | \"null_on_create\"\n | \"wrong_kind\"\n | \"blank\"\n | \"too_long\"\n | \"not_a_calendar_day\"\n | \"type_not_offered\";\n\n/** One refused field of a program write. */\nexport interface ProgramDetailError {\n readonly field: ProgramDetailKey;\n readonly code: ProgramDetailErrorCode;\n readonly message: string;\n}\n\n/**\n * The cleaned detail fields of a write: ONLY the keys the body carried. An\n * absent key is not written. `null` (an edit only) clears the field.\n */\nexport interface ProgramDetailsWrite {\n programType?: string | null;\n serviceArea?: string | null;\n providesRelevantServices?: boolean | null;\n operatingStartDate?: string | null;\n operatingEndDate?: string | null;\n locationId?: string | null;\n notes?: string | null;\n}\n\nexport interface ProgramDetailsCheckOptions {\n readonly mode: ProgramDetailsWriteMode;\n /**\n * The caller's rule for an offered organization type: the key to store, or\n * `null` when the value is not a type a person may choose. Required, because\n * this subpath does not import the codebook (the Platform passes its\n * `offeredWriteKey`).\n */\n readonly programType: (value: unknown) => string | null | undefined;\n}\n\nexport type ProgramDetailsCheck =\n | { readonly ok: true; readonly details: ProgramDetailsWrite }\n | { readonly ok: false; readonly errors: readonly ProgramDetailError[] };\n\nconst MESSAGES: Readonly<Record<ProgramDetailErrorCode, string>> = Object.freeze({\n null_on_create: \"Leave the field out when there is nothing to record.\",\n wrong_kind: \"That value is not the right kind for this field.\",\n blank: \"Leave the field out, or clear it, rather than sending it blank.\",\n too_long: \"That text is too long for this field.\",\n not_a_calendar_day: \"A date is a calendar day, YYYY-MM-DD.\",\n type_not_offered: \"That is not a program type a person can choose.\",\n});\n\n/**\n * Check and clean the detail fields of a program write body. Reads only the\n * seven detail keys; any other key of the body is the caller's to judge.\n *\n * Returns the cleaned details (text trimmed, the type as the key to store), or\n * EVERY refused field, never just the first. A key whose value is `undefined`\n * counts as absent.\n */\nexport function checkProgramDetails(\n body: unknown,\n options: ProgramDetailsCheckOptions,\n): ProgramDetailsCheck {\n const b = body && typeof body === \"object\" ? (body as Record<string, unknown>) : {};\n const details: Record<string, string | boolean | null> = {};\n const errors: ProgramDetailError[] = [];\n const refuse = (field: ProgramDetailKey, code: ProgramDetailErrorCode): void => {\n errors.push({ field, code, message: MESSAGES[code] });\n };\n\n for (const field of PROGRAM_DETAIL_KEYS) {\n const v = b[field];\n if (v === undefined) continue;\n if (v === null) {\n if (options.mode === \"patch\") details[field] = null;\n else refuse(field, \"null_on_create\");\n continue;\n }\n const rule = PROGRAM_DETAIL_RULES[field];\n if (rule.kind === \"yesNo\") {\n if (typeof v === \"boolean\") details[field] = v;\n else refuse(field, \"wrong_kind\");\n } else if (rule.kind === \"orgType\") {\n const key = options.programType(v);\n if (typeof key === \"string\" && key !== \"\") details[field] = key;\n else refuse(field, \"type_not_offered\");\n } else if (typeof v !== \"string\") {\n refuse(field, \"wrong_kind\");\n } else if (rule.kind === \"calendarDay\") {\n if (isCalendarDay(v)) details[field] = v;\n else refuse(field, \"not_a_calendar_day\");\n } else {\n const t = v.trim();\n if (t === \"\") refuse(field, \"blank\");\n else if (rule.maxLength !== undefined && t.length > rule.maxLength) refuse(field, \"too_long\");\n else details[field] = t;\n }\n }\n\n return errors.length > 0\n ? { ok: false, errors }\n : { ok: true, details: details as ProgramDetailsWrite };\n}\n","/**\n * Read rules for the platform-db org directory: which row shape a document\n * is, when an organization is an agency's OWN record, and the normalised read\n * view every app shares. Pure: no mongoose, no driver.\n *\n * Contract: platform `docs/ORG_DIRECTORY_CONTRACT.md`.\n */\n\nimport { OrganizationProgramRowSchema, type OrganizationProgramRow } from \"./schemas.js\";\nimport { isListedOrganization, isOrgKey, type OrgReviewStatus } from \"./orgRecord.js\";\nimport { programDetailsOf, type ProgramDetails } from \"./programDetails.js\";\nimport { isLiveOrganizationProgram, isProgramReviewStatus } from \"./vocabulary.js\";\n\n/** A driver ObjectId, or anything that prints itself as one. */\nexport interface ObjectIdLike {\n toHexString(): string;\n}\n\n/** An id's comparable string form: an ObjectId's hex, a string as-is, else null. */\nexport function directoryIdString(value: unknown): string | null {\n if (typeof value === \"string\") return value === \"\" ? null : value;\n if (\n value &&\n typeof value === \"object\" &&\n typeof (value as ObjectIdLike).toHexString === \"function\"\n ) {\n return (value as ObjectIdLike).toHexString();\n }\n return null;\n}\n\n/** Two ids name the same row (string vs ObjectId of one hex are the same). Absent is never a match. */\nexport function sameDirectoryId(a: unknown, b: unknown): boolean {\n const x = directoryIdString(a);\n const y = directoryIdString(b);\n return x !== null && y !== null && x.toLowerCase() === y.toLowerCase();\n}\n\n/**\n * Which writer's shape a stored `organizations` row has.\n *\n * - `canonical`: auth / Thread's global singletons (Unknown, Anonymous), marked by `canonicalKey`.\n * - `pave`: PAVE 2.0's legacy own shape (`packages/db/src/models/organization.ts`\n * before pl-958): a string `id`, `acronym`, `location`. Any ONE of the three\n * marks it.\n * - `thread`: the shared Thread / auth / Platform / PAVE (pl-958) shape: a\n * `type` in either stored form — the IC-58 Int (legacy) or a non-empty string\n * (the CVC-48 key). Whether the value is a VALID type is not this rule's\n * question (the subpath stays SOT-free); readers resolve it.\n * - `unknown`: none of the above (no type, `type: null`, an empty string —\n * e.g. the Platform's account rows).\n *\n * The FORM of `type` never decides `pave`: `organizations.type` is moving from\n * the IC-58 Int to the CVC-48 key on every shared row (auth's provisioning\n * writes the key; the `migrate:org-type-keys` script rewrites the rest), so a\n * key string is a shared-shape row. On platform-prod / platform-dev\n * (2026-10-16) every PAVE-shape row carries all three markers and no\n * Thread / auth / canonical row carries any of them.\n */\nexport type OrganizationRowShape = \"canonical\" | \"pave\" | \"thread\" | \"unknown\";\n\nexport function organizationRowShape(raw: unknown): OrganizationRowShape {\n if (!raw || typeof raw !== \"object\") return \"unknown\";\n const r = raw as Record<string, unknown>;\n if (typeof r.canonicalKey === \"string\" && r.canonicalKey !== \"\") return \"canonical\";\n if (typeof r.id === \"string\" || \"acronym\" in r || \"location\" in r) return \"pave\";\n if (typeof r.type === \"number\" || (typeof r.type === \"string\" && r.type.trim() !== \"\")) {\n return \"thread\";\n }\n return \"unknown\";\n}\n\n/**\n * Whether `org` is `agency`'s OWN organization record: both halves of the pair\n * auth's `ensureOrganizationForAgency` writes hold — `org.agencyId` names the\n * agency AND `agency.organizationId` names the org. Neither half alone counts;\n * `agencyScope` (tenancy) never counts.\n */\nexport function isAgencyOwnOrganization(\n org: { _id?: unknown; agencyId?: unknown } | null | undefined,\n agency: { _id?: unknown; organizationId?: unknown } | null | undefined,\n): boolean {\n if (!org || !agency) return false;\n return (\n sameDirectoryId(org.agencyId, agency._id) && sameDirectoryId(agency.organizationId, org._id)\n );\n}\n\n/**\n * One program as readers see it. Since 0.76.0 it carries the Program record's\n * own fields ({@link ProgramDetails}: kind, service area, direct services,\n * operating dates, site, notes), `null` where nothing is on record.\n * `programType` is the stored string; resolve it with `resolveOrgTypeKey`\n * (this subpath stays free of the codebook).\n */\nexport interface DirectoryProgramView extends ProgramDetails {\n programId: string;\n name: string;\n description: string | null;\n status: string | null;\n reviewStatus: OrganizationProgramRow[\"reviewStatus\"] | null;\n addedBy: string | null;\n addedInApp: string | null;\n /** Offered in pickers: not retired, not rejected. */\n live: boolean;\n}\n\n/** One program row as readers see it, or null when it fails the row schema. */\nexport function toDirectoryProgramView(raw: unknown): DirectoryProgramView | null {\n const parsed = OrganizationProgramRowSchema.safeParse(raw);\n if (!parsed.success) return null;\n const p = parsed.data;\n return {\n programId: p.programId,\n name: p.name,\n description: p.description ?? null,\n status: p.status ?? null,\n reviewStatus: p.reviewStatus ?? null,\n addedBy: p.addedBy ?? null,\n addedInApp: p.addedInApp ?? null,\n live: isLiveOrganizationProgram(p),\n ...programDetailsOf(p),\n };\n}\n\nexport interface DirectoryOrganizationView {\n /** `String(_id)`: the id listings and sharing settings key on. */\n id: string;\n shape: OrganizationRowShape;\n name: string;\n /** The stored `type` when it is a number (the legacy IC-58 Int), else null. */\n type: number | null;\n /**\n * The stored `type` when it is a string, else null: a CVC-48\n * `referral_entity_category` key on a shared-shape row once it is migrated\n * (or written by auth's provisioning), and on a legacy PAVE-shape row.\n */\n typeKey: string | null;\n /** PAVE's own string `id` on a PAVE-shape row, else null. */\n paveId: string | null;\n community: string | null;\n /** auth's identity half; see {@link isAgencyOwnOrganization}. */\n agencyId: string | null;\n /** Tenancy scope. Never an identity. */\n agencyScope: string | null;\n canonicalKey: string | null;\n // ── The Org record (`orgRecord.ts`); null = not captured ──\n /** The Org's identifier (the UDD `id`): the same in every database. Null on a row not yet given one. */\n key: string | null;\n legalName: string | null;\n commonName: string | null;\n /**\n * The curated short name (the UDD `acronym`): the stored `shortName`, else a\n * legacy PAVE-shape row's `acronym`. Never derived from the name here.\n */\n shortName: string | null;\n website: string | null;\n /** The organization this one is a unit of. */\n parentOrgId: string | null;\n /** HMIS VSP step 1. Tri-state: null = never captured. */\n vsp: boolean | null;\n /** HMIS VSP step 2. Null unless `vsp` is true. */\n vspPrivateNonprofit: boolean | null;\n /** pending · confirmed · rejected for an organization added inside an app; null on a steward row. */\n reviewStatus: OrgReviewStatus | null;\n addedInApp: string | null;\n /** Who added it (a platform `users._id`); a pre-0.60 row's `addedByUserId` reads here too. */\n addedBy: string | null;\n addedInSession: string | null;\n /** The stored lifecycle code (1 active, 2 inactive), else null. */\n status: number | null;\n /** Offered in pickers: active and not declined (`isListedOrganization`). */\n listed: boolean;\n programs: DirectoryProgramView[];\n /** Program rows that failed the row schema (not returned). */\n invalidPrograms: number;\n}\n\nconst text = (v: unknown): string | null => (typeof v === \"string\" && v !== \"\" ? v : null);\nconst line = (v: unknown): string | null => (typeof v === \"string\" && v.trim() !== \"\" ? v.trim() : null);\nconst flag = (v: unknown): boolean | null => (typeof v === \"boolean\" ? v : null);\n\n/** Normalise a stored row of any writer's shape into the shared read view. */\nexport function toDirectoryOrganizationView(raw: unknown): DirectoryOrganizationView | null {\n if (!raw || typeof raw !== \"object\") return null;\n const r = raw as Record<string, unknown>;\n const id = directoryIdString(r._id);\n if (!id) return null;\n const rows = Array.isArray(r.programs) ? r.programs : [];\n const programs = rows\n .map(toDirectoryProgramView)\n .filter((p): p is DirectoryProgramView => p !== null);\n const vsp = flag(r.vsp);\n const reviewStatus = isProgramReviewStatus(r.reviewStatus) ? r.reviewStatus : null;\n const status = typeof r.status === \"number\" ? r.status : null;\n return {\n id,\n shape: organizationRowShape(r),\n name: text(r.name) ?? \"\",\n type: typeof r.type === \"number\" ? r.type : null,\n typeKey: typeof r.type === \"string\" ? r.type : null,\n paveId: text(r.id),\n community: text(r.community),\n agencyId: directoryIdString(r.agencyId),\n agencyScope: directoryIdString(r.agencyScope),\n canonicalKey: text(r.canonicalKey),\n key: isOrgKey(r.key) ? r.key : null,\n legalName: line(r.legalName),\n commonName: line(r.commonName),\n shortName: line(r.shortName) ?? line(r.acronym),\n website: line(r.website),\n parentOrgId: directoryIdString(r.parentOrgId),\n vsp,\n vspPrivateNonprofit: vsp === true ? flag(r.vspPrivateNonprofit) : null,\n reviewStatus,\n addedInApp: line(r.addedInApp),\n addedBy: line(r.addedBy) ?? line(r.addedByUserId),\n addedInSession: line(r.addedInSession),\n status,\n listed: isListedOrganization({ status, reviewStatus }),\n programs,\n invalidPrograms: rows.length - programs.length,\n };\n}\n","/**\n * The raw-driver reads of the platform-db org directory. No driver import: the\n * readers take any object with the MongoDB driver's\n * `collection(name).findOne(filter, options)` shape, plus a `toObjectId`\n * factory so a 24-hex string id also matches a row stored under an ObjectId\n * (production `organizations._id` and `agencies._id` are ObjectIds).\n */\n\nimport {\n isAgencyOwnOrganization,\n toDirectoryOrganizationView,\n type DirectoryOrganizationView,\n type ObjectIdLike,\n} from \"./rules.js\";\n\nexport const ORGANIZATIONS_COLLECTION = \"organizations\";\nexport const AGENCIES_COLLECTION = \"agencies\";\n\nexport interface OrgDirectoryDbLike {\n collection(name: string): {\n findOne(filter: Record<string, unknown>, options?: Record<string, unknown>): Promise<unknown>;\n };\n}\n\nexport interface OrgDirectoryReadOptions {\n /** Build the driver's ObjectId from 24-hex (e.g. `(h) => new ObjectId(h)`). */\n toObjectId?: (hex: string) => unknown;\n}\n\nconst HEX = /^[0-9a-fA-F]{24}$/;\n\n/** Every stored form of one id: the string, and its ObjectId when 24-hex. */\nexport function organizationIdForms(\n id: string | ObjectIdLike,\n opts: OrgDirectoryReadOptions = {},\n): unknown[] {\n if (typeof id !== \"string\") return [id.toHexString(), id];\n return HEX.test(id) && opts.toObjectId ? [id, opts.toObjectId(id.toLowerCase())] : [id];\n}\n\n/** One organization in the shared view, or null. Read errors propagate. */\nexport async function readDirectoryOrganization(\n db: OrgDirectoryDbLike,\n id: string | ObjectIdLike,\n opts: OrgDirectoryReadOptions = {},\n): Promise<DirectoryOrganizationView | null> {\n const raw = await db\n .collection(ORGANIZATIONS_COLLECTION)\n .findOne({ _id: { $in: organizationIdForms(id, opts) } });\n return raw ? toDirectoryOrganizationView(raw) : null;\n}\n\n/**\n * An agency's OWN organization (both halves of the pair hold), or null — never\n * an organization the agency merely scopes (`agencyScope`) or that points at it\n * from one side only. The agency is looked up by `_id`.\n */\nexport async function readAgencyOwnOrganization(\n db: OrgDirectoryDbLike,\n agencyId: string | ObjectIdLike,\n opts: OrgDirectoryReadOptions = {},\n): Promise<DirectoryOrganizationView | null> {\n const agency = (await db\n .collection(AGENCIES_COLLECTION)\n .findOne(\n { _id: { $in: organizationIdForms(agencyId, opts) } },\n { projection: { _id: 1, organizationId: 1 } },\n )) as { _id?: unknown; organizationId?: unknown } | null;\n if (!agency || agency.organizationId == null) return null;\n const pointer = agency.organizationId as string | ObjectIdLike;\n const org = (await db\n .collection(ORGANIZATIONS_COLLECTION)\n .findOne({ _id: { $in: organizationIdForms(pointer, opts) } })) as {\n _id?: unknown;\n agencyId?: unknown;\n } | null;\n return org && isAgencyOwnOrganization(org, agency) ? toDirectoryOrganizationView(org) : null;\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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA,EACE,QAAU;AAAA,EACV,MAAQ;A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