@htilabs/platform-common-models 0.85.0 → 0.87.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 +30 -0
- package/dist/{index-XWSYon40.d.cts → index-1pWiqEBC.d.cts} +1 -1
- package/dist/{index-Bh1zO_Vu.d.ts → index-uz57Fic9.d.ts} +1 -1
- package/dist/index.cjs +12 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +12 -1
- package/dist/index.js.map +1 -1
- package/dist/models/index.d.cts +2 -2
- package/dist/models/index.d.ts +2 -2
- 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 +229 -24
- package/dist/points-of-contact/index.cjs.map +1 -1
- package/dist/points-of-contact/index.d.cts +50 -5
- package/dist/points-of-contact/index.d.ts +50 -5
- package/dist/points-of-contact/index.js +226 -23
- package/dist/points-of-contact/index.js.map +1 -1
- package/dist/reader-BmhzOis-.d.ts +273 -0
- package/dist/reader-DfQtdw6n.d.cts +273 -0
- package/dist/schemas/index.cjs +12 -1
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +57 -27
- package/dist/schemas/index.d.ts +57 -27
- package/dist/schemas/index.js +12 -1
- package/dist/schemas/index.js.map +1 -1
- package/dist/seat-logs/index.cjs +815 -0
- package/dist/seat-logs/index.cjs.map +1 -0
- package/dist/seat-logs/index.d.cts +274 -0
- package/dist/seat-logs/index.d.ts +274 -0
- package/dist/seat-logs/index.js +742 -0
- package/dist/seat-logs/index.js.map +1 -0
- package/dist/validation/index.d.cts +1 -1
- package/dist/validation/index.d.ts +1 -1
- package/package.json +6 -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/pointsOfContact/__tests__/seatContactLog.test.ts +170 -0
- package/src/pointsOfContact/readRules.ts +22 -4
- package/src/pointsOfContact/reader.ts +95 -1
- package/src/pointsOfContact/schemas.ts +4 -3
- package/src/schemas/organization-program.ts +25 -2
- package/src/seatLogs/__tests__/seatLogs.review.test.ts +222 -0
- package/src/seatLogs/__tests__/seatLogs.test.ts +335 -0
- package/src/seatLogs/index.ts +15 -0
- package/src/seatLogs/log.ts +700 -0
- package/src/seatLogs/personId.ts +100 -0
- package/src/seatLogs/personSlugWordlists.ts +40 -0
- package/src/seatLogs/reader.ts +143 -0
- package/src/seatLogs/schemas.ts +118 -0
- package/dist/{agency-CnVTwLeV.d.ts → agency-BHv54o79.d.ts} +4 -4
- package/dist/{agency-8ufZJJDH.d.cts → agency-Djp57S71.d.cts} +4 -4
- package/dist/{cvcEntry-D787utvP.d.cts → cvcEntry-DAuhe0cd.d.cts} +8 -8
- package/dist/{cvcEntry-D787utvP.d.ts → cvcEntry-DAuhe0cd.d.ts} +8 -8
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/orgMerge/index.ts","../../src/orgMerge/support.ts","../../src/orgDirectory/orgRecord.ts","../../src/orgDirectory/vocabulary.ts","../../src/orgDirectory/schemas.ts","../../src/orgDirectory/programDetails.ts","../../src/orgDirectory/rules.ts","../../src/orgDirectory/read.ts","../../src/pointsOfContact/schemas.ts","../../src/cvcs/preferredContactMethod.v1.1.0.json","../../src/pointsOfContact/vocabulary.ts","../../src/serviceListings/vocabulary.ts","../../src/serviceListings/schemas.ts","../../src/serviceListings/read.ts","../../src/orgMerge/orgMerge.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models/org-merge\n *\n * Folding a copy of an organization into the one that is kept: the plan, the\n * write and its undo (`orgMerge.ts`). Server only: it reads and writes\n * through MongoDB driver handles the caller opens. Used by the registry tool\n * (`fill-org-registry --apply-merges`) and by the Platform's Admin Hub\n * (\"Merge into another organization\"). Subpath only.\n *\n * The caller says who is merging (`planMerges(dbs, lines, driver, { mergedBy })`,\n * 0.84.0): `steward` for HTI Labs acting on the one platform-wide registry,\n * `agency` for a merge inside one agency's own list. See `orgMerge.ts`.\n */\nexport * from \"./types.js\";\nexport * from \"./support.js\";\nexport * from \"./orgMerge.js\";\n","/**\n * Small value helpers the merge shares with the registry fill script\n * (`scripts/lib/orgRegistryFill.ts` re-exports them).\n */\nconst text = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\");\n\n/** A name reduced for comparison: case, punctuation and a leading \"the\" dropped. */\nexport function comparableName(value: unknown): string {\n return text(value)\n .normalize(\"NFKD\")\n .toLowerCase()\n .replace(/&/g, \" and \")\n .replace(/[^a-z0-9]+/g, \" \")\n .trim()\n .replace(/^the /, \"\");\n}\n\n/**\n * An organization id as text, comparable: a 24-hex database id in lower case\n * (the form an ObjectId prints as), any other text id exactly as stored. A\n * text id is never case-folded: \"Org-A\" and \"org-a\" are two rows.\n */\nexport function comparableId(value: string): string {\n const s = value.trim();\n return /^[0-9a-fA-F]{24}$/.test(s) ? s.toLowerCase() : s;\n}\n\n/** A spreadsheet must not evaluate an org name as a formula. */\nexport const sheetText = (v: unknown): string => {\n const s = typeof v === \"string\" ? v : v == null ? \"\" : String(v);\n return /^[=+\\-@\\t\\r]/.test(s) ? `'${s}` : s;\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-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 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 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","/**\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 \"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 * @htilabs/platform-common-models/service-listings — the closed vocabularies a\n * Service Listing stores. Contract: platform `docs/SERVICE_LISTING_CONTRACT.md`.\n */\n\n/** The survey's two pick lists (profile § 5). */\nexport const LISTING_TIERS = [\"primary\", \"additional\"] as const;\nexport type ListingTier = (typeof LISTING_TIERS)[number];\n\n/**\n * How a service is reached (profile § 5; prototype\n * `Service Registry/README.md` @ 2103f288, \"CSV columns\").\n */\nexport const ACCESS_PATHS = [\n \"Referral required\",\n \"Hotline\",\n \"Walk-in\",\n \"Law enforcement initiated\",\n \"Court/probation initiated\",\n] as const;\nexport type AccessPath = (typeof ACCESS_PATHS)[number];\n\n/** What is STORED. `stale` is never stored: it is computed on read. */\nexport const STORED_VERIFICATION_STATUSES = [\"pending\", \"verified\"] as const;\nexport type StoredVerificationStatus = (typeof STORED_VERIFICATION_STATUSES)[number];\n\n/** What a READER sees (profile § 5: pending | verified | stale). */\nexport const VERIFICATION_STATUSES = [\"pending\", \"verified\", \"stale\"] as const;\nexport type VerificationStatus = (typeof VERIFICATION_STATUSES)[number];\n\n/** Where a listing was created: the Program's enum. Null on a steward sheet row. */\nexport const ADDED_IN_APPS = [\"pave\", \"thread\", \"leads\", \"platform\"] as const;\nexport type AddedInApp = (typeof ADDED_IN_APPS)[number];\n\n/** HTI Labs' review of a listing added from an app or the survey. */\nexport const LISTING_REVIEW_STATUSES = [\"pending\", \"confirmed\", \"rejected\"] as const;\nexport type ListingReviewStatus = (typeof LISTING_REVIEW_STATUSES)[number];\n\n/**\n * The lane a listing arrived through (profile census items 1, 2 and 9). It is\n * stored as `origin`. Every lane is human entry: UDD `dataSource.source_category`\n * is `human` for all three, so the lane is the provenance fact.\n */\nexport const LISTING_ORIGINS = [\"survey\", \"admin_hub\", \"steward_seed\"] as const;\nexport type ListingOrigin = (typeof LISTING_ORIGINS)[number];\n\n/** The two lanes an agency mints through. The steward seed is a separate path. */\nexport const MINT_ORIGINS = [\"survey\", \"admin_hub\"] as const;\nexport type MintOrigin = (typeof MINT_ORIGINS)[number];\n\n/** The verification window in months (profile § 6 q1 default; owner and length are Crysta's). */\nexport const STALE_WINDOW_MONTHS = 12;\n","/**\n * @htilabs/platform-common-models/service-listings — Zod schemas for the\n * `platform-db.servicelistings` document and the bodies its writers accept.\n *\n * Contract (fields, id universes, read rules, writers): platform\n * `docs/SERVICE_LISTING_CONTRACT.md`. This file declares shapes only.\n *\n * Three body schemas, so a writer cannot reach a field its lane does not own:\n * - {@link ServiceListingDetailsSchema}: the descriptive fields an edit may\n * change. No identity, verification, arrival or removal keys.\n * - {@link MintListingBodySchema}: details plus `vscat_key`. What the survey\n * and the Admin Hub send. No `id`, no verification: `.strict()` refuses them.\n * - {@link SeedListingBodySchema}: the steward seed only. It may also carry the\n * sheet's `id`, `verification_status` and `last_verified`.\n *\n * `org_id` is in none of them: the writer passes it as its own argument, from\n * the caller's scope, never from a body.\n */\n\nimport { z } from \"zod\";\n\nimport {\n ACCESS_PATHS,\n ADDED_IN_APPS,\n LISTING_ORIGINS,\n LISTING_REVIEW_STATUSES,\n LISTING_TIERS,\n STORED_VERIFICATION_STATUSES,\n} from \"./vocabulary.js\";\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst LISTING_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/** A real calendar date as YYYY-MM-DD. */\nexport const IsoDateSchema = z\n .string()\n .regex(ISO_DATE, \"Expected an ISO date (YYYY-MM-DD).\")\n .refine((s) => {\n const d = new Date(`${s}T00:00:00Z`);\n return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;\n }, \"Not a real calendar date.\");\n\n/** A non-empty trimmed id string (a directory id in its canonical string form). */\nexport const DirectoryIdSchema = z.string().trim().min(1);\n\n/** A listing id: the sheet's `service_id` shape, or `svc-<hex>` minted by the store. */\nexport const ListingIdSchema = z\n .string()\n .regex(LISTING_ID, \"A listing id is letters, digits, '.', '_' or '-'.\");\n\n/** A CVC-22 key slug (the join). Whether it names a listable category is checked by the writer. */\nexport const ServiceCategoryKeySchema = z.string().trim().regex(/^[a-z][a-z0-9_]*$/, \"Not a CVC key.\");\n\nconst text = z.string().trim();\nconst optionalText = text.nullable().optional();\n\n/** The descriptive fields: what an edit may change. */\nexport const ServiceListingDetailsSchema = z\n .object({\n program_id: DirectoryIdSchema.nullable().optional(),\n agency_id: DirectoryIdSchema.nullable().optional(),\n tier: z.enum(LISTING_TIERS).nullable().optional(),\n ht_specific: z.boolean().nullable().optional(),\n sector: optionalText,\n populations: z.array(text.min(1)).optional(),\n access_path: z.enum(ACCESS_PATHS).nullable().optional(),\n jurisdiction: optionalText,\n hours: optionalText,\n eligibility: optionalText,\n cost: optionalText,\n contact_name: optionalText,\n contact_email: optionalText,\n contact_phone: optionalText,\n contact_city: optionalText,\n contact_state: optionalText,\n confidential: z.boolean().optional(),\n })\n .strict();\nexport type ServiceListingDetails = z.infer<typeof ServiceListingDetailsSchema>;\n\n/** An edit: one or more descriptive fields. */\nexport const ServiceListingPatchSchema = ServiceListingDetailsSchema.refine(\n (b) => Object.keys(b).length > 0,\n { message: \"A listing edit must name at least one field.\" },\n);\nexport type ServiceListingPatch = z.infer<typeof ServiceListingPatchSchema>;\n\n/** A survey or Admin Hub mint. */\nexport const MintListingBodySchema = ServiceListingDetailsSchema.extend({\n vscat_key: ServiceCategoryKeySchema,\n}).strict();\nexport type MintListingBody = z.infer<typeof MintListingBodySchema>;\n\n/** A steward seed row. A verified row carries its date. */\nexport const SeedListingBodySchema = MintListingBodySchema.extend({\n id: ListingIdSchema.optional(),\n verification_status: z.enum(STORED_VERIFICATION_STATUSES).optional(),\n last_verified: IsoDateSchema.nullable().optional(),\n})\n .strict()\n .refine((b) => b.verification_status !== \"verified\" || !!b.last_verified, {\n message: \"A verified listing carries the date it was verified (last_verified).\",\n path: [\"last_verified\"],\n });\nexport type SeedListingBody = z.infer<typeof SeedListingBodySchema>;\n\nconst nullableText = z.string().nullable();\n\n/** The stored document, without Mongo's `_id`. Readers parse every row with it. */\nexport const StoredServiceListingSchema = z.object({\n id: ListingIdSchema,\n org_id: DirectoryIdSchema,\n program_id: DirectoryIdSchema.nullable(),\n agency_id: DirectoryIdSchema.nullable(),\n vscat_key: ServiceCategoryKeySchema,\n vscat_code: z.string(),\n vscat_label: z.string(),\n tier: z.enum(LISTING_TIERS).nullable(),\n ht_specific: z.boolean().nullable(),\n sector: nullableText,\n populations: z.array(z.string()),\n access_path: z.enum(ACCESS_PATHS).nullable(),\n jurisdiction: nullableText,\n hours: nullableText,\n eligibility: nullableText,\n cost: nullableText,\n contact_name: nullableText,\n contact_email: nullableText,\n contact_phone: nullableText,\n contact_city: nullableText,\n contact_state: nullableText,\n confidential: z.boolean(),\n verification_status: z.enum(STORED_VERIFICATION_STATUSES),\n last_verified: IsoDateSchema.nullable(),\n origin: z.enum(LISTING_ORIGINS),\n added_by: nullableText,\n added_in_app: z.enum(ADDED_IN_APPS).nullable(),\n review_status: z.enum(LISTING_REVIEW_STATUSES).nullable(),\n removal_requested_at: nullableText,\n removal_requested_by: nullableText,\n version: z.number().int().min(1),\n createdBy: nullableText,\n createdAt: z.string(),\n updatedBy: nullableText,\n updatedAt: z.string(),\n});\nexport type StoredServiceListing = z.infer<typeof StoredServiceListingSchema>;\n","/**\n * @htilabs/platform-common-models/service-listings — the collection, its\n * indexes and the one raw-driver read every app uses.\n *\n * No driver import: the reader takes any object with the MongoDB driver's\n * `collection(name).find(filter).toArray()` shape, so PAVE, Thread, LEADS and\n * the Platform pass their own `Db`.\n */\n\nimport type { ServiceCategories } from \"./categories.js\";\nimport { isListedOnNetwork, toListingView, type ServiceListingView } from \"./rules.js\";\nimport { StoredServiceListingSchema, type StoredServiceListing } from \"./schemas.js\";\n\nexport const SERVICE_LISTINGS_COLLECTION = \"servicelistings\";\n\n/** One index the store creates. */\nexport interface ServiceListingIndexSpec {\n name: string;\n key: Readonly<Record<string, 1>>;\n unique: boolean;\n}\n\n/**\n * The store's indexes. `offering` is the uniqueness rule: one listing per\n * (org, program, category). A null `program_id` indexes as a value, so an org\n * lists a category once at the org level. Its prefix serves the org and the\n * org + program reads.\n */\nexport const SERVICE_LISTING_INDEXES = {\n id: { name: \"servicelistings_id_unique\", key: { id: 1 }, unique: true },\n offering: {\n name: \"servicelistings_offering_unique\",\n key: { org_id: 1, program_id: 1, vscat_key: 1 },\n unique: true,\n },\n category: { name: \"servicelistings_vscat_key\", key: { vscat_key: 1 }, unique: false },\n} as const satisfies Record<string, ServiceListingIndexSpec>;\n\n/** A driver ObjectId, or anything that prints itself as one. */\nexport interface ObjectIdLike {\n toHexString(): string;\n}\n\n/** A directory id as a caller holds it: its string form or an ObjectId. */\nexport type DirectoryIdInput = string | ObjectIdLike;\n\n/**\n * The stored forms of a directory id. The store always writes the canonical\n * STRING form, so the string matches every row; an ObjectId the caller holds is\n * included as well, in case a row was ever written with one.\n */\nexport function directoryIdForms(id: DirectoryIdInput): unknown[] {\n return typeof id === \"string\" ? [id] : [id.toHexString(), id];\n}\n\n/** The read queries the apps make. */\nexport type ServiceListingQuery =\n /**\n * An org's listings. `programId` absent (or undefined): the rollup across its\n * programs. A string: that program's listings. `null`: the org-level listings.\n */\n | { orgId: DirectoryIdInput; programId?: string | null }\n /** Every listing of one or more CVC-22 categories, by key. */\n | { categoryKeys: readonly string[] }\n /** One listing. */\n | { id: string };\n\n/** The minimal driver surface the reader needs. */\nexport interface ListingsDbLike {\n collection(name: string): {\n find(filter: Record<string, unknown>): { toArray(): Promise<unknown[]> };\n };\n}\n\nexport interface ReadServiceListingsOptions {\n now?: Date;\n categories: ServiceCategories;\n /** Called with each stored row that fails the schema; such a row is not returned. */\n onInvalid?: (raw: unknown, issues: string) => void;\n}\n\n/** The Mongo filter for a query. Exported so a writer reads the same way. */\nexport function serviceListingFilter(query: ServiceListingQuery): Record<string, unknown> {\n if (\"id\" in query) return { id: query.id };\n if (\"categoryKeys\" in query) return { vscat_key: { $in: [...new Set(query.categoryKeys)] } };\n const org = { org_id: { $in: directoryIdForms(query.orgId) } };\n return query.programId !== undefined ? { ...org, program_id: query.programId } : org;\n}\n\n/** Parse one stored row (without `_id`), or null with the reason. */\nexport function parseStoredListing(\n raw: unknown,\n): { ok: true; doc: StoredServiceListing } | { ok: false; issues: string } {\n const rec = raw && typeof raw === \"object\" ? { ...(raw as Record<string, unknown>) } : raw;\n if (rec && typeof rec === \"object\") delete (rec as Record<string, unknown>)._id;\n const parsed = StoredServiceListingSchema.safeParse(rec);\n if (parsed.success) return { ok: true, doc: parsed.data };\n return {\n ok: false,\n issues: parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\"; \"),\n };\n}\n\nconst TIER_ORDER: Record<string, number> = { primary: 0, additional: 1 };\nconst LAST = \"\";\n\n/** Reading order: program, primary before additional, label, id. */\nexport function compareListings(\n a: Pick<StoredServiceListing, \"program_id\" | \"tier\" | \"vscat_label\" | \"id\">,\n b: Pick<StoredServiceListing, \"program_id\" | \"tier\" | \"vscat_label\" | \"id\">,\n): number {\n return (\n (a.program_id ?? LAST).localeCompare(b.program_id ?? LAST) ||\n (TIER_ORDER[a.tier ?? \"\"] ?? 2) - (TIER_ORDER[b.tier ?? \"\"] ?? 2) ||\n a.vscat_label.localeCompare(b.vscat_label) ||\n a.id.localeCompare(b.id)\n );\n}\n\n/**\n * Read listings as every reader sees them (the Network's public, masked view).\n * A listing whose review is `rejected` is left out ({@link isListedOnNetwork}),\n * so an `{id}` read of one reads `[]`. Read errors propagate: an org with no\n * rows reads `[]`; an unreadable store throws.\n */\nexport async function readServiceListings(\n db: ListingsDbLike,\n query: ServiceListingQuery,\n opts: ReadServiceListingsOptions,\n): Promise<ServiceListingView[]> {\n if (\"categoryKeys\" in query && query.categoryKeys.length === 0) return [];\n const raws = await db\n .collection(SERVICE_LISTINGS_COLLECTION)\n .find(serviceListingFilter(query))\n .toArray();\n const now = opts.now ?? new Date();\n const views: ServiceListingView[] = [];\n for (const raw of raws) {\n const parsed = parseStoredListing(raw);\n if (!parsed.ok) {\n opts.onInvalid?.(raw, parsed.issues);\n continue;\n }\n if (!isListedOnNetwork(parsed.doc)) continue;\n views.push(toListingView(parsed.doc, { now, categories: opts.categories }));\n }\n return views.sort(compareListings);\n}\n","/**\n * @htilabs/platform-common-models — folding a copy into the real organization\n *\n * The logic behind `fill-org-registry --apply-merges`. Runbook:\n * `scripts/FILL_ORG_REGISTRY_RUNBOOK.md`, \"Folding a copy into the real\n * organization\".\n *\n * ## Why\n *\n * One record per real-world organization (UDD Org Data Object, 2026-10-02).\n * Where the same organization was typed in twice, the steward (HTI Labs)\n * reconciles the two by hand: a person names the copy and the row that is\n * kept. Nothing here works out which rows are copies.\n *\n * ## What a merge is (ruled 2026-10-20, the prototype's ORG-MERGE)\n *\n * Pure re-pointing. Every stored reference to the copy's `_id` is changed to\n * the kept organization's `_id`. Nothing on the kept row is combined or\n * rewritten: not its name, type, VSP answer, list or programs, and no\n * Account's sharing rule. The copy is then deleted, and its id is recorded on\n * the kept row as `legacy_ids.merged_from`, so an old reference found later\n * can be traced.\n *\n * ## Where references live\n *\n * {@link ORG_REFERENCES} is the list, read from the models of this package,\n * Thread, PAVE 2.0, the Platform app and auth (2026-11-10). Thread and PAVE\n * keep their case records in databases of their own. The copy is deleted only\n * when nothing in the platform database points at it AND every Thread and\n * PAVE database was named on the command line and nothing there points at it\n * either. Otherwise the copy stays, marked inactive (`status` 2, which every\n * app already reads as \"not offered\", `isListedOrganization`), and the line\n * says why.\n *\n * ## Programs (0.84.0)\n *\n * A Program belongs to the Organization, and is stored on its row\n * (`organizations.programs[]`). \"Make the other objects really move in a\n * merge\" (Crysta, 2026-11-11): when a steward merges, the copy's program rows\n * move to the kept organization, exactly as stored and with their ids\n * unchanged. A program id is minted, never derived from a name, so it names\n * one program wherever its row sits; everything that points at a program\n * (`servicelistings.program_id`, a case's program in Thread or PAVE) names it\n * beside the organization, and that reference is re-pointed above. So nothing\n * that points at a program is touched, and nothing is left pointing at a\n * program that is gone. The rows are appended to the kept organization's\n * list in the same write that records the copy's id there. Two live programs\n * that end up with the same name are both kept, as two programs (a name is\n * not an identity; the plan says so in a flag). Where the agency whose list\n * the copy is in cannot yet read the kept row in Thread and PAVE (see \"Who is\n * merging\"), the flag also says it may not be able to pick the programs that\n * moved; nothing is refused for it. A copy that is then kept as\n * inactive keeps no programs: they are the kept organization's now. A merge\n * inside one agency's own list (`agency`) still refuses a copy with programs,\n * as before.\n *\n * ## What it never does\n *\n * It never writes a fact of the kept row (its programs are added to, never\n * rewritten), never moves an identifier (`key`: identifiers never change),\n * never moves a sharing grant, never merges an Agency's own organization\n * (that is not a copy), and never re-points a copy of an id kept inside a\n * sent share, a session draft or a sealed field (see the runbook).\n *\n * ## Who is merging (0.84.0)\n *\n * The caller says who merges ({@link MergeActor}); nothing here works it out.\n *\n * - `steward`: HTI Labs reconciling the registry (the Admin Hub's \"Merge into\n * another organization\", the registry tool). The registry is ONE\n * platform-wide list: \"Organizations should never sit inside one agency's\n * own list\" (Crysta, 2026-11-11), and an agency's list never blocks a\n * registry action. So the pair is judged against the registry alone: both\n * rows exist, the kept one is offered (active, not declined). Whose list a\n * row was typed into (`agencyScope`) and its `community` refuse nothing.\n * Where Thread's and PAVE's as-built per-agency read would hide the kept\n * row from the agency whose list the copy is in, the plan carries a flag\n * saying so, in words a steward can read; it goes when both apps read the\n * one list (Thread #1228 and PAVE's twin).\n * - `agency`: a merge made inside one agency's own list. The kept row must be\n * readable where the copy is used, by Thread's as-built rule. This is the\n * rule every caller had before 0.84.0, unchanged. No app calls it today.\n *\n * Every other refusal is about the data, not about lists, and holds for both.\n */\n\n/*\n * Moved here from scripts/ in 0.69.0, where the 100-column lint rule does not\n * run. The reference table below reads as one line per place an id is stored;\n * the long lines are kept so the move stays a move. The one change: nothing\n * here imports mongoose or the driver. The handles are typed structurally and\n * the caller passes its own ObjectId class and EJSON ({@link MergeDriver}), so\n * an id built here is the same class the caller's driver stores and reads.\n */\n/* eslint-disable max-len */\n\n\nimport { ORGANIZATION_STATUS, isListedOrganization } from \"../orgDirectory/orgRecord.js\";\nimport { isLiveOrganizationProgram, programNameKey } from \"../orgDirectory/vocabulary.js\";\nimport { AGENCIES_COLLECTION, ORGANIZATIONS_COLLECTION } from \"../orgDirectory/read.js\";\nimport { directoryIdString } from \"../orgDirectory/rules.js\";\nimport { POINTS_OF_CONTACT_COLLECTION } from \"../pointsOfContact/schemas.js\";\nimport { SERVICE_LISTINGS_COLLECTION } from \"../serviceListings/read.js\";\nimport { comparableId, comparableName, sheetText } from \"./support.js\";\nimport type {\n MergeBeforeImages,\n MergeDbLike,\n MergeDocument,\n MergeDriver,\n MergeImage,\n MergeProgramsImage,\n MergeRefImage,\n} from \"./types.js\";\n\ntype Db = MergeDbLike;\ntype Document = MergeDocument;\ntype Row = Record<string, unknown>;\n\nconst text = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\");\nconst blank = (v: unknown): boolean => v == null || (typeof v === \"string\" && v.trim() === \"\");\nconst idText = (v: unknown): string => directoryIdString(v) ?? String(v);\nconst HEX_24 = /^[0-9a-fA-F]{24}$/;\nconst message = (err: unknown): string => (err instanceof Error ? err.message : String(err));\n\n/**\n * An id's comparable text when the value is an id (a string or an ObjectId), else null. Never a sub-record.\n * A 24-hex id is lower-cased (the form an ObjectId prints as); a text id is compared exactly as stored.\n */\nconst idOf = (driver: MergeDriver, v: unknown): string | null =>\n typeof v === \"string\" ? comparableId(v) : v instanceof driver.ObjectId ? v.toHexString() : null;\n\n/** Every stored form of an id: the ObjectId and the lower-case text when it is 24-hex, else the text. */\nfunction idForms(driver: MergeDriver, id: unknown): unknown[] {\n const s = idText(id);\n return HEX_24.test(s) ? [new driver.ObjectId(s.toLowerCase()), s.toLowerCase()] : [s];\n}\n/**\n * The kept id in the same stored form as the value it replaces. A text id is\n * written exactly as the kept row stores it: before 0.84.0 it was lower-cased,\n * so a reference moved to a row stored under \"Org-A\" named \"org-a\", which is\n * no row.\n */\nfunction inFormOf(driver: MergeDriver, from: unknown, keptId: unknown): unknown {\n const s = idText(keptId);\n return from instanceof driver.ObjectId && HEX_24.test(s) ? new driver.ObjectId(s.toLowerCase()) : comparableId(s);\n}\n\n/**\n * Thread's development sample rows (`apps/api/src/seed/index.ts`: the\n * \"Thread Prototype Agency\" and its organizations, ids `64e4ff1c2a7dcd9cb5f4a0xx`\n * and `…a1xx`). Some reached production. They are never a kept row or a copy.\n */\nexport const THREAD_SAMPLE_ID_PREFIX = \"64e4ff1c2a7dcd9cb5f4a\";\n\n// ─── Where an organization's `_id` is stored ────────────────────────────────\n\n/** Which database a reference lives in: the platform database, or an app's own. */\nexport type ReferenceApp = \"platform\" | \"thread\" | \"pave\";\nexport const APP_LABEL: Record<ReferenceApp, string> = { platform: \"the platform\", thread: \"Thread\", pave: \"PAVE\" };\n\nexport interface OrgReference {\n app: ReferenceApp;\n collection: string;\n /**\n * `value`: `path` holds the id. `list`: `path` is a list of ids. `rows`:\n * `path` is a list of sub-records and `field` in each holds the id.\n * `answers`: `path` is a list of form answers and `field` in each is a list\n * of values, any of which may be the id. `count`: counted, never moved: a\n * copy it names is kept, not deleted.\n */\n kind: MergeRefImage[\"kind\"] | \"count\";\n path: string;\n field?: string;\n /** Who writes it, for the runbook's table. */\n writtenBy: string;\n}\n\n/**\n * Every place an organization's `_id` is stored, from the code (2026-11-10).\n * `agencies.organizationId` is not here: an organization an Agency points at\n * is that Agency's own and is never merged. A reference by an Org's `key`\n * (the Platform app's sharing-rule attachments) is not here either: a merge\n * moves ids, and identifiers never move. Program ids (`programs[].programId`)\n * are not here: a copy with programs is refused.\n */\nexport const ORG_REFERENCES: readonly OrgReference[] = Object.freeze([\n { app: \"platform\", collection: \"personnelpeople\", kind: \"value\", path: \"organizationId\", writtenBy: \"auth at a first sign-in; Thread's staff records\" },\n { app: \"platform\", collection: ORGANIZATIONS_COLLECTION, kind: \"value\", path: \"parentOrgId\", writtenBy: \"an Org that is a unit of this one\" },\n { app: \"platform\", collection: SERVICE_LISTINGS_COLLECTION, kind: \"value\", path: \"org_id\", writtenBy: \"service listings\" },\n { app: \"platform\", collection: POINTS_OF_CONTACT_COLLECTION, kind: \"value\", path: \"org_id\", writtenBy: \"points of contact\" },\n { app: \"platform\", collection: POINTS_OF_CONTACT_COLLECTION, kind: \"value\", path: \"subject_id\", writtenBy: \"an Org's own point of contact\" },\n { app: \"platform\", collection: \"personnelmergefolds\", kind: \"value\", path: \"survivorBefore.organizationId\", writtenBy: \"Thread's staff-record merge log\" },\n { app: \"platform\", collection: \"personnelmergefolds\", kind: \"value\", path: \"survivorChange.liftedOrganizationId\", writtenBy: \"Thread's staff-record merge log\" },\n { app: \"platform\", collection: \"surveyedOrganizations\", kind: \"value\", path: \"directoryOrganizationId\", writtenBy: \"the Platform app's agency survey link\" },\n { app: \"platform\", collection: \"accountPolicies\", kind: \"value\", path: \"orgRef\", writtenBy: \"the Platform app's account-policy seed\" },\n { app: \"platform\", collection: AGENCIES_COLLECTION, kind: \"list\", path: \"reportingDestinations.designated.mandatory_reporting\", writtenBy: \"the Platform app's reporting destinations\" },\n { app: \"platform\", collection: AGENCIES_COLLECTION, kind: \"list\", path: \"reportingDestinations.designated.authority_reporting\", writtenBy: \"the Platform app's reporting destinations\" },\n\n { app: \"thread\", collection: \"caserecords\", kind: \"value\", path: \"referralOrganizationId\", writtenBy: \"a case's referring organization\" },\n { app: \"thread\", collection: \"caserecords\", kind: \"rows\", path: \"identifierEntries\", field: \"usedByOrgId\", writtenBy: \"a case number's organization\" },\n { app: \"thread\", collection: \"submissions\", kind: \"answers\", path: \"answers\", field: \"val\", writtenBy: \"a form answer naming an organization (the referring-organization question)\" },\n { app: \"thread\", collection: \"casesessions\", kind: \"list\", path: \"relevantOrganizationIds\", writtenBy: \"organizations added in a session\" },\n { app: \"thread\", collection: \"serviceinstances\", kind: \"value\", path: \"referralToOrganizationId\", writtenBy: \"a service's referral\" },\n { app: \"thread\", collection: \"serviceinstances\", kind: \"value\", path: \"serviceProviderOrganizationId\", writtenBy: \"a service's provider\" },\n { app: \"thread\", collection: \"personnelpeople\", kind: \"value\", path: \"organizationId\", writtenBy: \"staff records\" },\n { app: \"thread\", collection: \"personinteracteds\", kind: \"value\", path: \"organizationId\", writtenBy: \"people a case interacted with\" },\n\n { app: \"pave\", collection: \"protectedpeople\", kind: \"value\", path: \"organizationId\", writtenBy: \"a person's organization\" },\n { app: \"pave\", collection: \"relevantpersons\", kind: \"value\", path: \"organizationId\", writtenBy: \"a relevant person's organization\" },\n { app: \"pave\", collection: \"serviceinstances\", kind: \"value\", path: \"serviceProviderOrgId\", writtenBy: \"a service's provider\" },\n { app: \"pave\", collection: \"serviceinstances\", kind: \"value\", path: \"referralToOrganizationId\", writtenBy: \"a service's referral\" },\n { app: \"pave\", collection: \"programhousingenrollments\", kind: \"value\", path: \"providerOrgId\", writtenBy: \"a housing program's provider\" },\n { app: \"pave\", collection: \"householdpets\", kind: \"value\", path: \"providerOrgId\", writtenBy: \"a pet program's provider\" },\n { app: \"pave\", collection: \"disclosure_records\", kind: \"value\", path: \"recipientOrg\", writtenBy: \"a disclosure's recipient\" },\n { app: \"pave\", collection: \"reportingdestinationconfigs\", kind: \"list\", path: \"organizationIds\", writtenBy: \"reporting destinations\" },\n { app: \"pave\", collection: \"casesessions\", kind: \"list\", path: \"relevantOrganizationIds\", writtenBy: \"organizations added in a session\" },\n { app: \"pave\", collection: \"sharingsettings\", kind: \"count\", path: \"organizationId\", writtenBy: \"a sharing grant to a partner organization (never moved: sharing rules are not merged)\" },\n] as const);\n\n/** The apps that keep references in a database of their own. A copy is deleted only when each was checked. */\nexport const APP_DATABASE_KINDS = [\"thread\", \"pave\"] as const;\nexport type AppDatabaseKind = (typeof APP_DATABASE_KINDS)[number];\n\n/** One database a merge reads and re-points in. */\nexport interface MergeDatabase {\n app: ReferenceApp;\n name: string;\n db: Db;\n}\n\n/** A collection every database of that app has: how a mistyped database name is caught. */\nconst APP_MARKER: Record<AppDatabaseKind, string> = { thread: \"caserecords\", pave: \"protectedpeople\" };\n\n/**\n * Collections ONLY PAVE's database has. Thread's database and PAVE's both\n * hold `caserecords` and `protectedpeople` (each app has both models), so the\n * two markers above cannot tell one from the other: before 0.84.0 PAVE's\n * database named as Thread's (or the two names swapped) was accepted, each\n * was searched with the other app's field names, found nothing, and a copy\n * its case records still named could be deleted.\n *\n * A database is PAVE's when it has ANY of these, and Thread's only when it\n * has NONE. Any, not one in particular: PAVE has built every model's\n * collection at each start only since its index sweep (pave-2.0\n * `declaredIndexSweep`, 2026-11-09); on an older build a collection exists\n * only once something was saved in it. Thread names none of the three (its\n * disclosure model's collection is `disclosurerecords`, no underscore).\n */\nconst PAVE_ONLY_COLLECTIONS = [\"programhousingenrollments\", \"disclosure_records\", \"reportingdestinationconfigs\"] as const;\n\n/** Why `db` cannot be `app`'s database, or null when it can. A name that matches nothing would read as \"no references\". */\nexport async function appDatabaseProblem(app: AppDatabaseKind, name: string, db: Db): Promise<string | null> {\n const has = async (collection: string): Promise<boolean> =>\n (await db.listCollections({ name: collection }, { nameOnly: true }).toArray()).length > 0;\n if (!(await has(APP_MARKER[app]))) {\n return `'${name}' has no ${APP_MARKER[app]} collection, so it is not a ${APP_LABEL[app]} database (check the name)`;\n }\n let paves: string | null = null;\n for (const c of PAVE_ONLY_COLLECTIONS) {\n if (await has(c)) {\n paves = c;\n break;\n }\n }\n if (app === \"thread\" && paves) {\n return `'${name}' has a ${paves} collection, which only PAVE's database has, so it is not a Thread database (check the name)`;\n }\n if (app === \"pave\" && !paves) {\n return (\n `'${name}' has none of the collections only PAVE's database has (${PAVE_ONLY_COLLECTIONS.join(\", \")}), ` +\n \"so it is not a PAVE database (check the name)\"\n );\n }\n return null;\n}\n\nconst refPath = (r: Pick<OrgReference, \"kind\" | \"path\" | \"field\">): string =>\n r.kind === \"rows\" || r.kind === \"answers\" ? `${r.path}.${String(r.field)}` : r.path;\n\n/** The value at a dotted path of a document read from the driver. */\nfunction getPath(doc: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((v, k) => (v && typeof v === \"object\" ? (v as Row)[k] : undefined), doc);\n}\n\n/**\n * A list of ids with the copy's replaced by the kept organization's (in each\n * value's stored form). A list is a set to every app that reads one: where\n * the kept id is already in it, the copy's id is dropped instead.\n */\nfunction rewriteIds(driver: MergeDriver, list: readonly unknown[], copy: string, kept: unknown): unknown[] {\n const keptHex = comparableId(idText(kept));\n let hasKept = list.some((v) => idOf(driver, v) === keptHex);\n const out: unknown[] = [];\n for (const v of list) {\n if (idOf(driver, v) !== copy) out.push(v);\n else if (!hasKept) {\n out.push(inFormOf(driver, v, kept));\n hasKept = true;\n }\n }\n return out;\n}\n\n/** Sub-records with the copy's id in `field` replaced; a sub-record that would then repeat another one exactly is dropped. */\nfunction rewriteRows(driver: MergeDriver, rows: readonly unknown[], field: string, copy: string, kept: unknown): unknown[] {\n const key = (r: unknown): string =>\n r && typeof r === \"object\" ? JSON.stringify({ ...(r as Row), [field]: idOf(driver, (r as Row)[field]) }) : JSON.stringify(r);\n const isCopyRow = (r: unknown): boolean => !!r && typeof r === \"object\" && idOf(driver, (r as Row)[field]) === copy;\n const seen = new Set(rows.filter((r) => !isCopyRow(r)).map(key));\n const out: unknown[] = [];\n for (const r of rows) {\n if (!isCopyRow(r)) {\n out.push(r);\n continue;\n }\n const moved = { ...(r as Row), [field]: inFormOf(driver, (r as Row)[field], kept) };\n if (seen.has(key(moved))) continue;\n seen.add(key(moved));\n out.push(moved);\n }\n return out;\n}\n\n/** Form answers with the copy's id replaced inside each answer's list of values. */\nfunction rewriteAnswers(driver: MergeDriver, answers: readonly unknown[], field: string, copy: string, kept: unknown): unknown[] {\n return answers.map((a) => {\n const vals = a && typeof a === \"object\" ? (a as Row)[field] : undefined;\n return Array.isArray(vals) && vals.some((v) => idOf(driver, v) === copy)\n ? { ...(a as Row), [field]: rewriteIds(driver, vals, copy, kept) }\n : a;\n });\n}\n\n/** Every stored reference to `orgId` in the given databases, as the before-images of a re-point to `keptId`. Reads only. */\nasync function findReferences(driver: MergeDriver, dbs: readonly MergeDatabase[], orgId: unknown, keptId: unknown): Promise<MergeRefImage[]> {\n const out: MergeRefImage[] = [];\n const copy = comparableId(idText(orgId));\n for (const d of dbs) {\n for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app)) {\n if (ref.kind === \"count\") continue;\n const base = { db: d.name, collection: ref.collection, kind: ref.kind, path: ref.path, ...(ref.field ? { field: ref.field } : {}) };\n if (ref.kind === \"value\") {\n for (const from of idForms(driver, orgId)) {\n const docs = await d.db.collection(ref.collection).find({ [ref.path]: from } as Document, { projection: { _id: 1 } }).toArray();\n for (const doc of docs) out.push({ ...base, docId: doc._id, from, to: inFormOf(driver, from, keptId) });\n }\n continue;\n }\n // A list or a list of sub-records is moved whole, one line per document, so a\n // document holding the id in both stored forms is one compare-and-swap. Read\n // without promoting numbers, so an untouched value written back keeps its type.\n const docs = await d.db\n .collection(ref.collection)\n .find({ [refPath(ref)]: { $in: idForms(driver, orgId) } } as Document, { projection: { _id: 1, [ref.path]: 1 }, promoteValues: false })\n .toArray();\n for (const doc of docs) {\n const before = getPath(doc as Row, ref.path);\n if (!Array.isArray(before)) continue;\n const after =\n ref.kind === \"list\"\n ? rewriteIds(driver, before, copy, keptId)\n : ref.kind === \"rows\"\n ? rewriteRows(driver, before, String(ref.field), copy, keptId)\n : rewriteAnswers(driver, before, String(ref.field), copy, keptId);\n out.push({ ...base, docId: doc._id, from: copy, to: comparableId(idText(keptId)), before, after });\n }\n }\n }\n return out;\n}\n\n/** How many documents still name `orgId` in the given databases (an Agency's pointer and the never-moved kinds included). */\nasync function countReferences(driver: MergeDriver, dbs: readonly MergeDatabase[], orgId: unknown, only?: \"count\"): Promise<number> {\n let n = 0;\n for (const d of dbs) {\n for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app && (!only || r.kind === only))) {\n n += await d.db.collection(ref.collection).countDocuments({ [refPath(ref)]: { $in: idForms(driver, orgId) } } as Document);\n }\n if (d.app === \"platform\" && !only) {\n n += await d.db.collection(AGENCIES_COLLECTION).countDocuments({ organizationId: { $in: idForms(driver, orgId) } } as Document);\n }\n }\n return n;\n}\n\n/** Move one reference forward (`back` false) or back, only where it still holds what was there. True when it moved. */\nasync function repoint(db: Db, ref: MergeRefImage, back: boolean): Promise<boolean> {\n const coll = db.collection(ref.collection);\n if (ref.kind === \"value\") {\n const [from, to] = back ? [ref.to, ref.from] : [ref.from, ref.to];\n return (await coll.updateOne({ _id: ref.docId, [ref.path]: from } as Document, { $set: { [ref.path]: to } })).matchedCount === 1;\n }\n const [from, to] = back ? [ref.after, ref.before] : [ref.before, ref.after];\n return (await coll.updateOne({ _id: ref.docId, [ref.path]: from } as Document, { $set: { [ref.path]: to } })).matchedCount === 1;\n}\n\n/** Whether a reference still holds what the merge wrote. */\nasync function holdsMerged(db: Db, ref: MergeRefImage): Promise<boolean> {\n const filter = ref.kind === \"value\" ? { _id: ref.docId, [ref.path]: ref.to } : { _id: ref.docId, [ref.path]: ref.after };\n return (await db.collection(ref.collection).countDocuments(filter as Document)) === 1;\n}\n\n// ─── One merge, as a person named it ────────────────────────────────────────\n\n/** What a reviewer writes in the merge sheet's `approved` column. */\nexport const MERGE = \"merge\";\n\n/** What a reviewer writes in the sheet's `different_name_ok` to merge two rows whose names differ. */\nexport const YES = \"yes\";\n\nexport interface MergeLine {\n /** Sheet line (header = 1), for messages. */\n line: number;\n duplicateId: string;\n duplicateName: string;\n keptId: string;\n keptName: string;\n /** The line says in so many words that the two names differ and are one organization. */\n differentNameOk: boolean;\n}\n\n// ─── Planning ───────────────────────────────────────────────────────────────\n\n/**\n * Who is merging. `steward`: HTI Labs, acting on the one platform-wide\n * registry; no agency's list refuses the pair. `agency`: a merge inside one\n * agency's own list; the kept row must be readable where the copy is used\n * (the only rule before 0.84.0). See \"Who is merging\" at the top of this file.\n */\nexport type MergeActor = \"steward\" | \"agency\";\n\n/** What the caller states about a plan. Required: the rules never guess who is merging. */\nexport interface MergePlanOptions {\n mergedBy: MergeActor;\n}\n\nexport interface PlannedMerge {\n line: MergeLine;\n /** `merge` is written; `already` is done (the copy is gone and recorded); `skip` blocks the whole apply. */\n status: \"merge\" | \"already\" | \"skip\";\n detail: string;\n /** Stored names (\"\" when the row was not found). */\n duplicateName: string;\n keptName: string;\n /** Whose list each row sits in (`agencyScope`), in words. */\n duplicateList: string;\n keptList: string;\n flags: string[];\n /** Present on `merge`: what {@link executeMerges} writes, and its undo. */\n write?: MergeImage;\n}\n\n/**\n * Read every approved line and decide. Reads only. `skip` (any one blocks the\n * whole apply): either row is missing; a stored name is not the sheet's; the\n * copy is a canonical singleton, an Agency's own organization (it names an\n * Agency, or an Agency points at it: that is not a copy), or has programs;\n * the kept row is inactive or declined, or is a unit of the copy; the two\n * names differ and the line does not say `different_name_ok` = yes; and, only\n * when an `agency` merges ({@link MergeActor}), the kept row could not be seen\n * where the copy is used. A `steward`'s merge is never refused for that: the\n * registry is one platform-wide list, and the plan carries a flag instead.\n *\n * Seen, as Thread decides it (`organizationReadableBy`, `resolveUserCommunity`):\n * an Agency sees the organizations in its own list, and an organization of\n * another list only when the Agency's `state` is exactly that organization's\n * `community` (both non-blank; compared as stored, no trimming or case change).\n * So the kept row must be in the copy's list, or the Agency whose list the\n * copy is in must have a `state` equal to the kept row's `community`.\n *\n * @param dbs - the platform database first, then each app database the caller could open.\n * @param driver - the caller's ObjectId class and EJSON (see {@link MergeDriver}).\n * @param opts - who is merging ({@link MergePlanOptions}); stated by the caller, never inferred.\n */\nexport async function planMerges(\n dbs: readonly MergeDatabase[],\n lines: readonly MergeLine[],\n driver: MergeDriver,\n opts: MergePlanOptions,\n): Promise<PlannedMerge[]> {\n if (opts?.mergedBy !== \"steward\" && opts?.mergedBy !== \"agency\") {\n throw new Error(\"planMerges: say who is merging (mergedBy: 'steward' or 'agency')\");\n }\n const byAgency = opts.mergedBy === \"agency\";\n const platform = dbs[0] as MergeDatabase;\n const orgs = platform.db.collection(ORGANIZATIONS_COLLECTION);\n const agencies = platform.db.collection(AGENCIES_COLLECTION);\n const unchecked = APP_DATABASE_KINDS.filter((k) => !dbs.some((d) => d.app === k));\n const listAgency = async (org: Row): Promise<Row | null> =>\n blank(org.agencyScope)\n ? null\n : ((await agencies.findOne({ _id: { $in: idForms(driver, org.agencyScope) } } as Document, { projection: { name: 1, state: 1 } })) as Row | null);\n const listOf = async (org: Row): Promise<string> => {\n if (blank(org.agencyScope)) return \"in no agency's list\";\n const a = await listAgency(org);\n return `in the list of ${a ? text(a.name) || idText(org.agencyScope) : `agency ${idText(org.agencyScope)}, which is not in this database`}`;\n };\n /** Whether `copyId` is the kept row's parent, or its parent's parent, and so on (a cycle or a deep chain stops the walk). */\n const isUnitOf = async (kept: Row, copyId: string): Promise<boolean> => {\n const seen = new Set<string>();\n let parent = kept.parentOrgId;\n for (let depth = 0; depth < 25 && !blank(parent); depth += 1) {\n const id = idOf(driver, parent);\n if (id === null || seen.has(id)) return false;\n if (id === copyId) return true;\n seen.add(id);\n const next = (await orgs.findOne({ _id: { $in: idForms(driver, parent) } } as Document, { projection: { parentOrgId: 1 } })) as Row | null;\n parent = next?.parentOrgId;\n }\n return false;\n };\n const out: PlannedMerge[] = [];\n for (const line of lines) {\n const one = async (id: string): Promise<Row | null> => {\n const found = await orgs.find({ _id: { $in: idForms(driver, id) } } as Document).limit(2).toArray();\n return found.length === 1 ? (found[0] as Row) : null;\n };\n const dup = await one(line.duplicateId);\n const kept = await one(line.keptId);\n const base = {\n line,\n duplicateName: dup ? text(dup.name) : \"\",\n keptName: kept ? text(kept.name) : \"\",\n duplicateList: dup ? await listOf(dup) : \"\",\n keptList: kept ? await listOf(kept) : \"\",\n };\n const flags: string[] = [];\n const skip = (detail: string): void => {\n out.push({ ...base, status: \"skip\", detail, flags });\n };\n // The sheet reader refuses this too. It is refused here as well because the\n // plan is a public call (0.69.0): a copy merged into itself would have its\n // references \"moved\" to itself and then be deleted.\n if (comparableId(line.duplicateId) === comparableId(line.keptId)) {\n skip(\"the copy and the kept organization are the same row\");\n continue;\n }\n const mergedFrom = (kept?.legacy_ids as { merged_from?: unknown } | undefined)?.merged_from;\n const listed = Array.isArray(mergedFrom) && mergedFrom.includes(line.duplicateId);\n if (!dup && kept && listed) {\n out.push({ ...base, status: \"already\", detail: \"already merged: the copy is gone and the kept organization records its id\", flags });\n continue;\n }\n if (!dup || !kept) {\n skip(`no organization has the id ${!dup ? line.duplicateId : line.keptId}`);\n continue;\n }\n const misnamed = (\n [\n [\"copy\", line.duplicateName, base.duplicateName],\n [\"kept organization\", line.keptName, base.keptName],\n ] as const\n ).find(([, onSheet, stored]) => onSheet.trim() !== stored && onSheet.trim() !== sheetText(stored).trim());\n if (misnamed) {\n skip(`the sheet names the ${misnamed[0]} ${JSON.stringify(misnamed[1].trim())}, the database names it ${JSON.stringify(misnamed[2])}`);\n continue;\n }\n if (!blank(dup.canonicalKey)) {\n skip(\"the copy is a canonical singleton (Unknown / Anonymous); never merged\");\n continue;\n }\n const pointing = await agencies.countDocuments({ organizationId: { $in: idForms(driver, dup._id) } } as Document);\n if (!blank(dup.agencyId) || pointing) {\n skip(\"the copy is an Agency's own organization (it names an Agency, or an Agency points at it): that is not a copy\");\n continue;\n }\n // A copy's programs move with it when a steward merges (see \"Programs\" at the top of this file).\n let programs: MergeProgramsImage | undefined;\n if (Array.isArray(dup.programs) && dup.programs.length) {\n if (byAgency) {\n skip(\"the copy has programs; merging programs is not supported\");\n continue;\n }\n // Read without promoting numbers, so a row written back (the undo) or compared keeps each value's stored type.\n const stored = async (id: unknown): Promise<unknown> =>\n ((await orgs.findOne({ _id: id } as Document, { projection: { programs: 1 }, promoteValues: false })) as Row | null)?.programs;\n const [keptRows, dupRows] = [await stored(kept._id), await stored(dup._id)];\n if (!Array.isArray(dupRows) || dupRows.length !== dup.programs.length) {\n skip(\"the copy's programs changed while the plan was read; plan again\");\n continue;\n }\n const keptHad = Array.isArray(keptRows);\n const keptBefore = keptHad ? (keptRows as unknown[]) : [];\n const idOfProgram = (r: unknown): string => (r && typeof r === \"object\" ? text((r as Row).programId) : \"\");\n const keptIds = new Set(keptBefore.map(idOfProgram).filter(Boolean));\n const twin = dupRows.map(idOfProgram).find((id) => id && keptIds.has(id));\n if (twin) {\n skip(`a program of the copy has the same id as a program of the kept organization (${twin}); two programs cannot share an id`);\n continue;\n }\n programs = { keptHad, keptBefore, moved: dupRows as unknown[] };\n const liveName = (r: unknown): string => {\n const row = r && typeof r === \"object\" ? (r as Row) : {};\n return typeof row.name === \"string\" && isLiveOrganizationProgram(row as { status?: string; reviewStatus?: string }) ? programNameKey(row.name) : \"\";\n };\n const keptNames = new Set(keptBefore.map(liveName).filter(Boolean));\n const same = programs.moved.filter((r) => liveName(r) && keptNames.has(liveName(r))).map((r) => text((r as Row).name));\n if (same.length) {\n flags.push(\n `${same.length} program(s) of the copy have the name of a live program of the kept organization (${same.join(\", \")}); ` +\n \"both are kept, as two programs\",\n );\n }\n }\n if (!isListedOrganization(kept as { status?: number; reviewStatus?: string })) {\n skip(\"the kept organization is inactive or declined: nothing is merged into a row that is not offered\");\n continue;\n }\n if (await isUnitOf(kept, comparableId(idText(dup._id)))) {\n skip(\"the kept organization is a unit of the copy (the copy is on its chain of parent organizations)\");\n continue;\n }\n if (comparableName(dup.name) !== comparableName(kept.name)) {\n if (!line.differentNameOk) {\n skip(`the two names differ: write ${YES} in different_name_ok on this line if they are one organization`);\n continue;\n }\n flags.push(\"the names differ; the sheet says they are one organization\");\n }\n const sameList = !blank(kept.agencyScope) && idText(kept.agencyScope) === idText(dup.agencyScope);\n const viewer = await listAgency(dup);\n const state = typeof viewer?.state === \"string\" ? viewer.state : \"\";\n const community = typeof kept.community === \"string\" ? kept.community : \"\";\n if (!sameList && !(state !== \"\" && state === community)) {\n if (byAgency) {\n skip(\n `the kept organization could not be seen by the agency whose list the copy is in: the copy is ${base.duplicateList} ` +\n `(that agency's state ${JSON.stringify(state)}), the kept row is ${base.keptList} (community ${JSON.stringify(community)}). ` +\n \"An agency sees another list's organization only when its state is exactly that organization's community. \" +\n \"The kept row's list or community is corrected first, by a deliberate edit\",\n );\n continue;\n }\n // A steward's merge is judged against the one registry, so this refuses nothing. Where the copy sits in an\n // agency's list, that agency's users read the kept row through Thread's and PAVE's as-built per-agency\n // rule until both apps read the one list: said, so the steward knows what they will see meanwhile.\n if (viewer) {\n // With programs it is more than a name: that agency's program pickers read the kept row the same way.\n flags.push(\n `until Thread and PAVE show every agency the one organization list, ${text(viewer.name) || \"the agency that added the copy\"} ` +\n \"may not see the kept organization's name on its records that move\" +\n (programs ? `, or pick the ${programs.moved.length} program(s) that move to it` : \"\"),\n );\n }\n }\n const keyed = !blank(dup.key);\n if (keyed) {\n flags.push(\n `the copy carries the identifier ${String(dup.key)}: identifiers never move` +\n `${blank(kept.key) ? \" (the kept organization has none; the key sheet gives it one)\" : \"\"}, so the copy is kept as inactive`,\n );\n }\n const refs = await findReferences(driver, dbs, dup._id, kept._id);\n const grants = await countReferences(driver, dbs, dup._id, \"count\");\n const outcome = keyed || grants || unchecked.length ? \"retire\" : \"delete\";\n const moves = new Map<string, number>();\n for (const r of refs) {\n const k = `${r.db} ${r.collection}.${refPath(r)}`;\n moves.set(k, (moves.get(k) ?? 0) + 1);\n }\n // The copy's programs move even when an app's database could not be checked, and the copy then stays (inactive)\n // for that database's sake. A record there that names the copy with one of its programs keeps naming the copy:\n // said, with the remedy, so nobody takes the merge for finished.\n if (programs && unchecked.length) {\n const where = unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(\" and \");\n flags.push(\n `${where} could not be checked: a record there that names the copy with one of its programs still names the copy, ` +\n \"while the programs are the kept organization's now; run the merge again with every database to move those records\",\n );\n }\n const why = [\n ...(unchecked.length ? [`references in ${unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(\" and \")} could not be checked`] : []),\n ...(grants ? [`${grants} sharing grant(s) name the copy, and sharing rules are never moved`] : []),\n ];\n const then =\n outcome === \"delete\"\n ? \"then the copy is deleted\"\n : `then the copy is kept as inactive${why.length ? `: ${why.join(\"; \")}` : \"\"}`;\n out.push({\n ...base,\n status: \"merge\",\n detail:\n `${moves.size ? `moves ${[...moves].map(([k, n]) => `${n} in ${k}`).join(\", \")}` : \"nothing points at the copy\"}; ` +\n `${programs ? `its ${programs.moved.length} program(s) move to the kept organization; ` : \"\"}${then}`,\n flags,\n write: {\n duplicateId: dup._id,\n duplicateName: base.duplicateName,\n keptId: kept._id,\n keptName: base.keptName,\n duplicate: dup as Document,\n refs,\n outcome,\n addsLegacyEntry: !listed,\n ...(programs ? { programs } : {}),\n },\n });\n }\n return out;\n}\n\n/** One planned line as printed: both rows by stored name and list, what moves, what happens to the copy, any flag. */\nexport function formatPlannedMerge(p: PlannedMerge): string {\n return (\n ` ${p.status.padEnd(6)} ${p.line.duplicateId} ${p.duplicateName || \"(no organization)\"}${p.duplicateList ? ` (${p.duplicateList})` : \"\"}` +\n ` -> ${p.line.keptId} ${p.keptName || \"(no organization)\"}${p.keptList ? ` (${p.keptList})` : \"\"}\\n` +\n ` ${p.detail}${p.flags.map((f) => ` [${f}]`).join(\"\")}`\n );\n}\n\n// ─── Writing ────────────────────────────────────────────────────────────────\n\n/** Said when a copy that changed under the merge could not be deleted or retired after its programs were added to the kept row. */\nconst COPY_KEEPS_PROGRAMS = \", and its programs were added to the kept organization while the copy still lists them: undo this merge and run it again\";\n\nexport interface ExecutedMerge {\n merge: MergeImage;\n /** `deleted` / `retired`: the line is done. `changed`: a row moved since the plan. `failed`: the database refused. */\n status: \"deleted\" | \"retired\" | \"changed\" | \"failed\";\n moved: number;\n detail?: string;\n}\n\n/**\n * Carry out each merge, one at a time: record the copy's id on the kept row,\n * move each reference (only where it still holds what the plan read), then\n * count what still names the copy. Nothing left and every app database\n * checked: the copy is deleted. Otherwise it is marked inactive. Either\n * happens only while the copy is still exactly as planned. The kept row gets\n * `legacy_ids.merged_from` and, when the copy has programs, those rows added\n * to the end of its own (in the one write, and only while its programs are\n * still as planned): nothing else, not even a new `updatedTime`.\n */\nexport async function executeMerges(\n dbs: readonly MergeDatabase[],\n merges: readonly MergeImage[],\n now: Date,\n driver: MergeDriver,\n): Promise<ExecutedMerge[]> {\n const orgs = (dbs[0] as MergeDatabase).db.collection(ORGANIZATIONS_COLLECTION);\n const dbNamed = new Map(dbs.map((d) => [d.name, d.db]));\n const out: ExecutedMerge[] = [];\n for (const merge of merges) {\n let moved = 0;\n try {\n const programs = merge.programs;\n const kept = await orgs.updateOne(\n {\n _id: merge.keptId,\n status: { $in: [null, ORGANIZATION_STATUS.ACTIVE] },\n reviewStatus: { $ne: \"rejected\" },\n // The copy's programs join the kept row's only while that list is still exactly as the plan read it\n // (`null` matches a row that stores no list).\n ...(programs ? { programs: programs.keptHad ? programs.keptBefore : null } : {}),\n } as Document,\n {\n $addToSet: { \"legacy_ids.merged_from\": idText(merge.duplicateId) },\n // Added to the end: the kept row's own program rows are not rewritten, not even re-typed.\n ...(programs ? (programs.keptHad ? { $push: { programs: { $each: programs.moved } } } : { $set: { programs: programs.moved } }) : {}),\n },\n );\n if (kept.matchedCount !== 1) {\n out.push({\n merge,\n status: \"changed\",\n moved,\n detail: `the kept organization is gone or no longer offered${programs ? \", or its programs changed,\" : \"\"} since the plan; nothing was written`,\n });\n continue;\n }\n let stale = 0;\n for (const ref of merge.refs) {\n if (await repoint(dbNamed.get(ref.db) as Db, ref, false)) moved += 1;\n else stale += 1;\n }\n const left = await countReferences(driver, dbs, merge.duplicateId);\n const asPlanned = { _id: merge.duplicateId, updatedTime: merge.duplicate.updatedTime ?? null, status: merge.duplicate.status ?? null } as Document;\n if (merge.outcome === \"delete\" && left === 0) {\n const res = await orgs.deleteOne(asPlanned);\n out.push(\n res.deletedCount === 1\n ? { merge, status: \"deleted\", moved }\n : { merge, status: \"changed\", moved, detail: `the copy changed since the plan and was left as it is; its references were moved${programs ? COPY_KEEPS_PROGRAMS : \"\"}` },\n );\n continue;\n }\n // A copy kept as inactive keeps no programs: they are the kept organization's now, under the same ids.\n const res = await orgs.updateOne(asPlanned, { $set: { status: ORGANIZATION_STATUS.INACTIVE, updatedTime: now, ...(programs ? { programs: [] } : {}) } });\n const why =\n merge.outcome === \"delete\"\n ? `${left} reference(s) still point at the copy${stale ? ` (${stale} changed since the plan)` : \"\"}, so it was not deleted`\n : left\n ? `${left} reference(s) still point at the copy`\n : undefined;\n out.push(\n res.matchedCount === 1\n ? { merge, status: \"retired\", moved, ...(why ? { detail: why } : {}) }\n : { merge, status: \"changed\", moved, detail: `the copy changed since the plan and was left as it is; its references were moved${programs ? COPY_KEEPS_PROGRAMS : \"\"}` },\n );\n } catch (err) {\n out.push({ merge, status: \"failed\", moved, detail: message(err) });\n }\n }\n return out;\n}\n\n// ─── Undo ───────────────────────────────────────────────────────────────────\n\nexport interface MergeRollbackRow {\n image: MergeImage;\n /** `restore`: everything can be put back. `partial`: some of it. `skip`: nothing to do, or nothing safe to do. */\n status: \"restore\" | \"partial\" | \"skip\";\n detail: string;\n}\n\n/** A document compared whole, whatever order its top-level keys come back in. */\nfunction sameDocument(driver: MergeDriver, x: Document, y: Document): boolean {\n const sorted = (d: Document): Document => Object.fromEntries(Object.keys(d).sort().map((k) => [k, d[k] as unknown]));\n const strict = (d: Document): string => driver.EJSON.stringify({ v: d }, { relaxed: false });\n return strict(sorted(x)) === strict(sorted(y));\n}\n\n/**\n * Undo each merge of a before-images file, newest first; with `dryRun`, only\n * say what would happen. The copy comes back first (re-inserted exactly from\n * its before-image when it was deleted; its `status` and `updatedTime`\n * restored when it was marked inactive), then each reference that still holds\n * what the merge wrote goes back (a list or a list of sub-records is put back\n * whole, so a copy's id the merge dropped returns too), then the copy's id is\n * taken off the kept row's `legacy_ids`, only when this run put it there. A\n * reference somebody has changed since is left alone and counted.\n *\n * @param dbFor - a handle on a database of the same server, by name.\n */\nexport async function rollbackMerges(\n dbFor: (name: string) => Db,\n images: MergeBeforeImages,\n opts: { dryRun: boolean },\n driver: MergeDriver,\n): Promise<MergeRollbackRow[]> {\n const orgs = dbFor(images.db).collection(ORGANIZATIONS_COLLECTION);\n const out: MergeRollbackRow[] = [];\n for (const image of [...(images.merges ?? [])].reverse()) {\n const said: string[] = [];\n let partial = false;\n const before = image.duplicate;\n const now = (await orgs.findOne({ _id: image.duplicateId } as Document)) as Document | null;\n const programs = image.programs;\n const retiredHere =\n !!now &&\n sameDocument(driver, now, {\n ...before,\n status: ORGANIZATION_STATUS.INACTIVE,\n updatedTime: images.appliedTime,\n // A copy the merge kept as inactive was left with no programs (they moved).\n ...(programs ? { programs: [] } : {}),\n });\n // True once the copy is back as it was before the merge (its programs included).\n let copyBack = true;\n if (!now) {\n said.push(\"put the deleted copy back exactly as it was\");\n if (!opts.dryRun) await orgs.insertOne(before);\n } else if (retiredHere) {\n said.push(before.status === ORGANIZATION_STATUS.INACTIVE ? \"put the copy back as it was before this run\" : \"make the copy active again, as it was\");\n if (!opts.dryRun) await orgs.replaceOne({ _id: image.duplicateId, updatedTime: images.appliedTime } as Document, before);\n } else if (sameDocument(driver, now, before)) {\n said.push(\"the copy is as it was\");\n } else {\n partial = true;\n copyBack = false;\n said.push(\"the copy has changed since the merge: left as it is\");\n }\n let back = 0;\n let moved = 0;\n for (const ref of image.refs) {\n const db = dbFor(ref.db);\n if (!(await holdsMerged(db, ref))) moved += 1;\n else if (opts.dryRun || (await repoint(db, ref, true))) back += 1;\n else moved += 1;\n }\n if (image.refs.length) {\n said.push(`${back} of ${image.refs.length} reference(s) back to the copy${moved ? ` (${moved} changed since the merge: left alone)` : \"\"}`);\n }\n if (moved) partial = true;\n // The copy's programs come off the kept row, only while its list is still exactly as the merge left it.\n let programsBack = false;\n if (programs) {\n const merged = [...programs.keptBefore, ...programs.moved];\n const holds = (await orgs.countDocuments({ _id: image.keptId, programs: merged } as Document)) === 1;\n const asBefore = (await orgs.countDocuments({ _id: image.keptId, programs: programs.keptHad ? programs.keptBefore : null } as Document)) === 1;\n if (holds) {\n programsBack = true;\n said.push(`take the copy's ${programs.moved.length} program(s) off the kept organization`);\n if (!opts.dryRun) {\n await orgs.updateOne(\n { _id: image.keptId, programs: merged } as Document,\n programs.keptHad ? { $set: { programs: programs.keptBefore } } : { $unset: { programs: \"\" } },\n );\n }\n } else if (!asBefore) {\n partial = true;\n said.push(\n \"the kept organization's programs have changed since the merge: left as they are\" +\n (copyBack ? \" (the copy has its programs back too, so the same program ids are on both organizations until one list is corrected)\" : \"\"),\n );\n }\n }\n const entry = idText(image.duplicateId);\n const listed = image.addsLegacyEntry\n ? await orgs.countDocuments({ _id: image.keptId, \"legacy_ids.merged_from\": entry } as Document)\n : 0;\n if (listed) {\n said.push(\"take the copy's id off the kept organization's legacy_ids\");\n if (!opts.dryRun) {\n await orgs.updateOne({ _id: image.keptId } as Document, { $pull: { \"legacy_ids.merged_from\": entry } } as Document);\n // Leave no empty shell behind: the row had no such field before its first merge.\n await orgs.updateOne({ _id: image.keptId, \"legacy_ids.merged_from\": { $size: 0 } } as Document, { $unset: { \"legacy_ids.merged_from\": \"\" } });\n await orgs.updateOne({ _id: image.keptId, legacy_ids: {} } as Document, { $unset: { legacy_ids: \"\" } });\n }\n } else if (!image.addsLegacyEntry) {\n said.push(\"the copy's id stays on the kept organization's legacy_ids (an earlier run put it there)\");\n }\n const anything = !now || retiredHere || back > 0 || listed > 0 || programsBack;\n out.push({\n image,\n status: !anything ? \"skip\" : partial ? \"partial\" : \"restore\",\n detail: anything ? said.join(\"; \") : `nothing left to undo (${said.join(\"; \")})`,\n });\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,IAAM,OAAO,CAAC,MAAwB,OAAO,MAAM,WAAW,EAAE,KAAK,IAAI;AAGlE,SAAS,eAAe,OAAwB;AACrD,SAAO,KAAK,KAAK,EACd,UAAU,MAAM,EAChB,YAAY,EACZ,QAAQ,MAAM,OAAO,EACrB,QAAQ,eAAe,GAAG,EAC1B,KAAK,EACL,QAAQ,SAAS,EAAE;AACxB;AAOO,SAAS,aAAa,OAAuB;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AAE;AAAA,UAC9F;AAAA,QACF;AAAA,MACF,WAAW,CAAC,UAAU;AACpB,kBAAU;AACV,aAAK;AAAA,UACH,qFACG,WAAW,yHAAyH;AAAA,QACzI;AAAA,MACF;AAAA,IACF;AACA,UAAM,QAAQ,OAAO,MAAM,WAAW;AACtC,UAAM,SAAS,MAAM,kBACjB,MAAM,KAAK,eAAe,EAAE,KAAK,MAAM,QAAQ,0BAA0B,MAAM,CAAa,IAC5F;AACJ,QAAI,QAAQ;AACV,WAAK,KAAK,2DAA2D;AACrE,UAAI,CAAC,KAAK,QAAQ;AAChB,cAAM,KAAK,UAAU,EAAE,KAAK,MAAM,OAAO,GAAe,EAAE,OAAO,EAAE,0BAA0B,MAAM,EAAE,CAAa;AAElH,cAAM,KAAK,UAAU,EAAE,KAAK,MAAM,QAAQ,0BAA0B,EAAE,OAAO,EAAE,EAAE,GAAe,EAAE,QAAQ,EAAE,0BAA0B,GAAG,EAAE,CAAC;AAC5I,cAAM,KAAK,UAAU,EAAE,KAAK,MAAM,QAAQ,YAAY,CAAC,EAAE,GAAe,EAAE,QAAQ,EAAE,YAAY,GAAG,EAAE,CAAC;AAAA,MACxG;AAAA,IACF,WAAW,CAAC,MAAM,iBAAiB;AACjC,WAAK,KAAK,yFAAyF;AAAA,IACrG;AACA,UAAM,WAAW,CAAC,OAAO,eAAe,OAAO,KAAK,SAAS,KAAK;AAClE,QAAI,KAAK;AAAA,MACP;AAAA,MACA,QAAQ,CAAC,WAAW,SAAS,UAAU,YAAY;AAAA,MACnD,QAAQ,WAAW,KAAK,KAAK,IAAI,IAAI,yBAAyB,KAAK,KAAK,IAAI,CAAC;AAAA,IAC/E,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["import_zod","import_zod","text","text","text","import_zod","text","optionalText","text","HEX_24","docs","from","to","line","res"]}
|
|
1
|
+
{"version":3,"sources":["../../src/orgMerge/index.ts","../../src/orgMerge/support.ts","../../src/orgDirectory/orgRecord.ts","../../src/orgDirectory/vocabulary.ts","../../src/orgDirectory/schemas.ts","../../src/orgDirectory/programDetails.ts","../../src/orgDirectory/rules.ts","../../src/orgDirectory/read.ts","../../src/pointsOfContact/schemas.ts","../../src/cvcs/preferredContactMethod.v1.1.0.json","../../src/pointsOfContact/vocabulary.ts","../../src/serviceListings/vocabulary.ts","../../src/serviceListings/schemas.ts","../../src/serviceListings/read.ts","../../src/orgMerge/orgMerge.ts"],"sourcesContent":["/**\n * @htilabs/platform-common-models/org-merge\n *\n * Folding a copy of an organization into the one that is kept: the plan, the\n * write and its undo (`orgMerge.ts`). Server only: it reads and writes\n * through MongoDB driver handles the caller opens. Used by the registry tool\n * (`fill-org-registry --apply-merges`) and by the Platform's Admin Hub\n * (\"Merge into another organization\"). Subpath only.\n *\n * The caller says who is merging (`planMerges(dbs, lines, driver, { mergedBy })`,\n * 0.84.0): `steward` for HTI Labs acting on the one platform-wide registry,\n * `agency` for a merge inside one agency's own list. See `orgMerge.ts`.\n */\nexport * from \"./types.js\";\nexport * from \"./support.js\";\nexport * from \"./orgMerge.js\";\n","/**\n * Small value helpers the merge shares with the registry fill script\n * (`scripts/lib/orgRegistryFill.ts` re-exports them).\n */\nconst text = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\");\n\n/** A name reduced for comparison: case, punctuation and a leading \"the\" dropped. */\nexport function comparableName(value: unknown): string {\n return text(value)\n .normalize(\"NFKD\")\n .toLowerCase()\n .replace(/&/g, \" and \")\n .replace(/[^a-z0-9]+/g, \" \")\n .trim()\n .replace(/^the /, \"\");\n}\n\n/**\n * An organization id as text, comparable: a 24-hex database id in lower case\n * (the form an ObjectId prints as), any other text id exactly as stored. A\n * text id is never case-folded: \"Org-A\" and \"org-a\" are two rows.\n */\nexport function comparableId(value: string): string {\n const s = value.trim();\n return /^[0-9a-fA-F]{24}$/.test(s) ? s.toLowerCase() : s;\n}\n\n/** A spreadsheet must not evaluate an org name as a formula. */\nexport const sheetText = (v: unknown): string => {\n const s = typeof v === \"string\" ? v : v == null ? \"\" : String(v);\n return /^[=+\\-@\\t\\r]/.test(s) ? `'${s}` : s;\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-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 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 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","/**\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 reads the seat's contact log (`seat_contacts`)\n * when the reader's seat resolver carries it (`withSeatContactLogs`,\n * pl-9h4, 0.87.0); a seat with no log yet still reads ONE email and ONE\n * phone from `users`.\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 \"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 * @htilabs/platform-common-models/service-listings — the closed vocabularies a\n * Service Listing stores. Contract: platform `docs/SERVICE_LISTING_CONTRACT.md`.\n */\n\n/** The survey's two pick lists (profile § 5). */\nexport const LISTING_TIERS = [\"primary\", \"additional\"] as const;\nexport type ListingTier = (typeof LISTING_TIERS)[number];\n\n/**\n * How a service is reached (profile § 5; prototype\n * `Service Registry/README.md` @ 2103f288, \"CSV columns\").\n */\nexport const ACCESS_PATHS = [\n \"Referral required\",\n \"Hotline\",\n \"Walk-in\",\n \"Law enforcement initiated\",\n \"Court/probation initiated\",\n] as const;\nexport type AccessPath = (typeof ACCESS_PATHS)[number];\n\n/** What is STORED. `stale` is never stored: it is computed on read. */\nexport const STORED_VERIFICATION_STATUSES = [\"pending\", \"verified\"] as const;\nexport type StoredVerificationStatus = (typeof STORED_VERIFICATION_STATUSES)[number];\n\n/** What a READER sees (profile § 5: pending | verified | stale). */\nexport const VERIFICATION_STATUSES = [\"pending\", \"verified\", \"stale\"] as const;\nexport type VerificationStatus = (typeof VERIFICATION_STATUSES)[number];\n\n/** Where a listing was created: the Program's enum. Null on a steward sheet row. */\nexport const ADDED_IN_APPS = [\"pave\", \"thread\", \"leads\", \"platform\"] as const;\nexport type AddedInApp = (typeof ADDED_IN_APPS)[number];\n\n/** HTI Labs' review of a listing added from an app or the survey. */\nexport const LISTING_REVIEW_STATUSES = [\"pending\", \"confirmed\", \"rejected\"] as const;\nexport type ListingReviewStatus = (typeof LISTING_REVIEW_STATUSES)[number];\n\n/**\n * The lane a listing arrived through (profile census items 1, 2 and 9). It is\n * stored as `origin`. Every lane is human entry: UDD `dataSource.source_category`\n * is `human` for all three, so the lane is the provenance fact.\n */\nexport const LISTING_ORIGINS = [\"survey\", \"admin_hub\", \"steward_seed\"] as const;\nexport type ListingOrigin = (typeof LISTING_ORIGINS)[number];\n\n/** The two lanes an agency mints through. The steward seed is a separate path. */\nexport const MINT_ORIGINS = [\"survey\", \"admin_hub\"] as const;\nexport type MintOrigin = (typeof MINT_ORIGINS)[number];\n\n/** The verification window in months (profile § 6 q1 default; owner and length are Crysta's). */\nexport const STALE_WINDOW_MONTHS = 12;\n","/**\n * @htilabs/platform-common-models/service-listings — Zod schemas for the\n * `platform-db.servicelistings` document and the bodies its writers accept.\n *\n * Contract (fields, id universes, read rules, writers): platform\n * `docs/SERVICE_LISTING_CONTRACT.md`. This file declares shapes only.\n *\n * Three body schemas, so a writer cannot reach a field its lane does not own:\n * - {@link ServiceListingDetailsSchema}: the descriptive fields an edit may\n * change. No identity, verification, arrival or removal keys.\n * - {@link MintListingBodySchema}: details plus `vscat_key`. What the survey\n * and the Admin Hub send. No `id`, no verification: `.strict()` refuses them.\n * - {@link SeedListingBodySchema}: the steward seed only. It may also carry the\n * sheet's `id`, `verification_status` and `last_verified`.\n *\n * `org_id` is in none of them: the writer passes it as its own argument, from\n * the caller's scope, never from a body.\n */\n\nimport { z } from \"zod\";\n\nimport {\n ACCESS_PATHS,\n ADDED_IN_APPS,\n LISTING_ORIGINS,\n LISTING_REVIEW_STATUSES,\n LISTING_TIERS,\n STORED_VERIFICATION_STATUSES,\n} from \"./vocabulary.js\";\n\nconst ISO_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst LISTING_ID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;\n\n/** A real calendar date as YYYY-MM-DD. */\nexport const IsoDateSchema = z\n .string()\n .regex(ISO_DATE, \"Expected an ISO date (YYYY-MM-DD).\")\n .refine((s) => {\n const d = new Date(`${s}T00:00:00Z`);\n return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === s;\n }, \"Not a real calendar date.\");\n\n/** A non-empty trimmed id string (a directory id in its canonical string form). */\nexport const DirectoryIdSchema = z.string().trim().min(1);\n\n/** A listing id: the sheet's `service_id` shape, or `svc-<hex>` minted by the store. */\nexport const ListingIdSchema = z\n .string()\n .regex(LISTING_ID, \"A listing id is letters, digits, '.', '_' or '-'.\");\n\n/** A CVC-22 key slug (the join). Whether it names a listable category is checked by the writer. */\nexport const ServiceCategoryKeySchema = z.string().trim().regex(/^[a-z][a-z0-9_]*$/, \"Not a CVC key.\");\n\nconst text = z.string().trim();\nconst optionalText = text.nullable().optional();\n\n/** The descriptive fields: what an edit may change. */\nexport const ServiceListingDetailsSchema = z\n .object({\n program_id: DirectoryIdSchema.nullable().optional(),\n agency_id: DirectoryIdSchema.nullable().optional(),\n tier: z.enum(LISTING_TIERS).nullable().optional(),\n ht_specific: z.boolean().nullable().optional(),\n sector: optionalText,\n populations: z.array(text.min(1)).optional(),\n access_path: z.enum(ACCESS_PATHS).nullable().optional(),\n jurisdiction: optionalText,\n hours: optionalText,\n eligibility: optionalText,\n cost: optionalText,\n contact_name: optionalText,\n contact_email: optionalText,\n contact_phone: optionalText,\n contact_city: optionalText,\n contact_state: optionalText,\n confidential: z.boolean().optional(),\n })\n .strict();\nexport type ServiceListingDetails = z.infer<typeof ServiceListingDetailsSchema>;\n\n/** An edit: one or more descriptive fields. */\nexport const ServiceListingPatchSchema = ServiceListingDetailsSchema.refine(\n (b) => Object.keys(b).length > 0,\n { message: \"A listing edit must name at least one field.\" },\n);\nexport type ServiceListingPatch = z.infer<typeof ServiceListingPatchSchema>;\n\n/** A survey or Admin Hub mint. */\nexport const MintListingBodySchema = ServiceListingDetailsSchema.extend({\n vscat_key: ServiceCategoryKeySchema,\n}).strict();\nexport type MintListingBody = z.infer<typeof MintListingBodySchema>;\n\n/** A steward seed row. A verified row carries its date. */\nexport const SeedListingBodySchema = MintListingBodySchema.extend({\n id: ListingIdSchema.optional(),\n verification_status: z.enum(STORED_VERIFICATION_STATUSES).optional(),\n last_verified: IsoDateSchema.nullable().optional(),\n})\n .strict()\n .refine((b) => b.verification_status !== \"verified\" || !!b.last_verified, {\n message: \"A verified listing carries the date it was verified (last_verified).\",\n path: [\"last_verified\"],\n });\nexport type SeedListingBody = z.infer<typeof SeedListingBodySchema>;\n\nconst nullableText = z.string().nullable();\n\n/** The stored document, without Mongo's `_id`. Readers parse every row with it. */\nexport const StoredServiceListingSchema = z.object({\n id: ListingIdSchema,\n org_id: DirectoryIdSchema,\n program_id: DirectoryIdSchema.nullable(),\n agency_id: DirectoryIdSchema.nullable(),\n vscat_key: ServiceCategoryKeySchema,\n vscat_code: z.string(),\n vscat_label: z.string(),\n tier: z.enum(LISTING_TIERS).nullable(),\n ht_specific: z.boolean().nullable(),\n sector: nullableText,\n populations: z.array(z.string()),\n access_path: z.enum(ACCESS_PATHS).nullable(),\n jurisdiction: nullableText,\n hours: nullableText,\n eligibility: nullableText,\n cost: nullableText,\n contact_name: nullableText,\n contact_email: nullableText,\n contact_phone: nullableText,\n contact_city: nullableText,\n contact_state: nullableText,\n confidential: z.boolean(),\n verification_status: z.enum(STORED_VERIFICATION_STATUSES),\n last_verified: IsoDateSchema.nullable(),\n origin: z.enum(LISTING_ORIGINS),\n added_by: nullableText,\n added_in_app: z.enum(ADDED_IN_APPS).nullable(),\n review_status: z.enum(LISTING_REVIEW_STATUSES).nullable(),\n removal_requested_at: nullableText,\n removal_requested_by: nullableText,\n version: z.number().int().min(1),\n createdBy: nullableText,\n createdAt: z.string(),\n updatedBy: nullableText,\n updatedAt: z.string(),\n});\nexport type StoredServiceListing = z.infer<typeof StoredServiceListingSchema>;\n","/**\n * @htilabs/platform-common-models/service-listings — the collection, its\n * indexes and the one raw-driver read every app uses.\n *\n * No driver import: the reader takes any object with the MongoDB driver's\n * `collection(name).find(filter).toArray()` shape, so PAVE, Thread, LEADS and\n * the Platform pass their own `Db`.\n */\n\nimport type { ServiceCategories } from \"./categories.js\";\nimport { isListedOnNetwork, toListingView, type ServiceListingView } from \"./rules.js\";\nimport { StoredServiceListingSchema, type StoredServiceListing } from \"./schemas.js\";\n\nexport const SERVICE_LISTINGS_COLLECTION = \"servicelistings\";\n\n/** One index the store creates. */\nexport interface ServiceListingIndexSpec {\n name: string;\n key: Readonly<Record<string, 1>>;\n unique: boolean;\n}\n\n/**\n * The store's indexes. `offering` is the uniqueness rule: one listing per\n * (org, program, category). A null `program_id` indexes as a value, so an org\n * lists a category once at the org level. Its prefix serves the org and the\n * org + program reads.\n */\nexport const SERVICE_LISTING_INDEXES = {\n id: { name: \"servicelistings_id_unique\", key: { id: 1 }, unique: true },\n offering: {\n name: \"servicelistings_offering_unique\",\n key: { org_id: 1, program_id: 1, vscat_key: 1 },\n unique: true,\n },\n category: { name: \"servicelistings_vscat_key\", key: { vscat_key: 1 }, unique: false },\n} as const satisfies Record<string, ServiceListingIndexSpec>;\n\n/** A driver ObjectId, or anything that prints itself as one. */\nexport interface ObjectIdLike {\n toHexString(): string;\n}\n\n/** A directory id as a caller holds it: its string form or an ObjectId. */\nexport type DirectoryIdInput = string | ObjectIdLike;\n\n/**\n * The stored forms of a directory id. The store always writes the canonical\n * STRING form, so the string matches every row; an ObjectId the caller holds is\n * included as well, in case a row was ever written with one.\n */\nexport function directoryIdForms(id: DirectoryIdInput): unknown[] {\n return typeof id === \"string\" ? [id] : [id.toHexString(), id];\n}\n\n/** The read queries the apps make. */\nexport type ServiceListingQuery =\n /**\n * An org's listings. `programId` absent (or undefined): the rollup across its\n * programs. A string: that program's listings. `null`: the org-level listings.\n */\n | { orgId: DirectoryIdInput; programId?: string | null }\n /** Every listing of one or more CVC-22 categories, by key. */\n | { categoryKeys: readonly string[] }\n /** One listing. */\n | { id: string };\n\n/** The minimal driver surface the reader needs. */\nexport interface ListingsDbLike {\n collection(name: string): {\n find(filter: Record<string, unknown>): { toArray(): Promise<unknown[]> };\n };\n}\n\nexport interface ReadServiceListingsOptions {\n now?: Date;\n categories: ServiceCategories;\n /** Called with each stored row that fails the schema; such a row is not returned. */\n onInvalid?: (raw: unknown, issues: string) => void;\n}\n\n/** The Mongo filter for a query. Exported so a writer reads the same way. */\nexport function serviceListingFilter(query: ServiceListingQuery): Record<string, unknown> {\n if (\"id\" in query) return { id: query.id };\n if (\"categoryKeys\" in query) return { vscat_key: { $in: [...new Set(query.categoryKeys)] } };\n const org = { org_id: { $in: directoryIdForms(query.orgId) } };\n return query.programId !== undefined ? { ...org, program_id: query.programId } : org;\n}\n\n/** Parse one stored row (without `_id`), or null with the reason. */\nexport function parseStoredListing(\n raw: unknown,\n): { ok: true; doc: StoredServiceListing } | { ok: false; issues: string } {\n const rec = raw && typeof raw === \"object\" ? { ...(raw as Record<string, unknown>) } : raw;\n if (rec && typeof rec === \"object\") delete (rec as Record<string, unknown>)._id;\n const parsed = StoredServiceListingSchema.safeParse(rec);\n if (parsed.success) return { ok: true, doc: parsed.data };\n return {\n ok: false,\n issues: parsed.error.issues.map((i) => `${i.path.join(\".\")}: ${i.message}`).join(\"; \"),\n };\n}\n\nconst TIER_ORDER: Record<string, number> = { primary: 0, additional: 1 };\nconst LAST = \"\";\n\n/** Reading order: program, primary before additional, label, id. */\nexport function compareListings(\n a: Pick<StoredServiceListing, \"program_id\" | \"tier\" | \"vscat_label\" | \"id\">,\n b: Pick<StoredServiceListing, \"program_id\" | \"tier\" | \"vscat_label\" | \"id\">,\n): number {\n return (\n (a.program_id ?? LAST).localeCompare(b.program_id ?? LAST) ||\n (TIER_ORDER[a.tier ?? \"\"] ?? 2) - (TIER_ORDER[b.tier ?? \"\"] ?? 2) ||\n a.vscat_label.localeCompare(b.vscat_label) ||\n a.id.localeCompare(b.id)\n );\n}\n\n/**\n * Read listings as every reader sees them (the Network's public, masked view).\n * A listing whose review is `rejected` is left out ({@link isListedOnNetwork}),\n * so an `{id}` read of one reads `[]`. Read errors propagate: an org with no\n * rows reads `[]`; an unreadable store throws.\n */\nexport async function readServiceListings(\n db: ListingsDbLike,\n query: ServiceListingQuery,\n opts: ReadServiceListingsOptions,\n): Promise<ServiceListingView[]> {\n if (\"categoryKeys\" in query && query.categoryKeys.length === 0) return [];\n const raws = await db\n .collection(SERVICE_LISTINGS_COLLECTION)\n .find(serviceListingFilter(query))\n .toArray();\n const now = opts.now ?? new Date();\n const views: ServiceListingView[] = [];\n for (const raw of raws) {\n const parsed = parseStoredListing(raw);\n if (!parsed.ok) {\n opts.onInvalid?.(raw, parsed.issues);\n continue;\n }\n if (!isListedOnNetwork(parsed.doc)) continue;\n views.push(toListingView(parsed.doc, { now, categories: opts.categories }));\n }\n return views.sort(compareListings);\n}\n","/**\n * @htilabs/platform-common-models — folding a copy into the real organization\n *\n * The logic behind `fill-org-registry --apply-merges`. Runbook:\n * `scripts/FILL_ORG_REGISTRY_RUNBOOK.md`, \"Folding a copy into the real\n * organization\".\n *\n * ## Why\n *\n * One record per real-world organization (UDD Org Data Object, 2026-10-02).\n * Where the same organization was typed in twice, the steward (HTI Labs)\n * reconciles the two by hand: a person names the copy and the row that is\n * kept. Nothing here works out which rows are copies.\n *\n * ## What a merge is (ruled 2026-10-20, the prototype's ORG-MERGE)\n *\n * Pure re-pointing. Every stored reference to the copy's `_id` is changed to\n * the kept organization's `_id`. Nothing on the kept row is combined or\n * rewritten: not its name, type, VSP answer, list or programs, and no\n * Account's sharing rule. The copy is then deleted, and its id is recorded on\n * the kept row as `legacy_ids.merged_from`, so an old reference found later\n * can be traced.\n *\n * ## Where references live\n *\n * {@link ORG_REFERENCES} is the list, read from the models of this package,\n * Thread, PAVE 2.0, the Platform app and auth (2026-11-10). Thread and PAVE\n * keep their case records in databases of their own. The copy is deleted only\n * when nothing in the platform database points at it AND every Thread and\n * PAVE database was named on the command line and nothing there points at it\n * either. Otherwise the copy stays, marked inactive (`status` 2, which every\n * app already reads as \"not offered\", `isListedOrganization`), and the line\n * says why.\n *\n * ## Programs (0.84.0)\n *\n * A Program belongs to the Organization, and is stored on its row\n * (`organizations.programs[]`). \"Make the other objects really move in a\n * merge\" (Crysta, 2026-11-11): when a steward merges, the copy's program rows\n * move to the kept organization, exactly as stored and with their ids\n * unchanged. A program id is minted, never derived from a name, so it names\n * one program wherever its row sits; everything that points at a program\n * (`servicelistings.program_id`, a case's program in Thread or PAVE) names it\n * beside the organization, and that reference is re-pointed above. So nothing\n * that points at a program is touched, and nothing is left pointing at a\n * program that is gone. The rows are appended to the kept organization's\n * list in the same write that records the copy's id there. Two live programs\n * that end up with the same name are both kept, as two programs (a name is\n * not an identity; the plan says so in a flag). Where the agency whose list\n * the copy is in cannot yet read the kept row in Thread and PAVE (see \"Who is\n * merging\"), the flag also says it may not be able to pick the programs that\n * moved; nothing is refused for it. A copy that is then kept as\n * inactive keeps no programs: they are the kept organization's now. A merge\n * inside one agency's own list (`agency`) still refuses a copy with programs,\n * as before.\n *\n * ## What it never does\n *\n * It never writes a fact of the kept row (its programs are added to, never\n * rewritten), never moves an identifier (`key`: identifiers never change),\n * never moves a sharing grant, never merges an Agency's own organization\n * (that is not a copy), and never re-points a copy of an id kept inside a\n * sent share, a session draft or a sealed field (see the runbook).\n *\n * ## Who is merging (0.84.0)\n *\n * The caller says who merges ({@link MergeActor}); nothing here works it out.\n *\n * - `steward`: HTI Labs reconciling the registry (the Admin Hub's \"Merge into\n * another organization\", the registry tool). The registry is ONE\n * platform-wide list: \"Organizations should never sit inside one agency's\n * own list\" (Crysta, 2026-11-11), and an agency's list never blocks a\n * registry action. So the pair is judged against the registry alone: both\n * rows exist, the kept one is offered (active, not declined). Whose list a\n * row was typed into (`agencyScope`) and its `community` refuse nothing.\n * Where Thread's and PAVE's as-built per-agency read would hide the kept\n * row from the agency whose list the copy is in, the plan carries a flag\n * saying so, in words a steward can read; it goes when both apps read the\n * one list (Thread #1228 and PAVE's twin).\n * - `agency`: a merge made inside one agency's own list. The kept row must be\n * readable where the copy is used, by Thread's as-built rule. This is the\n * rule every caller had before 0.84.0, unchanged. No app calls it today.\n *\n * Every other refusal is about the data, not about lists, and holds for both.\n */\n\n/*\n * Moved here from scripts/ in 0.69.0, where the 100-column lint rule does not\n * run. The reference table below reads as one line per place an id is stored;\n * the long lines are kept so the move stays a move. The one change: nothing\n * here imports mongoose or the driver. The handles are typed structurally and\n * the caller passes its own ObjectId class and EJSON ({@link MergeDriver}), so\n * an id built here is the same class the caller's driver stores and reads.\n */\n/* eslint-disable max-len */\n\n\nimport { ORGANIZATION_STATUS, isListedOrganization } from \"../orgDirectory/orgRecord.js\";\nimport { isLiveOrganizationProgram, programNameKey } from \"../orgDirectory/vocabulary.js\";\nimport { AGENCIES_COLLECTION, ORGANIZATIONS_COLLECTION } from \"../orgDirectory/read.js\";\nimport { directoryIdString } from \"../orgDirectory/rules.js\";\nimport { POINTS_OF_CONTACT_COLLECTION } from \"../pointsOfContact/schemas.js\";\nimport { SERVICE_LISTINGS_COLLECTION } from \"../serviceListings/read.js\";\nimport { comparableId, comparableName, sheetText } from \"./support.js\";\nimport type {\n MergeBeforeImages,\n MergeDbLike,\n MergeDocument,\n MergeDriver,\n MergeImage,\n MergeProgramsImage,\n MergeRefImage,\n} from \"./types.js\";\n\ntype Db = MergeDbLike;\ntype Document = MergeDocument;\ntype Row = Record<string, unknown>;\n\nconst text = (v: unknown): string => (typeof v === \"string\" ? v.trim() : \"\");\nconst blank = (v: unknown): boolean => v == null || (typeof v === \"string\" && v.trim() === \"\");\nconst idText = (v: unknown): string => directoryIdString(v) ?? String(v);\nconst HEX_24 = /^[0-9a-fA-F]{24}$/;\nconst message = (err: unknown): string => (err instanceof Error ? err.message : String(err));\n\n/**\n * An id's comparable text when the value is an id (a string or an ObjectId), else null. Never a sub-record.\n * A 24-hex id is lower-cased (the form an ObjectId prints as); a text id is compared exactly as stored.\n */\nconst idOf = (driver: MergeDriver, v: unknown): string | null =>\n typeof v === \"string\" ? comparableId(v) : v instanceof driver.ObjectId ? v.toHexString() : null;\n\n/** Every stored form of an id: the ObjectId and the lower-case text when it is 24-hex, else the text. */\nfunction idForms(driver: MergeDriver, id: unknown): unknown[] {\n const s = idText(id);\n return HEX_24.test(s) ? [new driver.ObjectId(s.toLowerCase()), s.toLowerCase()] : [s];\n}\n/**\n * The kept id in the same stored form as the value it replaces. A text id is\n * written exactly as the kept row stores it: before 0.84.0 it was lower-cased,\n * so a reference moved to a row stored under \"Org-A\" named \"org-a\", which is\n * no row.\n */\nfunction inFormOf(driver: MergeDriver, from: unknown, keptId: unknown): unknown {\n const s = idText(keptId);\n return from instanceof driver.ObjectId && HEX_24.test(s) ? new driver.ObjectId(s.toLowerCase()) : comparableId(s);\n}\n\n/**\n * Thread's development sample rows (`apps/api/src/seed/index.ts`: the\n * \"Thread Prototype Agency\" and its organizations, ids `64e4ff1c2a7dcd9cb5f4a0xx`\n * and `…a1xx`). Some reached production. They are never a kept row or a copy.\n */\nexport const THREAD_SAMPLE_ID_PREFIX = \"64e4ff1c2a7dcd9cb5f4a\";\n\n// ─── Where an organization's `_id` is stored ────────────────────────────────\n\n/** Which database a reference lives in: the platform database, or an app's own. */\nexport type ReferenceApp = \"platform\" | \"thread\" | \"pave\";\nexport const APP_LABEL: Record<ReferenceApp, string> = { platform: \"the platform\", thread: \"Thread\", pave: \"PAVE\" };\n\nexport interface OrgReference {\n app: ReferenceApp;\n collection: string;\n /**\n * `value`: `path` holds the id. `list`: `path` is a list of ids. `rows`:\n * `path` is a list of sub-records and `field` in each holds the id.\n * `answers`: `path` is a list of form answers and `field` in each is a list\n * of values, any of which may be the id. `count`: counted, never moved: a\n * copy it names is kept, not deleted.\n */\n kind: MergeRefImage[\"kind\"] | \"count\";\n path: string;\n field?: string;\n /** Who writes it, for the runbook's table. */\n writtenBy: string;\n}\n\n/**\n * Every place an organization's `_id` is stored, from the code (2026-11-10).\n * `agencies.organizationId` is not here: an organization an Agency points at\n * is that Agency's own and is never merged. A reference by an Org's `key`\n * (the Platform app's sharing-rule attachments) is not here either: a merge\n * moves ids, and identifiers never move. Program ids (`programs[].programId`)\n * are not here: a copy with programs is refused.\n */\nexport const ORG_REFERENCES: readonly OrgReference[] = Object.freeze([\n { app: \"platform\", collection: \"personnelpeople\", kind: \"value\", path: \"organizationId\", writtenBy: \"auth at a first sign-in; Thread's staff records\" },\n { app: \"platform\", collection: ORGANIZATIONS_COLLECTION, kind: \"value\", path: \"parentOrgId\", writtenBy: \"an Org that is a unit of this one\" },\n { app: \"platform\", collection: SERVICE_LISTINGS_COLLECTION, kind: \"value\", path: \"org_id\", writtenBy: \"service listings\" },\n { app: \"platform\", collection: POINTS_OF_CONTACT_COLLECTION, kind: \"value\", path: \"org_id\", writtenBy: \"points of contact\" },\n { app: \"platform\", collection: POINTS_OF_CONTACT_COLLECTION, kind: \"value\", path: \"subject_id\", writtenBy: \"an Org's own point of contact\" },\n { app: \"platform\", collection: \"personnelmergefolds\", kind: \"value\", path: \"survivorBefore.organizationId\", writtenBy: \"Thread's staff-record merge log\" },\n { app: \"platform\", collection: \"personnelmergefolds\", kind: \"value\", path: \"survivorChange.liftedOrganizationId\", writtenBy: \"Thread's staff-record merge log\" },\n { app: \"platform\", collection: \"surveyedOrganizations\", kind: \"value\", path: \"directoryOrganizationId\", writtenBy: \"the Platform app's agency survey link\" },\n { app: \"platform\", collection: \"accountPolicies\", kind: \"value\", path: \"orgRef\", writtenBy: \"the Platform app's account-policy seed\" },\n { app: \"platform\", collection: AGENCIES_COLLECTION, kind: \"list\", path: \"reportingDestinations.designated.mandatory_reporting\", writtenBy: \"the Platform app's reporting destinations\" },\n { app: \"platform\", collection: AGENCIES_COLLECTION, kind: \"list\", path: \"reportingDestinations.designated.authority_reporting\", writtenBy: \"the Platform app's reporting destinations\" },\n\n { app: \"thread\", collection: \"caserecords\", kind: \"value\", path: \"referralOrganizationId\", writtenBy: \"a case's referring organization\" },\n { app: \"thread\", collection: \"caserecords\", kind: \"rows\", path: \"identifierEntries\", field: \"usedByOrgId\", writtenBy: \"a case number's organization\" },\n { app: \"thread\", collection: \"submissions\", kind: \"answers\", path: \"answers\", field: \"val\", writtenBy: \"a form answer naming an organization (the referring-organization question)\" },\n { app: \"thread\", collection: \"casesessions\", kind: \"list\", path: \"relevantOrganizationIds\", writtenBy: \"organizations added in a session\" },\n { app: \"thread\", collection: \"serviceinstances\", kind: \"value\", path: \"referralToOrganizationId\", writtenBy: \"a service's referral\" },\n { app: \"thread\", collection: \"serviceinstances\", kind: \"value\", path: \"serviceProviderOrganizationId\", writtenBy: \"a service's provider\" },\n { app: \"thread\", collection: \"personnelpeople\", kind: \"value\", path: \"organizationId\", writtenBy: \"staff records\" },\n { app: \"thread\", collection: \"personinteracteds\", kind: \"value\", path: \"organizationId\", writtenBy: \"people a case interacted with\" },\n\n { app: \"pave\", collection: \"protectedpeople\", kind: \"value\", path: \"organizationId\", writtenBy: \"a person's organization\" },\n { app: \"pave\", collection: \"relevantpersons\", kind: \"value\", path: \"organizationId\", writtenBy: \"a relevant person's organization\" },\n { app: \"pave\", collection: \"serviceinstances\", kind: \"value\", path: \"serviceProviderOrgId\", writtenBy: \"a service's provider\" },\n { app: \"pave\", collection: \"serviceinstances\", kind: \"value\", path: \"referralToOrganizationId\", writtenBy: \"a service's referral\" },\n { app: \"pave\", collection: \"programhousingenrollments\", kind: \"value\", path: \"providerOrgId\", writtenBy: \"a housing program's provider\" },\n { app: \"pave\", collection: \"householdpets\", kind: \"value\", path: \"providerOrgId\", writtenBy: \"a pet program's provider\" },\n { app: \"pave\", collection: \"disclosure_records\", kind: \"value\", path: \"recipientOrg\", writtenBy: \"a disclosure's recipient\" },\n { app: \"pave\", collection: \"reportingdestinationconfigs\", kind: \"list\", path: \"organizationIds\", writtenBy: \"reporting destinations\" },\n { app: \"pave\", collection: \"casesessions\", kind: \"list\", path: \"relevantOrganizationIds\", writtenBy: \"organizations added in a session\" },\n { app: \"pave\", collection: \"sharingsettings\", kind: \"count\", path: \"organizationId\", writtenBy: \"a sharing grant to a partner organization (never moved: sharing rules are not merged)\" },\n] as const);\n\n/** The apps that keep references in a database of their own. A copy is deleted only when each was checked. */\nexport const APP_DATABASE_KINDS = [\"thread\", \"pave\"] as const;\nexport type AppDatabaseKind = (typeof APP_DATABASE_KINDS)[number];\n\n/** One database a merge reads and re-points in. */\nexport interface MergeDatabase {\n app: ReferenceApp;\n name: string;\n db: Db;\n}\n\n/** A collection every database of that app has: how a mistyped database name is caught. */\nconst APP_MARKER: Record<AppDatabaseKind, string> = { thread: \"caserecords\", pave: \"protectedpeople\" };\n\n/**\n * Collections ONLY PAVE's database has. Thread's database and PAVE's both\n * hold `caserecords` and `protectedpeople` (each app has both models), so the\n * two markers above cannot tell one from the other: before 0.84.0 PAVE's\n * database named as Thread's (or the two names swapped) was accepted, each\n * was searched with the other app's field names, found nothing, and a copy\n * its case records still named could be deleted.\n *\n * A database is PAVE's when it has ANY of these, and Thread's only when it\n * has NONE. Any, not one in particular: PAVE has built every model's\n * collection at each start only since its index sweep (pave-2.0\n * `declaredIndexSweep`, 2026-11-09); on an older build a collection exists\n * only once something was saved in it. Thread names none of the three (its\n * disclosure model's collection is `disclosurerecords`, no underscore).\n */\nconst PAVE_ONLY_COLLECTIONS = [\"programhousingenrollments\", \"disclosure_records\", \"reportingdestinationconfigs\"] as const;\n\n/** Why `db` cannot be `app`'s database, or null when it can. A name that matches nothing would read as \"no references\". */\nexport async function appDatabaseProblem(app: AppDatabaseKind, name: string, db: Db): Promise<string | null> {\n const has = async (collection: string): Promise<boolean> =>\n (await db.listCollections({ name: collection }, { nameOnly: true }).toArray()).length > 0;\n if (!(await has(APP_MARKER[app]))) {\n return `'${name}' has no ${APP_MARKER[app]} collection, so it is not a ${APP_LABEL[app]} database (check the name)`;\n }\n let paves: string | null = null;\n for (const c of PAVE_ONLY_COLLECTIONS) {\n if (await has(c)) {\n paves = c;\n break;\n }\n }\n if (app === \"thread\" && paves) {\n return `'${name}' has a ${paves} collection, which only PAVE's database has, so it is not a Thread database (check the name)`;\n }\n if (app === \"pave\" && !paves) {\n return (\n `'${name}' has none of the collections only PAVE's database has (${PAVE_ONLY_COLLECTIONS.join(\", \")}), ` +\n \"so it is not a PAVE database (check the name)\"\n );\n }\n return null;\n}\n\nconst refPath = (r: Pick<OrgReference, \"kind\" | \"path\" | \"field\">): string =>\n r.kind === \"rows\" || r.kind === \"answers\" ? `${r.path}.${String(r.field)}` : r.path;\n\n/** The value at a dotted path of a document read from the driver. */\nfunction getPath(doc: Row, path: string): unknown {\n return path.split(\".\").reduce<unknown>((v, k) => (v && typeof v === \"object\" ? (v as Row)[k] : undefined), doc);\n}\n\n/**\n * A list of ids with the copy's replaced by the kept organization's (in each\n * value's stored form). A list is a set to every app that reads one: where\n * the kept id is already in it, the copy's id is dropped instead.\n */\nfunction rewriteIds(driver: MergeDriver, list: readonly unknown[], copy: string, kept: unknown): unknown[] {\n const keptHex = comparableId(idText(kept));\n let hasKept = list.some((v) => idOf(driver, v) === keptHex);\n const out: unknown[] = [];\n for (const v of list) {\n if (idOf(driver, v) !== copy) out.push(v);\n else if (!hasKept) {\n out.push(inFormOf(driver, v, kept));\n hasKept = true;\n }\n }\n return out;\n}\n\n/** Sub-records with the copy's id in `field` replaced; a sub-record that would then repeat another one exactly is dropped. */\nfunction rewriteRows(driver: MergeDriver, rows: readonly unknown[], field: string, copy: string, kept: unknown): unknown[] {\n const key = (r: unknown): string =>\n r && typeof r === \"object\" ? JSON.stringify({ ...(r as Row), [field]: idOf(driver, (r as Row)[field]) }) : JSON.stringify(r);\n const isCopyRow = (r: unknown): boolean => !!r && typeof r === \"object\" && idOf(driver, (r as Row)[field]) === copy;\n const seen = new Set(rows.filter((r) => !isCopyRow(r)).map(key));\n const out: unknown[] = [];\n for (const r of rows) {\n if (!isCopyRow(r)) {\n out.push(r);\n continue;\n }\n const moved = { ...(r as Row), [field]: inFormOf(driver, (r as Row)[field], kept) };\n if (seen.has(key(moved))) continue;\n seen.add(key(moved));\n out.push(moved);\n }\n return out;\n}\n\n/** Form answers with the copy's id replaced inside each answer's list of values. */\nfunction rewriteAnswers(driver: MergeDriver, answers: readonly unknown[], field: string, copy: string, kept: unknown): unknown[] {\n return answers.map((a) => {\n const vals = a && typeof a === \"object\" ? (a as Row)[field] : undefined;\n return Array.isArray(vals) && vals.some((v) => idOf(driver, v) === copy)\n ? { ...(a as Row), [field]: rewriteIds(driver, vals, copy, kept) }\n : a;\n });\n}\n\n/** Every stored reference to `orgId` in the given databases, as the before-images of a re-point to `keptId`. Reads only. */\nasync function findReferences(driver: MergeDriver, dbs: readonly MergeDatabase[], orgId: unknown, keptId: unknown): Promise<MergeRefImage[]> {\n const out: MergeRefImage[] = [];\n const copy = comparableId(idText(orgId));\n for (const d of dbs) {\n for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app)) {\n if (ref.kind === \"count\") continue;\n const base = { db: d.name, collection: ref.collection, kind: ref.kind, path: ref.path, ...(ref.field ? { field: ref.field } : {}) };\n if (ref.kind === \"value\") {\n for (const from of idForms(driver, orgId)) {\n const docs = await d.db.collection(ref.collection).find({ [ref.path]: from } as Document, { projection: { _id: 1 } }).toArray();\n for (const doc of docs) out.push({ ...base, docId: doc._id, from, to: inFormOf(driver, from, keptId) });\n }\n continue;\n }\n // A list or a list of sub-records is moved whole, one line per document, so a\n // document holding the id in both stored forms is one compare-and-swap. Read\n // without promoting numbers, so an untouched value written back keeps its type.\n const docs = await d.db\n .collection(ref.collection)\n .find({ [refPath(ref)]: { $in: idForms(driver, orgId) } } as Document, { projection: { _id: 1, [ref.path]: 1 }, promoteValues: false })\n .toArray();\n for (const doc of docs) {\n const before = getPath(doc as Row, ref.path);\n if (!Array.isArray(before)) continue;\n const after =\n ref.kind === \"list\"\n ? rewriteIds(driver, before, copy, keptId)\n : ref.kind === \"rows\"\n ? rewriteRows(driver, before, String(ref.field), copy, keptId)\n : rewriteAnswers(driver, before, String(ref.field), copy, keptId);\n out.push({ ...base, docId: doc._id, from: copy, to: comparableId(idText(keptId)), before, after });\n }\n }\n }\n return out;\n}\n\n/** How many documents still name `orgId` in the given databases (an Agency's pointer and the never-moved kinds included). */\nasync function countReferences(driver: MergeDriver, dbs: readonly MergeDatabase[], orgId: unknown, only?: \"count\"): Promise<number> {\n let n = 0;\n for (const d of dbs) {\n for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app && (!only || r.kind === only))) {\n n += await d.db.collection(ref.collection).countDocuments({ [refPath(ref)]: { $in: idForms(driver, orgId) } } as Document);\n }\n if (d.app === \"platform\" && !only) {\n n += await d.db.collection(AGENCIES_COLLECTION).countDocuments({ organizationId: { $in: idForms(driver, orgId) } } as Document);\n }\n }\n return n;\n}\n\n/** Move one reference forward (`back` false) or back, only where it still holds what was there. True when it moved. */\nasync function repoint(db: Db, ref: MergeRefImage, back: boolean): Promise<boolean> {\n const coll = db.collection(ref.collection);\n if (ref.kind === \"value\") {\n const [from, to] = back ? [ref.to, ref.from] : [ref.from, ref.to];\n return (await coll.updateOne({ _id: ref.docId, [ref.path]: from } as Document, { $set: { [ref.path]: to } })).matchedCount === 1;\n }\n const [from, to] = back ? [ref.after, ref.before] : [ref.before, ref.after];\n return (await coll.updateOne({ _id: ref.docId, [ref.path]: from } as Document, { $set: { [ref.path]: to } })).matchedCount === 1;\n}\n\n/** Whether a reference still holds what the merge wrote. */\nasync function holdsMerged(db: Db, ref: MergeRefImage): Promise<boolean> {\n const filter = ref.kind === \"value\" ? { _id: ref.docId, [ref.path]: ref.to } : { _id: ref.docId, [ref.path]: ref.after };\n return (await db.collection(ref.collection).countDocuments(filter as Document)) === 1;\n}\n\n// ─── One merge, as a person named it ────────────────────────────────────────\n\n/** What a reviewer writes in the merge sheet's `approved` column. */\nexport const MERGE = \"merge\";\n\n/** What a reviewer writes in the sheet's `different_name_ok` to merge two rows whose names differ. */\nexport const YES = \"yes\";\n\nexport interface MergeLine {\n /** Sheet line (header = 1), for messages. */\n line: number;\n duplicateId: string;\n duplicateName: string;\n keptId: string;\n keptName: string;\n /** The line says in so many words that the two names differ and are one organization. */\n differentNameOk: boolean;\n}\n\n// ─── Planning ───────────────────────────────────────────────────────────────\n\n/**\n * Who is merging. `steward`: HTI Labs, acting on the one platform-wide\n * registry; no agency's list refuses the pair. `agency`: a merge inside one\n * agency's own list; the kept row must be readable where the copy is used\n * (the only rule before 0.84.0). See \"Who is merging\" at the top of this file.\n */\nexport type MergeActor = \"steward\" | \"agency\";\n\n/** What the caller states about a plan. Required: the rules never guess who is merging. */\nexport interface MergePlanOptions {\n mergedBy: MergeActor;\n}\n\nexport interface PlannedMerge {\n line: MergeLine;\n /** `merge` is written; `already` is done (the copy is gone and recorded); `skip` blocks the whole apply. */\n status: \"merge\" | \"already\" | \"skip\";\n detail: string;\n /** Stored names (\"\" when the row was not found). */\n duplicateName: string;\n keptName: string;\n /** Whose list each row sits in (`agencyScope`), in words. */\n duplicateList: string;\n keptList: string;\n flags: string[];\n /** Present on `merge`: what {@link executeMerges} writes, and its undo. */\n write?: MergeImage;\n}\n\n/**\n * Read every approved line and decide. Reads only. `skip` (any one blocks the\n * whole apply): either row is missing; a stored name is not the sheet's; the\n * copy is a canonical singleton, an Agency's own organization (it names an\n * Agency, or an Agency points at it: that is not a copy), or has programs;\n * the kept row is inactive or declined, or is a unit of the copy; the two\n * names differ and the line does not say `different_name_ok` = yes; and, only\n * when an `agency` merges ({@link MergeActor}), the kept row could not be seen\n * where the copy is used. A `steward`'s merge is never refused for that: the\n * registry is one platform-wide list, and the plan carries a flag instead.\n *\n * Seen, as Thread decides it (`organizationReadableBy`, `resolveUserCommunity`):\n * an Agency sees the organizations in its own list, and an organization of\n * another list only when the Agency's `state` is exactly that organization's\n * `community` (both non-blank; compared as stored, no trimming or case change).\n * So the kept row must be in the copy's list, or the Agency whose list the\n * copy is in must have a `state` equal to the kept row's `community`.\n *\n * @param dbs - the platform database first, then each app database the caller could open.\n * @param driver - the caller's ObjectId class and EJSON (see {@link MergeDriver}).\n * @param opts - who is merging ({@link MergePlanOptions}); stated by the caller, never inferred.\n */\nexport async function planMerges(\n dbs: readonly MergeDatabase[],\n lines: readonly MergeLine[],\n driver: MergeDriver,\n opts: MergePlanOptions,\n): Promise<PlannedMerge[]> {\n if (opts?.mergedBy !== \"steward\" && opts?.mergedBy !== \"agency\") {\n throw new Error(\"planMerges: say who is merging (mergedBy: 'steward' or 'agency')\");\n }\n const byAgency = opts.mergedBy === \"agency\";\n const platform = dbs[0] as MergeDatabase;\n const orgs = platform.db.collection(ORGANIZATIONS_COLLECTION);\n const agencies = platform.db.collection(AGENCIES_COLLECTION);\n const unchecked = APP_DATABASE_KINDS.filter((k) => !dbs.some((d) => d.app === k));\n const listAgency = async (org: Row): Promise<Row | null> =>\n blank(org.agencyScope)\n ? null\n : ((await agencies.findOne({ _id: { $in: idForms(driver, org.agencyScope) } } as Document, { projection: { name: 1, state: 1 } })) as Row | null);\n const listOf = async (org: Row): Promise<string> => {\n if (blank(org.agencyScope)) return \"in no agency's list\";\n const a = await listAgency(org);\n return `in the list of ${a ? text(a.name) || idText(org.agencyScope) : `agency ${idText(org.agencyScope)}, which is not in this database`}`;\n };\n /** Whether `copyId` is the kept row's parent, or its parent's parent, and so on (a cycle or a deep chain stops the walk). */\n const isUnitOf = async (kept: Row, copyId: string): Promise<boolean> => {\n const seen = new Set<string>();\n let parent = kept.parentOrgId;\n for (let depth = 0; depth < 25 && !blank(parent); depth += 1) {\n const id = idOf(driver, parent);\n if (id === null || seen.has(id)) return false;\n if (id === copyId) return true;\n seen.add(id);\n const next = (await orgs.findOne({ _id: { $in: idForms(driver, parent) } } as Document, { projection: { parentOrgId: 1 } })) as Row | null;\n parent = next?.parentOrgId;\n }\n return false;\n };\n const out: PlannedMerge[] = [];\n for (const line of lines) {\n const one = async (id: string): Promise<Row | null> => {\n const found = await orgs.find({ _id: { $in: idForms(driver, id) } } as Document).limit(2).toArray();\n return found.length === 1 ? (found[0] as Row) : null;\n };\n const dup = await one(line.duplicateId);\n const kept = await one(line.keptId);\n const base = {\n line,\n duplicateName: dup ? text(dup.name) : \"\",\n keptName: kept ? text(kept.name) : \"\",\n duplicateList: dup ? await listOf(dup) : \"\",\n keptList: kept ? await listOf(kept) : \"\",\n };\n const flags: string[] = [];\n const skip = (detail: string): void => {\n out.push({ ...base, status: \"skip\", detail, flags });\n };\n // The sheet reader refuses this too. It is refused here as well because the\n // plan is a public call (0.69.0): a copy merged into itself would have its\n // references \"moved\" to itself and then be deleted.\n if (comparableId(line.duplicateId) === comparableId(line.keptId)) {\n skip(\"the copy and the kept organization are the same row\");\n continue;\n }\n const mergedFrom = (kept?.legacy_ids as { merged_from?: unknown } | undefined)?.merged_from;\n const listed = Array.isArray(mergedFrom) && mergedFrom.includes(line.duplicateId);\n if (!dup && kept && listed) {\n out.push({ ...base, status: \"already\", detail: \"already merged: the copy is gone and the kept organization records its id\", flags });\n continue;\n }\n if (!dup || !kept) {\n skip(`no organization has the id ${!dup ? line.duplicateId : line.keptId}`);\n continue;\n }\n const misnamed = (\n [\n [\"copy\", line.duplicateName, base.duplicateName],\n [\"kept organization\", line.keptName, base.keptName],\n ] as const\n ).find(([, onSheet, stored]) => onSheet.trim() !== stored && onSheet.trim() !== sheetText(stored).trim());\n if (misnamed) {\n skip(`the sheet names the ${misnamed[0]} ${JSON.stringify(misnamed[1].trim())}, the database names it ${JSON.stringify(misnamed[2])}`);\n continue;\n }\n if (!blank(dup.canonicalKey)) {\n skip(\"the copy is a canonical singleton (Unknown / Anonymous); never merged\");\n continue;\n }\n const pointing = await agencies.countDocuments({ organizationId: { $in: idForms(driver, dup._id) } } as Document);\n if (!blank(dup.agencyId) || pointing) {\n skip(\"the copy is an Agency's own organization (it names an Agency, or an Agency points at it): that is not a copy\");\n continue;\n }\n // A copy's programs move with it when a steward merges (see \"Programs\" at the top of this file).\n let programs: MergeProgramsImage | undefined;\n if (Array.isArray(dup.programs) && dup.programs.length) {\n if (byAgency) {\n skip(\"the copy has programs; merging programs is not supported\");\n continue;\n }\n // Read without promoting numbers, so a row written back (the undo) or compared keeps each value's stored type.\n const stored = async (id: unknown): Promise<unknown> =>\n ((await orgs.findOne({ _id: id } as Document, { projection: { programs: 1 }, promoteValues: false })) as Row | null)?.programs;\n const [keptRows, dupRows] = [await stored(kept._id), await stored(dup._id)];\n if (!Array.isArray(dupRows) || dupRows.length !== dup.programs.length) {\n skip(\"the copy's programs changed while the plan was read; plan again\");\n continue;\n }\n const keptHad = Array.isArray(keptRows);\n const keptBefore = keptHad ? (keptRows as unknown[]) : [];\n const idOfProgram = (r: unknown): string => (r && typeof r === \"object\" ? text((r as Row).programId) : \"\");\n const keptIds = new Set(keptBefore.map(idOfProgram).filter(Boolean));\n const twin = dupRows.map(idOfProgram).find((id) => id && keptIds.has(id));\n if (twin) {\n skip(`a program of the copy has the same id as a program of the kept organization (${twin}); two programs cannot share an id`);\n continue;\n }\n programs = { keptHad, keptBefore, moved: dupRows as unknown[] };\n const liveName = (r: unknown): string => {\n const row = r && typeof r === \"object\" ? (r as Row) : {};\n return typeof row.name === \"string\" && isLiveOrganizationProgram(row as { status?: string; reviewStatus?: string }) ? programNameKey(row.name) : \"\";\n };\n const keptNames = new Set(keptBefore.map(liveName).filter(Boolean));\n const same = programs.moved.filter((r) => liveName(r) && keptNames.has(liveName(r))).map((r) => text((r as Row).name));\n if (same.length) {\n flags.push(\n `${same.length} program(s) of the copy have the name of a live program of the kept organization (${same.join(\", \")}); ` +\n \"both are kept, as two programs\",\n );\n }\n }\n if (!isListedOrganization(kept as { status?: number; reviewStatus?: string })) {\n skip(\"the kept organization is inactive or declined: nothing is merged into a row that is not offered\");\n continue;\n }\n if (await isUnitOf(kept, comparableId(idText(dup._id)))) {\n skip(\"the kept organization is a unit of the copy (the copy is on its chain of parent organizations)\");\n continue;\n }\n if (comparableName(dup.name) !== comparableName(kept.name)) {\n if (!line.differentNameOk) {\n skip(`the two names differ: write ${YES} in different_name_ok on this line if they are one organization`);\n continue;\n }\n flags.push(\"the names differ; the sheet says they are one organization\");\n }\n const sameList = !blank(kept.agencyScope) && idText(kept.agencyScope) === idText(dup.agencyScope);\n const viewer = await listAgency(dup);\n const state = typeof viewer?.state === \"string\" ? viewer.state : \"\";\n const community = typeof kept.community === \"string\" ? kept.community : \"\";\n if (!sameList && !(state !== \"\" && state === community)) {\n if (byAgency) {\n skip(\n `the kept organization could not be seen by the agency whose list the copy is in: the copy is ${base.duplicateList} ` +\n `(that agency's state ${JSON.stringify(state)}), the kept row is ${base.keptList} (community ${JSON.stringify(community)}). ` +\n \"An agency sees another list's organization only when its state is exactly that organization's community. \" +\n \"The kept row's list or community is corrected first, by a deliberate edit\",\n );\n continue;\n }\n // A steward's merge is judged against the one registry, so this refuses nothing. Where the copy sits in an\n // agency's list, that agency's users read the kept row through Thread's and PAVE's as-built per-agency\n // rule until both apps read the one list: said, so the steward knows what they will see meanwhile.\n if (viewer) {\n // With programs it is more than a name: that agency's program pickers read the kept row the same way.\n flags.push(\n `until Thread and PAVE show every agency the one organization list, ${text(viewer.name) || \"the agency that added the copy\"} ` +\n \"may not see the kept organization's name on its records that move\" +\n (programs ? `, or pick the ${programs.moved.length} program(s) that move to it` : \"\"),\n );\n }\n }\n const keyed = !blank(dup.key);\n if (keyed) {\n flags.push(\n `the copy carries the identifier ${String(dup.key)}: identifiers never move` +\n `${blank(kept.key) ? \" (the kept organization has none; the key sheet gives it one)\" : \"\"}, so the copy is kept as inactive`,\n );\n }\n const refs = await findReferences(driver, dbs, dup._id, kept._id);\n const grants = await countReferences(driver, dbs, dup._id, \"count\");\n const outcome = keyed || grants || unchecked.length ? \"retire\" : \"delete\";\n const moves = new Map<string, number>();\n for (const r of refs) {\n const k = `${r.db} ${r.collection}.${refPath(r)}`;\n moves.set(k, (moves.get(k) ?? 0) + 1);\n }\n // The copy's programs move even when an app's database could not be checked, and the copy then stays (inactive)\n // for that database's sake. A record there that names the copy with one of its programs keeps naming the copy:\n // said, with the remedy, so nobody takes the merge for finished.\n if (programs && unchecked.length) {\n const where = unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(\" and \");\n flags.push(\n `${where} could not be checked: a record there that names the copy with one of its programs still names the copy, ` +\n \"while the programs are the kept organization's now; run the merge again with every database to move those records\",\n );\n }\n const why = [\n ...(unchecked.length ? [`references in ${unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(\" and \")} could not be checked`] : []),\n ...(grants ? [`${grants} sharing grant(s) name the copy, and sharing rules are never moved`] : []),\n ];\n const then =\n outcome === \"delete\"\n ? \"then the copy is deleted\"\n : `then the copy is kept as inactive${why.length ? `: ${why.join(\"; \")}` : \"\"}`;\n out.push({\n ...base,\n status: \"merge\",\n detail:\n `${moves.size ? `moves ${[...moves].map(([k, n]) => `${n} in ${k}`).join(\", \")}` : \"nothing points at the copy\"}; ` +\n `${programs ? `its ${programs.moved.length} program(s) move to the kept organization; ` : \"\"}${then}`,\n flags,\n write: {\n duplicateId: dup._id,\n duplicateName: base.duplicateName,\n keptId: kept._id,\n keptName: base.keptName,\n duplicate: dup as Document,\n refs,\n outcome,\n addsLegacyEntry: !listed,\n ...(programs ? { programs } : {}),\n },\n });\n }\n return out;\n}\n\n/** One planned line as printed: both rows by stored name and list, what moves, what happens to the copy, any flag. */\nexport function formatPlannedMerge(p: PlannedMerge): string {\n return (\n ` ${p.status.padEnd(6)} ${p.line.duplicateId} ${p.duplicateName || \"(no organization)\"}${p.duplicateList ? ` (${p.duplicateList})` : \"\"}` +\n ` -> ${p.line.keptId} ${p.keptName || \"(no organization)\"}${p.keptList ? ` (${p.keptList})` : \"\"}\\n` +\n ` ${p.detail}${p.flags.map((f) => ` [${f}]`).join(\"\")}`\n );\n}\n\n// ─── Writing ────────────────────────────────────────────────────────────────\n\n/** Said when a copy that changed under the merge could not be deleted or retired after its programs were added to the kept row. */\nconst COPY_KEEPS_PROGRAMS = \", and its programs were added to the kept organization while the copy still lists them: undo this merge and run it again\";\n\nexport interface ExecutedMerge {\n merge: MergeImage;\n /** `deleted` / `retired`: the line is done. `changed`: a row moved since the plan. `failed`: the database refused. */\n status: \"deleted\" | \"retired\" | \"changed\" | \"failed\";\n moved: number;\n detail?: string;\n}\n\n/**\n * Carry out each merge, one at a time: record the copy's id on the kept row,\n * move each reference (only where it still holds what the plan read), then\n * count what still names the copy. Nothing left and every app database\n * checked: the copy is deleted. Otherwise it is marked inactive. Either\n * happens only while the copy is still exactly as planned. The kept row gets\n * `legacy_ids.merged_from` and, when the copy has programs, those rows added\n * to the end of its own (in the one write, and only while its programs are\n * still as planned): nothing else, not even a new `updatedTime`.\n */\nexport async function executeMerges(\n dbs: readonly MergeDatabase[],\n merges: readonly MergeImage[],\n now: Date,\n driver: MergeDriver,\n): Promise<ExecutedMerge[]> {\n const orgs = (dbs[0] as MergeDatabase).db.collection(ORGANIZATIONS_COLLECTION);\n const dbNamed = new Map(dbs.map((d) => [d.name, d.db]));\n const out: ExecutedMerge[] = [];\n for (const merge of merges) {\n let moved = 0;\n try {\n const programs = merge.programs;\n const kept = await orgs.updateOne(\n {\n _id: merge.keptId,\n status: { $in: [null, ORGANIZATION_STATUS.ACTIVE] },\n reviewStatus: { $ne: \"rejected\" },\n // The copy's programs join the kept row's only while that list is still exactly as the plan read it\n // (`null` matches a row that stores no list).\n ...(programs ? { programs: programs.keptHad ? programs.keptBefore : null } : {}),\n } as Document,\n {\n $addToSet: { \"legacy_ids.merged_from\": idText(merge.duplicateId) },\n // Added to the end: the kept row's own program rows are not rewritten, not even re-typed.\n ...(programs ? (programs.keptHad ? { $push: { programs: { $each: programs.moved } } } : { $set: { programs: programs.moved } }) : {}),\n },\n );\n if (kept.matchedCount !== 1) {\n out.push({\n merge,\n status: \"changed\",\n moved,\n detail: `the kept organization is gone or no longer offered${programs ? \", or its programs changed,\" : \"\"} since the plan; nothing was written`,\n });\n continue;\n }\n let stale = 0;\n for (const ref of merge.refs) {\n if (await repoint(dbNamed.get(ref.db) as Db, ref, false)) moved += 1;\n else stale += 1;\n }\n const left = await countReferences(driver, dbs, merge.duplicateId);\n const asPlanned = { _id: merge.duplicateId, updatedTime: merge.duplicate.updatedTime ?? null, status: merge.duplicate.status ?? null } as Document;\n if (merge.outcome === \"delete\" && left === 0) {\n const res = await orgs.deleteOne(asPlanned);\n out.push(\n res.deletedCount === 1\n ? { merge, status: \"deleted\", moved }\n : { merge, status: \"changed\", moved, detail: `the copy changed since the plan and was left as it is; its references were moved${programs ? COPY_KEEPS_PROGRAMS : \"\"}` },\n );\n continue;\n }\n // A copy kept as inactive keeps no programs: they are the kept organization's now, under the same ids.\n const res = await orgs.updateOne(asPlanned, { $set: { status: ORGANIZATION_STATUS.INACTIVE, updatedTime: now, ...(programs ? { programs: [] } : {}) } });\n const why =\n merge.outcome === \"delete\"\n ? `${left} reference(s) still point at the copy${stale ? ` (${stale} changed since the plan)` : \"\"}, so it was not deleted`\n : left\n ? `${left} reference(s) still point at the copy`\n : undefined;\n out.push(\n res.matchedCount === 1\n ? { merge, status: \"retired\", moved, ...(why ? { detail: why } : {}) }\n : { merge, status: \"changed\", moved, detail: `the copy changed since the plan and was left as it is; its references were moved${programs ? COPY_KEEPS_PROGRAMS : \"\"}` },\n );\n } catch (err) {\n out.push({ merge, status: \"failed\", moved, detail: message(err) });\n }\n }\n return out;\n}\n\n// ─── Undo ───────────────────────────────────────────────────────────────────\n\nexport interface MergeRollbackRow {\n image: MergeImage;\n /** `restore`: everything can be put back. `partial`: some of it. `skip`: nothing to do, or nothing safe to do. */\n status: \"restore\" | \"partial\" | \"skip\";\n detail: string;\n}\n\n/** A document compared whole, whatever order its top-level keys come back in. */\nfunction sameDocument(driver: MergeDriver, x: Document, y: Document): boolean {\n const sorted = (d: Document): Document => Object.fromEntries(Object.keys(d).sort().map((k) => [k, d[k] as unknown]));\n const strict = (d: Document): string => driver.EJSON.stringify({ v: d }, { relaxed: false });\n return strict(sorted(x)) === strict(sorted(y));\n}\n\n/**\n * Undo each merge of a before-images file, newest first; with `dryRun`, only\n * say what would happen. The copy comes back first (re-inserted exactly from\n * its before-image when it was deleted; its `status` and `updatedTime`\n * restored when it was marked inactive), then each reference that still holds\n * what the merge wrote goes back (a list or a list of sub-records is put back\n * whole, so a copy's id the merge dropped returns too), then the copy's id is\n * taken off the kept row's `legacy_ids`, only when this run put it there. A\n * reference somebody has changed since is left alone and counted.\n *\n * @param dbFor - a handle on a database of the same server, by name.\n */\nexport async function rollbackMerges(\n dbFor: (name: string) => Db,\n images: MergeBeforeImages,\n opts: { dryRun: boolean },\n driver: MergeDriver,\n): Promise<MergeRollbackRow[]> {\n const orgs = dbFor(images.db).collection(ORGANIZATIONS_COLLECTION);\n const out: MergeRollbackRow[] = [];\n for (const image of [...(images.merges ?? [])].reverse()) {\n const said: string[] = [];\n let partial = false;\n const before = image.duplicate;\n const now = (await orgs.findOne({ _id: image.duplicateId } as Document)) as Document | null;\n const programs = image.programs;\n const retiredHere =\n !!now &&\n sameDocument(driver, now, {\n ...before,\n status: ORGANIZATION_STATUS.INACTIVE,\n updatedTime: images.appliedTime,\n // A copy the merge kept as inactive was left with no programs (they moved).\n ...(programs ? { programs: [] } : {}),\n });\n // True once the copy is back as it was before the merge (its programs included).\n let copyBack = true;\n if (!now) {\n said.push(\"put the deleted copy back exactly as it was\");\n if (!opts.dryRun) await orgs.insertOne(before);\n } else if (retiredHere) {\n said.push(before.status === ORGANIZATION_STATUS.INACTIVE ? \"put the copy back as it was before this run\" : \"make the copy active again, as it was\");\n if (!opts.dryRun) await orgs.replaceOne({ _id: image.duplicateId, updatedTime: images.appliedTime } as Document, before);\n } else if (sameDocument(driver, now, before)) {\n said.push(\"the copy is as it was\");\n } else {\n partial = true;\n copyBack = false;\n said.push(\"the copy has changed since the merge: left as it is\");\n }\n let back = 0;\n let moved = 0;\n for (const ref of image.refs) {\n const db = dbFor(ref.db);\n if (!(await holdsMerged(db, ref))) moved += 1;\n else if (opts.dryRun || (await repoint(db, ref, true))) back += 1;\n else moved += 1;\n }\n if (image.refs.length) {\n said.push(`${back} of ${image.refs.length} reference(s) back to the copy${moved ? ` (${moved} changed since the merge: left alone)` : \"\"}`);\n }\n if (moved) partial = true;\n // The copy's programs come off the kept row, only while its list is still exactly as the merge left it.\n let programsBack = false;\n if (programs) {\n const merged = [...programs.keptBefore, ...programs.moved];\n const holds = (await orgs.countDocuments({ _id: image.keptId, programs: merged } as Document)) === 1;\n const asBefore = (await orgs.countDocuments({ _id: image.keptId, programs: programs.keptHad ? programs.keptBefore : null } as Document)) === 1;\n if (holds) {\n programsBack = true;\n said.push(`take the copy's ${programs.moved.length} program(s) off the kept organization`);\n if (!opts.dryRun) {\n await orgs.updateOne(\n { _id: image.keptId, programs: merged } as Document,\n programs.keptHad ? { $set: { programs: programs.keptBefore } } : { $unset: { programs: \"\" } },\n );\n }\n } else if (!asBefore) {\n partial = true;\n said.push(\n \"the kept organization's programs have changed since the merge: left as they are\" +\n (copyBack ? \" (the copy has its programs back too, so the same program ids are on both organizations until one list is corrected)\" : \"\"),\n );\n }\n }\n const entry = idText(image.duplicateId);\n const listed = image.addsLegacyEntry\n ? await orgs.countDocuments({ _id: image.keptId, \"legacy_ids.merged_from\": entry } as Document)\n : 0;\n if (listed) {\n said.push(\"take the copy's id off the kept organization's legacy_ids\");\n if (!opts.dryRun) {\n await orgs.updateOne({ _id: image.keptId } as Document, { $pull: { \"legacy_ids.merged_from\": entry } } as Document);\n // Leave no empty shell behind: the row had no such field before its first merge.\n await orgs.updateOne({ _id: image.keptId, \"legacy_ids.merged_from\": { $size: 0 } } as Document, { $unset: { \"legacy_ids.merged_from\": \"\" } });\n await orgs.updateOne({ _id: image.keptId, legacy_ids: {} } as Document, { $unset: { legacy_ids: \"\" } });\n }\n } else if (!image.addsLegacyEntry) {\n said.push(\"the copy's id stays on the kept organization's legacy_ids (an earlier run put it there)\");\n }\n const anything = !now || retiredHere || back > 0 || listed > 0 || programsBack;\n out.push({\n image,\n status: !anything ? \"skip\" : partial ? \"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K,UAAU,EAAE,KAAK,MAAM,QAAQ,YAAY,CAAC,EAAE,GAAe,EAAE,QAAQ,EAAE,YAAY,GAAG,EAAE,CAAC;AAAA,MACxG;AAAA,IACF,WAAW,CAAC,MAAM,iBAAiB;AACjC,WAAK,KAAK,yFAAyF;AAAA,IACrG;AACA,UAAM,WAAW,CAAC,OAAO,eAAe,OAAO,KAAK,SAAS,KAAK;AAClE,QAAI,KAAK;AAAA,MACP;AAAA,MACA,QAAQ,CAAC,WAAW,SAAS,UAAU,YAAY;AAAA,MACnD,QAAQ,WAAW,KAAK,KAAK,IAAI,IAAI,yBAAyB,KAAK,KAAK,IAAI,CAAC;AAAA,IAC/E,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":["import_zod","import_zod","text","text","text","import_zod","text","optionalText","text","HEX_24","docs","from","to","line","res"]}
|