@htilabs/platform-common-models 0.83.0 → 0.84.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 CHANGED
@@ -16,6 +16,58 @@ Package exports are organized into a public root API and a small number of
16
16
  dedicated subpaths (`/validation`, `/cvcs`) — consult `package.json` for the
17
17
  authoritative `exports` map.
18
18
 
19
+ ## 0.84.0 — the organization merge is judged against the one registry and moves the duplicate's programs; the caller says who is merging (`./org-merge`; one new required argument)
20
+
21
+ **What a person gets.** An HTI Labs steward can now merge the pairs that matter: an organization added in the Admin Hub (as the copy or as the one kept), and a copy in one agency's list into another agency's or a member's own organization. Until now the shared rules refused all of these, because they asked whether the agency whose list the copy is in could see the kept row. "Organizations should never sit inside one agency's own list" (Crysta, 2026-11-11): the registry is one platform-wide list, and an agency's list never blocks a registry action.
22
+
23
+ **The one breaking change.** `planMerges` takes a fourth, required argument:
24
+
25
+ ```ts
26
+ import { planMerges } from "@htilabs/platform-common-models/org-merge";
27
+
28
+ const plan = await planMerges(dbs, lines, driver, { mergedBy: "steward" }); // HTI Labs, on the registry
29
+ const mine = await planMerges(dbs, lines, driver, { mergedBy: "agency" }); // inside one agency's own list
30
+ ```
31
+
32
+ - `steward`: the pair is judged against the registry alone. Whose list a row was typed into (`agencyScope`) and its `community` refuse nothing. Where Thread's and PAVE's as-built per-agency read would hide the kept row from the agency whose list the copy is in, the plan carries a flag a steward can read ("until Thread and PAVE show every agency the one organization list, The Spring may not see the kept organization's name on its records that move"). The flag goes when both apps read the one list (Thread #1228 and PAVE's twin).
33
+ - `agency`: the rule every caller had before, unchanged: the kept row must be in the copy's list, or the copy's agency's `state` must equal the kept row's `community`. No app calls it today; it is kept so a merge inside one agency's list never gets the registry-wide rule by default.
34
+ - Left out, or anything else: `planMerges` throws. The rules never guess who is merging.
35
+
36
+ Every other refusal is about the data and holds for both: a missing row, a name that is not the stored one, a canonical singleton, a copy that is an Agency's own organization (it holds or could hold an account: not a copy), a kept row that is inactive or declined or a unit of the copy, two different names not confirmed. A copy with programs is refused only for `agency`; a steward's merge moves them (below). `executeMerges` and `rollbackMerges` keep their signatures.
37
+
38
+ The registry tool (`fill-org-registry --apply-merges`) is HTI Labs' and plans as `steward`. Runbook: `scripts/FILL_ORG_REGISTRY_RUNBOOK.md`.
39
+
40
+ **Two gaps closed in the same rules.**
41
+
42
+ - *A text id is no longer lower-cased.* An organization stored under a text id (a seed slug) had its id lower-cased on the merge sheet and when a reference was re-pointed, so a reference moved to a row stored under `Org-A` named `org-a`, which is no row. Now only a 24-hex database id is compared in lower case (`comparableId`, exported); a text id is read and written exactly as stored. Every production organization is stored under a database id, so nothing stored changes.
43
+ - *Thread's database is told from PAVE's.* Both databases hold `caserecords` and `protectedpeople`, the two collections `appDatabaseProblem` checked, so PAVE's database named as Thread's (or the two names swapped) was accepted; each was then searched with the other app's field names, found nothing, and a copy its case records still named could be deleted. Now a database is PAVE's when it has any of the collections only PAVE has (`programhousingenrollments`, `disclosure_records`, `reportingdestinationconfigs`) and Thread's only when it has none of them. Any one, because PAVE has built every model's collection at each start only since its index sweep (2026-11-09); on an older build a collection exists only once something was saved in it. Thread names none of the three (its disclosure collection is `disclosurerecords`).
44
+
45
+ **For a consumer that bumps to this version** (the Platform's Admin Hub, `lib/org-directory/merge.ts`): pass `{ mergedBy: "steward" }` to `planMerges`; give the PAVE database of a test one of the PAVE-only collections (`programhousingenrollments`, say), or it is reported as unchecked and the copy is kept inactive instead of deleted.
46
+
47
+ **Mechanics.** `src/orgMerge/orgMerge.ts` (`MergeActor`, `MergePlanOptions`, `appDatabaseProblem`), `src/orgMerge/support.ts` (`comparableId`), `scripts/lib/orgMergeSheet.ts`, `scripts/lib/orgMerge.ts`. Tests: `src/orgMerge/__tests__/orgMergeSubpath.test.ts` (hermetic) and `scripts/fill-org-registry.test.ts` against a real MongoDB (the steward rule on five pairs the old rule refused, each still refused for `agency`; a merge between two text ids and its undo; the two databases told apart with both marker collections in each).
48
+
49
+ ### The duplicate's programs move with it
50
+
51
+ **What a person gets.** A duplicate organization that has programs can be merged. Until now the shared rules refused it ("the copy has programs; merging programs is not supported"), so a duplicate an advocate had named a program on could not be cleaned up. "Make the other objects really move in a merge" (Crysta, 2026-11-11); a Program belongs to the Organization (UDD).
52
+
53
+ **What the merge does with programs** (only when `mergedBy` is `steward`):
54
+
55
+ - The duplicate's `programs[]` rows are added to the end of the kept organization's list, exactly as stored and **under the same ids**, in the one write that records the duplicate's id on the kept row, and only while the kept row's list is still exactly as the plan read it (otherwise `changed`, nothing written). The kept row's own program rows are not rewritten, not even re-typed (`$push`).
56
+ - Nothing that points at a program is touched. A program id is minted, never derived from a name; a service listing or a case names a program by that id beside the organization, and the organization reference is what the merge already re-points.
57
+ - Where the agency whose list the duplicate is in cannot yet read the kept row in Thread and PAVE (the flag above), the flag also says it may not be able to pick the programs that moved: "…may not see the kept organization's name on its records that move, or pick the 2 program(s) that move to it". Said, never refused.
58
+ - A program of the duplicate with the name of a live program of the kept organization: both are kept, as two programs, and the plan says so in a flag. A name is not an identity; folding two programs would mean re-pointing program ids in three databases and is not done here.
59
+ - A duplicate that is kept as inactive keeps no programs (`programs: []`), so one program is never on two rows and a second run has nothing left to move.
60
+ - The undo takes the rows back off the kept organization, only while its list is still as the merge left it, and puts the duplicate back with its programs. If the kept list was edited meanwhile it is left alone: `partial`, and the line says the same program ids are then on both organizations.
61
+ - Refused, before anything is written: a program of the duplicate whose id is also a program id of the kept organization.
62
+ - When the duplicate has programs and is kept as inactive because Thread's or PAVE's database could not be checked, the plan carries a flag: a record there that names the duplicate with one of its programs still names the duplicate, while the programs are the kept organization's now; run the merge again with every database.
63
+ - **The registry tool (not the package) refuses a duplicate that has locations on file** (`scripts/lib/orgMerge.ts`, `COPY_HAS_LOCATIONS`). The package does not know the Platform's `locations` store, and a moved program can work from a location. The Admin Hub's merge moves the locations itself in the same act (platform #141), so its path is not affected.
64
+
65
+ `MergeImage` gains optional `programs: { keptHad, keptBefore, moved }` (`MergeProgramsImage`): what the write and the undo need. A caller that stores its own record of a merge (the Admin Hub) should keep the moved program ids from it. `mergedBy: "agency"` still refuses a duplicate with programs, as before.
66
+
67
+ **For the Admin Hub when it bumps** (`lib/org-directory/merge.ts`): show `write.programs.moved.length` in the plan; after its own undo, also confirm that none of the moved program ids is left on the kept row; its program editors do not yet stand down while a merge is in flight (the site editors do), which is what makes "the kept row's list changed" reachable.
68
+
69
+ **Mechanics.** `src/orgMerge/orgMerge.ts`, `src/orgMerge/types.ts`. Tests in `scripts/fill-org-registry.test.ts` against a real MongoDB: programs moved with ids unchanged, a listing under one of them still resolving, the kept row's own number still a double, and the undo back to byte-identical; a kept row with no list, a retired duplicate, a second run and both undos; the kept list changed between plan and write; a shared id refused; the undo leaving an edited list alone.
70
+
19
71
  ## 0.83.0 — coreFunctions 1.8.0: `agency_reports_view`, who may open an agency's Echo pages (one new permission; additive — no existing code, key, title or bound changes)
20
72
 
21
73
  **What changed.** Platform, PAVE and Thread can now gate an agency's Echo
@@ -1,4 +1,4 @@
1
- import { F as Form, l as buildFormSchema, h as Section, q as buildSectionSchema, Q as Question, o as buildQuestionSchema, f as ScoringRule, p as buildScoringRuleSchema, P as PlatformFunction, m as buildPlatformFunctionSchema, d as PlatformRole, n as buildPlatformRoleSchema, b as CvcRegistry, k as buildCvcRegistrySchema, a as CvcEntry, j as buildCvcEntrySchema } from './cvcEntry-D787utvP.cjs';
1
+ import { F as Form, l as buildFormSchema, h as Section, q as buildSectionSchema, Q as Question, o as buildQuestionSchema, f as ScoringRule, p as buildScoringRuleSchema, P as PlatformFunction, m as buildPlatformFunctionSchema, d as PlatformRole, n as buildPlatformRoleSchema, b as CvcRegistry, k as buildCvcRegistrySchema, a as CvcEntry, j as buildCvcEntrySchema } from './cvcEntry-BLeRivoF.cjs';
2
2
  import * as mongoose from 'mongoose';
3
3
  import { HydratedDocument, Connection, Model } from 'mongoose';
4
4
 
@@ -1,4 +1,4 @@
1
- import { F as Form, l as buildFormSchema, h as Section, q as buildSectionSchema, Q as Question, o as buildQuestionSchema, f as ScoringRule, p as buildScoringRuleSchema, P as PlatformFunction, m as buildPlatformFunctionSchema, d as PlatformRole, n as buildPlatformRoleSchema, b as CvcRegistry, k as buildCvcRegistrySchema, a as CvcEntry, j as buildCvcEntrySchema } from './cvcEntry-D787utvP.js';
1
+ import { F as Form, l as buildFormSchema, h as Section, q as buildSectionSchema, Q as Question, o as buildQuestionSchema, f as ScoringRule, p as buildScoringRuleSchema, P as PlatformFunction, m as buildPlatformFunctionSchema, d as PlatformRole, n as buildPlatformRoleSchema, b as CvcRegistry, k as buildCvcRegistrySchema, a as CvcEntry, j as buildCvcEntrySchema } from './cvcEntry-BLeRivoF.js';
2
2
  import * as mongoose from 'mongoose';
3
3
  import { HydratedDocument, Connection, Model } from 'mongoose';
4
4
 
package/dist/index.d.cts CHANGED
@@ -3,9 +3,9 @@ export { ActiveServiceStateKey, CASEWORK_APP_IDS, CodebookPickerOption, Codebook
3
3
  export { D as DEFAULT_BOUND_STATE, a as DEFAULT_BOUND_STATE_DISPLAY, b as DEFAULT_BOUND_STATE_LABELS, c as DEFAULT_BOUND_STATE_VALUES, d as DefaultBoundStateValue, F as FUNCTION_STATUS, e as FUNCTION_STATUS_LABELS, f as FUNCTION_STATUS_VALUES, g as FunctionStatusValue, P as PERMISSION_STATE, h as PERMISSION_STATE_DISPLAY, i as PERMISSION_STATE_LABELS, j as PERMISSION_STATE_VALUES, k as PLATFORM_TOOL, l as PLATFORM_TOOL_LABELS, m as PLATFORM_TOOL_VALUES, n as PermissionStateValue, o as PlatformToolValue, R as ROLE_LEVEL, p as ROLE_LEVEL_LABELS, q as ROLE_LEVEL_VALUES, r as RoleLevelValue, S as SHARE_VIEW, s as SHARE_VIEW_LABELS, t as SHARE_VIEW_VALUES, u as ShareViewValue } from './platform-auth-DJO-r9Pf.cjs';
4
4
  export { A as AGENCY_TYPE_KEYS, a as AgencyTypeKey, H as HEALTHCARE_ORG_TYPE_KEYS, L as LAW_ENFORCEMENT_ORG_TYPE_KEYS, b as LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY, c as LEGAL_ORG_TYPE_KEYS, d as LegacyNumericReferralEntity, N as NO_SECTOR_ORG_TYPE_KEYS, O as ORG_TYPE_HEADING_KEYS, e as ORG_TYPE_KEYS, f as ORG_TYPE_NONPICKABLE_LEAF_KEYS, g as ORG_TYPE_PARENT_KEY, h as ORG_TYPE_SELECTABLE_KEYS, i as OrgTypeHeadingKey, j as OrgTypeKey, k as OrgTypeSelectableKey, R as REPORT_AUTHORITY_ORG_TYPE_KEYS, V as VICTIM_SERVING_ORG_TYPE_KEYS, l as isAgencyTypeKey, m as isHealthcareOrgType, n as isLawEnforcementOrgType, o as isLegalOrgType, p as isOrgTypeKey, q as isReportAuthorityOrgType, r as isVictimServingOrgType, s as orgTypeAncestry, t as orgTypeCanonicalCode, u as orgTypeDefaultSessionRole, v as orgTypeDefaultSessionRoleOrNull, w as orgTypeDefaultVsp, x as orgTypeEnumConstant, y as orgTypeLabel, z as orgTypeSector, B as resolveAgencyTypeKey, C as resolveOrgTypeKey, D as resolveOrgTypeKeyFromLegacyNumeric, E as resolveReferralEntityKeyFromLegacyNumeric } from './org-type-D_FG4KdN.cjs';
5
5
  export { AddOrganizationProgramsFieldOptions, Address, Demographics, Email, ORGANIZATION_PROGRAM_VALIDATED_UPDATE_OPS, ORG_KEY_INDEX_NAME, ORG_KEY_INDEX_OPTIONS, ORG_KEY_INDEX_SPEC, OrganizationProgram, PersonName, Phone, TEAM_MODEL_NAME, TeamDirectoryFields, addOrgRecordFields, addOrganizationProgramsField, addTeamDirectoryFields, addressSchema, buildOrganizationProgramSchema, buildOrganizationProgramsFieldDefinition, demographicsSchema, emailSchema, orgAsBuiltSchemaDefinition, orgRecordSchemaDefinition, organizationProgramSchemaDefinition, organizationSchemaIssues, personNameSchema, phoneSchema, teamDirectorySchemaDefinition } from './schemas/index.cjs';
6
- export { C as Choice, a as CvcEntry, b as CvcRegistry, F as Form, c as FormSectionRef, G as Guidance, L as Layout, P as PlatformFunction, d as PlatformRole, Q as Question, S as ScoringCondition, e as ScoringRecommendation, f as ScoringRule, g as ScoringThreshold, h as Section, i as SectionQuestionRef, V as VisibilityRule, j as buildCvcEntrySchema, k as buildCvcRegistrySchema, l as buildFormSchema, m as buildPlatformFunctionSchema, n as buildPlatformRoleSchema, o as buildQuestionSchema, p as buildScoringRuleSchema, q as buildSectionSchema, r as choiceSchema, s as cvcEntrySchemaDefinition, t as cvcEntrySchemaOptions, u as cvcRegistrySchemaDefinition, v as cvcRegistrySchemaOptions, w as formSchemaDefinition, x as formSchemaOptions, y as formSectionRefSchema, z as guidanceSchema, A as layoutSchema, B as platformFunctionSchemaDefinition, D as platformFunctionSchemaOptions, E as platformRoleSchemaDefinition, H as platformRoleSchemaOptions, I as questionSchemaDefinition, J as questionSchemaOptions, K as scoringConditionSchema, M as scoringRecommendationSchema, N as scoringRuleSchemaDefinition, O as scoringRuleSchemaOptions, R as scoringThresholdSchema, T as sectionQuestionRefSchema, U as sectionSchemaDefinition, W as sectionSchemaOptions, X as visibilityRuleSchema } from './cvcEntry-D787utvP.cjs';
6
+ export { C as Choice, a as CvcEntry, b as CvcRegistry, F as Form, c as FormSectionRef, G as Guidance, L as Layout, P as PlatformFunction, d as PlatformRole, Q as Question, S as ScoringCondition, e as ScoringRecommendation, f as ScoringRule, g as ScoringThreshold, h as Section, i as SectionQuestionRef, V as VisibilityRule, j as buildCvcEntrySchema, k as buildCvcRegistrySchema, l as buildFormSchema, m as buildPlatformFunctionSchema, n as buildPlatformRoleSchema, o as buildQuestionSchema, p as buildScoringRuleSchema, q as buildSectionSchema, r as choiceSchema, s as cvcEntrySchemaDefinition, t as cvcEntrySchemaOptions, u as cvcRegistrySchemaDefinition, v as cvcRegistrySchemaOptions, w as formSchemaDefinition, x as formSchemaOptions, y as formSectionRefSchema, z as guidanceSchema, A as layoutSchema, B as platformFunctionSchemaDefinition, D as platformFunctionSchemaOptions, E as platformRoleSchemaDefinition, H as platformRoleSchemaOptions, I as questionSchemaDefinition, J as questionSchemaOptions, K as scoringConditionSchema, M as scoringRecommendationSchema, N as scoringRuleSchemaDefinition, O as scoringRuleSchemaOptions, R as scoringThresholdSchema, T as sectionQuestionRefSchema, U as sectionSchemaDefinition, W as sectionSchemaOptions, X as visibilityRuleSchema } from './cvcEntry-BLeRivoF.cjs';
7
7
  export { A as AGENCY_ORG_TYPE_VALIDATED_UPDATE_OPS, a as AddAgencyOrgTypeFieldsOptions, b as AgencyOrgTypeFields, O as ORG_TYPE_FIELD_NAMES, c as OrgTypeFieldName, d as OrgTypeFields, e as OrgTypeFieldsHolder, V as VSP_TWO_STEP_ISSUE, f as addAgencyOrgTypeFields, g as addOrgTypeFields, h as agencyOrgTypeSchemaDefinition, i as applyRunValidatorsIfUnset, j as installVspTwoStepHooks, m as mirrorOrgTypeFields, o as orgTypeFieldsDiffer, k as orgTypeSchemaDefinition, r as resolveEffectiveOrgType, l as resolveEffectiveOrgTypeFields, v as vspTwoStepHolds, n as vspTwoStepHoldsOnUpdate } from './agency-BXvE4yWu.cjs';
8
- export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, e as compileCvcEntryModel, f as compileCvcRegistryModel, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from './index-XWSYon40.cjs';
8
+ export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, e as compileCvcEntryModel, f as compileCvcRegistryModel, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from './index-Bj-s0nZy.cjs';
9
9
  export { AccommodationTypeKey, AccommodationTypeKeys, ActionStepCompletionStatusKey, ActionStepCompletionStatusKeys, ActionStepTypeKey, ActionStepTypeKeys, ActivityTypeKey, ActivityTypeKeys, AdminRoleKey, AdminRoleKeys, AdministeringJurisdictionKey, AdministeringJurisdictionKeys, AgeBinReportingKey, AgeBinReportingKeys, AnnouncementAudienceScopeKey, AnnouncementAudienceScopeKeys, AnnouncementResponseTypeKey, AnnouncementResponseTypeKeys, AssertionDomainKey, AssertionDomainKeys, AssertionStatusKey, AssertionStatusKeys, BasisQuickPicksKey, BasisQuickPicksKeys, BirthCountryReportingKey, BirthCountryReportingKeys, CarCorrectionReasonKey, CarCorrectionReasonKeys, CaseShareChannelStateKey, CaseShareChannelStateKeys, CaseShareStateKey, CaseShareStateKeys, CheckInActivityKey, CheckInActivityKeys, CheckInPhaseKey, CheckInPhaseKeys, ChildBehavioralConcernsKey, ChildBehavioralConcernsKeys, ChildChangeTypeKey, ChildChangeTypeKeys, ChildCustodyArrangementKey, ChildCustodyArrangementKeys, CitizenshipKey, CitizenshipKeys, CollectionContextKey, CollectionContextKeys, ContactInfoTypeKey, ContactInfoTypeKeys, ContactInfoUseTypeKey, ContactInfoUseTypeKeys, ContactLinkTypeKey, ContactLinkTypeKeys, ContactSafetyStatusKey, ContactSafetyStatusKeys, CoreFunctionsKey, CoreFunctionsKeys, CoreIndicatorKey, CoreIndicatorKeys, CoreInformationScopeKey, CoreInformationScopeKeys, CoreReferralOutcomeKey, CoreReferralOutcomeKeys, CountryKey, CountryKeys, CreatedBySystemKey, CreatedBySystemKeys, CriminalOrgCategoryKey, CriminalOrgCategoryKeys, DaIncidentArchiveReasonKey, DaIncidentArchiveReasonKeys, DaIncidentConfidenceKey, DaIncidentConfidenceKeys, DaIncidentDayApproxKey, DaIncidentDayApproxKeys, DaIncidentSeverityKey, DaIncidentSeverityKeys, DeterminationHelperCategoryKey, DeterminationHelperCategoryKeys, DeterminationLevelKey, DeterminationLevelKeys, DhStateKey, DhStateKeys, DisabilityReportingKey, DisabilityReportingKeys, DisabilitySubtypeKey, DisabilitySubtypeKeys, DiscretionLevelKey, DiscretionLevelKeys, EmergencyContactCallReasonKey, EmergencyContactCallReasonKeys, EmergencyContactPermissionsKey, EmergencyContactPermissionsKeys, EmergencyExitCascadeKey, EmergencyExitCascadeKeys, EmploymentStatusKey, EmploymentStatusKeys, EnglishProficiencyKey, EnglishProficiencyKeys, EnrollmentApplicationStatusKey, EnrollmentApplicationStatusKeys, ExitProcessChecklistItemKey, ExitProcessChecklistItemKeys, ExitReasonsKey, ExitReasonsKeys, ExploitationTypeKey, ExploitationTypeKeys, EyeColorKey, EyeColorKeys, FacialHairKey, FacialHairKeys, FacilitatorEntityTypeKey, FacilitatorEntityTypeKeys, FacilitatorLabelUsedInSourceKey, FacilitatorLabelUsedInSourceKeys, FacilitatorSubroleKey, FacilitatorSubroleKeys, FrequencyCadenceKey, FrequencyCadenceKeys, FunderKey, FunderKeys, GenderIdentityKey, GenderIdentityKeys, GenderReportingKey, GenderReportingKeys, GeneralDisabilityKey, GeneralDisabilityKeys, GoalCategoryKey, GoalCategoryKeys, GoalPriorityKey, GoalPriorityKeys, GoalStatusKey, GoalStatusKeys, GoalWithdrawalReasonKey, GoalWithdrawalReasonKeys, HairColorKey, HairColorKeys, HandlingFlagsKey, HandlingFlagsKeys, HasTattoosKey, HasTattoosKeys, HighestEducationLevelCompletedKey, HighestEducationLevelCompletedKeys, HivStatusKey, HivStatusKeys, HmisCurrentLivingSituationKey, HmisCurrentLivingSituationKeys, HmisProjectTypeKey, HmisProjectTypeKeys, HmisRelationshipToHohKey, HmisRelationshipToHohKeys, HomelessStatusKey, HomelessStatusKeys, HopeScaleCaptureContextKey, HopeScaleCaptureContextKeys, HopeScaleResponseOptionsKey, HopeScaleResponseOptionsKeys, HopeScaleTierKey, HopeScaleTierKeys, HousingSubsidyTypesKey, HousingSubsidyTypesKeys, HtTypeKey, HtTypeKeys, IdentificationStatusKey, IdentificationStatusKeys, ImmigrationLegalStatusChangeTypeKey, ImmigrationLegalStatusChangeTypeKeys, IncarcerationEpisodeTypeKey, IncarcerationEpisodeTypeKeys, IncidentInvolvementRoleKey, IncidentInvolvementRoleKeys, IncidentParticipationRoleKey, IncidentParticipationRoleKeys, IncomeBenefitsSourcesKey, IncomeBenefitsSourcesKeys, InferenceTypeKey, InferenceTypeKeys, InvestigativeRequestTypeKey, InvestigativeRequestTypeKeys, JuvenileJusticeEpisodeTypeKey, JuvenileJusticeEpisodeTypeKeys, JuvenileJusticeInvolvementStatusKey, JuvenileJusticeInvolvementStatusKeys, LanguagesKey, LanguagesKeys, LeReportStatusKey, LeReportStatusKeys, LegalActionTypeKey, LegalActionTypeKeys, LivingSituationKey, LivingSituationKeys, LocationTypeKey, LocationTypeKeys, MaritalStatusLegalKey, MaritalStatusLegalKeys, MentalHealthStatusKey, MentalHealthStatusKeys, MessageReportReasonKey, MessageReportReasonKeys, MidStayEventTypeKey, MidStayEventTypeKeys, MilestoneTypeKey, MilestoneTypeKeys, MilitaryBranchKey, MilitaryBranchKeys, MilitaryStatusKey, MilitaryStatusKeys, MinorAdultStatusKey, MinorAdultStatusKeys, NameTypeKey, NameTypeKeys, NeedsAssessmentChangeTypeKey, NeedsAssessmentChangeTypeKeys, NeedsResidentialAgainKey, NeedsResidentialAgainKeys, OffenderStatusFamilyKey, OffenderStatusFamilyKeys, OffenderStatusKey, OffenderStatusKeys, OrientationIdentityKey, OrientationIdentityKeys, PersonRelationshipsKey, PersonRelationshipsKeys, PetExitReasonKey, PetExitReasonKeys, PetRelationshipBasisKey, PetRelationshipBasisKeys, PoPetitionBasisKey, PoPetitionBasisKeys, PoStatusKey, PoStatusKeys, PoViolationStatusKey, PoViolationStatusKeys, PreferredContactMethodKey, PreferredContactMethodKeys, PrimaryLanguageKey, PrimaryLanguageKeys, ProgramEnrollmentChangeTypeKey, ProgramEnrollmentChangeTypeKeys, ProgramSpecificCodeKey, ProgramSpecificCodeKeys, PronounsKey, PronounsKeys, ProofOfIdTypeKey, ProofOfIdTypeKeys, ProvenanceSourceIdKey, ProvenanceSourceIdKeys, QualityFlagsKey, QualityFlagsKeys, RaceEthnicityKey, RaceEthnicityKeys, RaceEthnicityReportingKey, RaceEthnicityReportingKeys, RadiusBucketKey, RadiusBucketKeys, RecencyBandKey, RecencyBandKeys, RecipientRoleKey, RecipientRoleKeys, RecordRemovalReasonKey, RecordRemovalReasonKeys, ReferenceLinkTypeKey, ReferenceLinkTypeKeys, ReferralEntityCategoryKey, ReferralEntityCategoryKeys, ReferralOriginKey, ReferralOriginKeys, RelationshipConcernKey, RelationshipConcernKeys, RelationshipDynamicsKey, RelationshipDynamicsKeys, RelationshipStatusCurrentKey, RelationshipStatusCurrentKeys, RelationshipTiesKey, RelationshipTiesKeys, ReportingAudienceKey, ReportingAudienceKeys, ReportingRegimeKey, ReportingRegimeKeys, ReturnedToAbuserStatusKey, ReturnedToAbuserStatusKeys, RiskCategoryKey, RiskCategoryKeys, RiskIdentificationMilestoneKey, RiskIdentificationMilestoneKeys, RiskSeverityBandKey, RiskSeverityBandKeys, RoiMethodKey, RoiMethodKeys, RoiScopeKey, RoiScopeKeys, RoiStatusKey, RoiStatusKeys, RoleContextKey, RoleContextKeys, RomanticRelationshipChangeTypeKey, RomanticRelationshipChangeTypeKeys, RsvpResponseKey, RsvpResponseKeys, ServiceAudienceKey, ServiceAudienceKeys, ServiceCategoryKey, ServiceCategoryKeys, ServiceDeliveryChangeTypeKey, ServiceDeliveryChangeTypeKeys, ServiceDeliveryChannelKey, ServiceDeliveryChannelKeys, ServiceMechanismKey, ServiceMechanismKeys, ServicePlanClosureReasonKey, ServicePlanClosureReasonKeys, ServicePlanReviewSnoozeReasonKey, ServicePlanReviewSnoozeReasonKeys, ServiceSourceKey, ServiceSourceKeys, ServiceStateKey, ServiceStateKeys, SessionNoteVisibilityKey, SessionNoteVisibilityKeys, SessionStateKey, SessionStateKeys, SessionTemplateKey, SessionTemplateKeys, SeverityFollowUpKey, SeverityFollowUpKeys, SexProviderSubroleKey, SexProviderSubroleKeys, ShareCadenceKey, ShareCadenceKeys, SharePurposeKey, SharePurposeKeys, ShareReleaseBasisKey, ShareReleaseBasisKeys, ShareResponseReasonKey, ShareResponseReasonKeys, SignatureMethodKey, SignatureMethodKeys, SignatureTypeKey, SignatureTypeKeys, SitePurposeKey, SitePurposeKeys, SmtBodyLocationKey, SmtBodyLocationKeys, SmtNameRelationKey, SmtNameRelationKeys, SmtSignificanceFlagsKey, SmtSignificanceFlagsKeys, SmtTypeKey, SmtTypeKeys, SourceCategoryKey, SourceCategoryKeys, SourceInstrumentKey, SourceInstrumentKeys, SourceSubtypeKey, SourceSubtypeKeys, SourceSystemKey, SourceSystemKeys, SpecialNeedsDisabilitiesKey, SpecialNeedsDisabilitiesKeys, SubjectTypeKey, SubjectTypeKeys, SubstanceUseStatusKey, SubstanceUseStatusKeys, SuggestionSourceKey, SuggestionSourceKeys, SupportStrengthKey, SupportStrengthKeys, SupportTopicKey, SupportTopicKeys, ThreadStatusKey, ThreadStatusKeys, ThreadTypeKey, ThreadTypeKeys, TimeScopeKey, TimeScopeKeys, TraffickingRelevantRoleKey, TraffickingRelevantRoleKeys, TribesKey, TribesKeys, UserRoleKey, UserRoleKeys, VehicleBodyTypeKey, VehicleBodyTypeKeys, VehicleColorKey, VehicleColorKeys, VerificationMethodKey, VerificationMethodKeys, VerificationStatusKey, VerificationStatusKeys, VeteranStatusKey, VeteranStatusKeys, VictimAbuseTypesKey, VictimAbuseTypesKeys, VictimStatusFamilyKey, VictimStatusFamilyKeys, VisaTypeKey, VisaTypeKeys, WhyNotKey, WhyNotKeys } from './enums/index.cjs';
10
10
  export { CvcRegistryService, CvcRegistryServiceOptions, EntryLoader, ICvcEntry, ICvcRegistry, RegistryLoader, RegistryScope, applyEntryOverrides, cascadeExclusions, cvcVersionsToRecord, resolveRegistryWithInheritance } from './services/index.cjs';
11
11
  export { C as CreateInformationScopeResolverInput, I as INFORMATION_SCOPE_POLICY_VERSION_ROW_NOTE, a as INFORMATION_SCOPE_READABLE_VERSIONS, b as INFORMATION_SCOPE_SYSTEM_INFO, c as INFORMATION_SCOPE_VERSION, d as InformationScopeResolver, S as ScopeApp, e as ScopeApps, f as ScopeCodeReading, g as ScopeKindBranch, h as ScopeMigration, i as ScopeMigrationRule, j as ScopePersonKind, k as ScopeReadOptions, l as ScopeReading, m as ScopeReadingRule, n as ScopeReadingSubject, o as ScopeRetainedReading, p as ScopeRow, q as ScopeRowStatus, r as ScopeRowType, s as ScopeShareOptions, t as ScopeShareReason, u as ScopeShareVerdict, v as ScopeSpecialDataType, w as ScopeSubjectKind, x as StoredScopeList, y as createInformationScopeResolver, z as isScopeInstrumentRow, A as isScopeRestRow, B as isSelectableScopeRow, D as kindForPerson } from './informationScopeResolver-BYiubygD.cjs';
package/dist/index.d.ts CHANGED
@@ -3,9 +3,9 @@ export { ActiveServiceStateKey, CASEWORK_APP_IDS, CodebookPickerOption, Codebook
3
3
  export { D as DEFAULT_BOUND_STATE, a as DEFAULT_BOUND_STATE_DISPLAY, b as DEFAULT_BOUND_STATE_LABELS, c as DEFAULT_BOUND_STATE_VALUES, d as DefaultBoundStateValue, F as FUNCTION_STATUS, e as FUNCTION_STATUS_LABELS, f as FUNCTION_STATUS_VALUES, g as FunctionStatusValue, P as PERMISSION_STATE, h as PERMISSION_STATE_DISPLAY, i as PERMISSION_STATE_LABELS, j as PERMISSION_STATE_VALUES, k as PLATFORM_TOOL, l as PLATFORM_TOOL_LABELS, m as PLATFORM_TOOL_VALUES, n as PermissionStateValue, o as PlatformToolValue, R as ROLE_LEVEL, p as ROLE_LEVEL_LABELS, q as ROLE_LEVEL_VALUES, r as RoleLevelValue, S as SHARE_VIEW, s as SHARE_VIEW_LABELS, t as SHARE_VIEW_VALUES, u as ShareViewValue } from './platform-auth-DJO-r9Pf.js';
4
4
  export { A as AGENCY_TYPE_KEYS, a as AgencyTypeKey, H as HEALTHCARE_ORG_TYPE_KEYS, L as LAW_ENFORCEMENT_ORG_TYPE_KEYS, b as LEGACY_NUMERIC_TO_REFERRAL_ENTITY_KEY, c as LEGAL_ORG_TYPE_KEYS, d as LegacyNumericReferralEntity, N as NO_SECTOR_ORG_TYPE_KEYS, O as ORG_TYPE_HEADING_KEYS, e as ORG_TYPE_KEYS, f as ORG_TYPE_NONPICKABLE_LEAF_KEYS, g as ORG_TYPE_PARENT_KEY, h as ORG_TYPE_SELECTABLE_KEYS, i as OrgTypeHeadingKey, j as OrgTypeKey, k as OrgTypeSelectableKey, R as REPORT_AUTHORITY_ORG_TYPE_KEYS, V as VICTIM_SERVING_ORG_TYPE_KEYS, l as isAgencyTypeKey, m as isHealthcareOrgType, n as isLawEnforcementOrgType, o as isLegalOrgType, p as isOrgTypeKey, q as isReportAuthorityOrgType, r as isVictimServingOrgType, s as orgTypeAncestry, t as orgTypeCanonicalCode, u as orgTypeDefaultSessionRole, v as orgTypeDefaultSessionRoleOrNull, w as orgTypeDefaultVsp, x as orgTypeEnumConstant, y as orgTypeLabel, z as orgTypeSector, B as resolveAgencyTypeKey, C as resolveOrgTypeKey, D as resolveOrgTypeKeyFromLegacyNumeric, E as resolveReferralEntityKeyFromLegacyNumeric } from './org-type-BYQb9Qzq.js';
5
5
  export { AddOrganizationProgramsFieldOptions, Address, Demographics, Email, ORGANIZATION_PROGRAM_VALIDATED_UPDATE_OPS, ORG_KEY_INDEX_NAME, ORG_KEY_INDEX_OPTIONS, ORG_KEY_INDEX_SPEC, OrganizationProgram, PersonName, Phone, TEAM_MODEL_NAME, TeamDirectoryFields, addOrgRecordFields, addOrganizationProgramsField, addTeamDirectoryFields, addressSchema, buildOrganizationProgramSchema, buildOrganizationProgramsFieldDefinition, demographicsSchema, emailSchema, orgAsBuiltSchemaDefinition, orgRecordSchemaDefinition, organizationProgramSchemaDefinition, organizationSchemaIssues, personNameSchema, phoneSchema, teamDirectorySchemaDefinition } from './schemas/index.js';
6
- export { C as Choice, a as CvcEntry, b as CvcRegistry, F as Form, c as FormSectionRef, G as Guidance, L as Layout, P as PlatformFunction, d as PlatformRole, Q as Question, S as ScoringCondition, e as ScoringRecommendation, f as ScoringRule, g as ScoringThreshold, h as Section, i as SectionQuestionRef, V as VisibilityRule, j as buildCvcEntrySchema, k as buildCvcRegistrySchema, l as buildFormSchema, m as buildPlatformFunctionSchema, n as buildPlatformRoleSchema, o as buildQuestionSchema, p as buildScoringRuleSchema, q as buildSectionSchema, r as choiceSchema, s as cvcEntrySchemaDefinition, t as cvcEntrySchemaOptions, u as cvcRegistrySchemaDefinition, v as cvcRegistrySchemaOptions, w as formSchemaDefinition, x as formSchemaOptions, y as formSectionRefSchema, z as guidanceSchema, A as layoutSchema, B as platformFunctionSchemaDefinition, D as platformFunctionSchemaOptions, E as platformRoleSchemaDefinition, H as platformRoleSchemaOptions, I as questionSchemaDefinition, J as questionSchemaOptions, K as scoringConditionSchema, M as scoringRecommendationSchema, N as scoringRuleSchemaDefinition, O as scoringRuleSchemaOptions, R as scoringThresholdSchema, T as sectionQuestionRefSchema, U as sectionSchemaDefinition, W as sectionSchemaOptions, X as visibilityRuleSchema } from './cvcEntry-D787utvP.js';
6
+ export { C as Choice, a as CvcEntry, b as CvcRegistry, F as Form, c as FormSectionRef, G as Guidance, L as Layout, P as PlatformFunction, d as PlatformRole, Q as Question, S as ScoringCondition, e as ScoringRecommendation, f as ScoringRule, g as ScoringThreshold, h as Section, i as SectionQuestionRef, V as VisibilityRule, j as buildCvcEntrySchema, k as buildCvcRegistrySchema, l as buildFormSchema, m as buildPlatformFunctionSchema, n as buildPlatformRoleSchema, o as buildQuestionSchema, p as buildScoringRuleSchema, q as buildSectionSchema, r as choiceSchema, s as cvcEntrySchemaDefinition, t as cvcEntrySchemaOptions, u as cvcRegistrySchemaDefinition, v as cvcRegistrySchemaOptions, w as formSchemaDefinition, x as formSchemaOptions, y as formSectionRefSchema, z as guidanceSchema, A as layoutSchema, B as platformFunctionSchemaDefinition, D as platformFunctionSchemaOptions, E as platformRoleSchemaDefinition, H as platformRoleSchemaOptions, I as questionSchemaDefinition, J as questionSchemaOptions, K as scoringConditionSchema, M as scoringRecommendationSchema, N as scoringRuleSchemaDefinition, O as scoringRuleSchemaOptions, R as scoringThresholdSchema, T as sectionQuestionRefSchema, U as sectionSchemaDefinition, W as sectionSchemaOptions, X as visibilityRuleSchema } from './cvcEntry-BLeRivoF.js';
7
7
  export { A as AGENCY_ORG_TYPE_VALIDATED_UPDATE_OPS, a as AddAgencyOrgTypeFieldsOptions, b as AgencyOrgTypeFields, O as ORG_TYPE_FIELD_NAMES, c as OrgTypeFieldName, d as OrgTypeFields, e as OrgTypeFieldsHolder, V as VSP_TWO_STEP_ISSUE, f as addAgencyOrgTypeFields, g as addOrgTypeFields, h as agencyOrgTypeSchemaDefinition, i as applyRunValidatorsIfUnset, j as installVspTwoStepHooks, m as mirrorOrgTypeFields, o as orgTypeFieldsDiffer, k as orgTypeSchemaDefinition, r as resolveEffectiveOrgType, l as resolveEffectiveOrgTypeFields, v as vspTwoStepHolds, n as vspTwoStepHoldsOnUpdate } from './agency-NEW6NOGD.js';
8
- export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, e as compileCvcEntryModel, f as compileCvcRegistryModel, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from './index-Bh1zO_Vu.js';
8
+ export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, e as compileCvcEntryModel, f as compileCvcRegistryModel, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from './index-DvAypMJV.js';
9
9
  export { AccommodationTypeKey, AccommodationTypeKeys, ActionStepCompletionStatusKey, ActionStepCompletionStatusKeys, ActionStepTypeKey, ActionStepTypeKeys, ActivityTypeKey, ActivityTypeKeys, AdminRoleKey, AdminRoleKeys, AdministeringJurisdictionKey, AdministeringJurisdictionKeys, AgeBinReportingKey, AgeBinReportingKeys, AnnouncementAudienceScopeKey, AnnouncementAudienceScopeKeys, AnnouncementResponseTypeKey, AnnouncementResponseTypeKeys, AssertionDomainKey, AssertionDomainKeys, AssertionStatusKey, AssertionStatusKeys, BasisQuickPicksKey, BasisQuickPicksKeys, BirthCountryReportingKey, BirthCountryReportingKeys, CarCorrectionReasonKey, CarCorrectionReasonKeys, CaseShareChannelStateKey, CaseShareChannelStateKeys, CaseShareStateKey, CaseShareStateKeys, CheckInActivityKey, CheckInActivityKeys, CheckInPhaseKey, CheckInPhaseKeys, ChildBehavioralConcernsKey, ChildBehavioralConcernsKeys, ChildChangeTypeKey, ChildChangeTypeKeys, ChildCustodyArrangementKey, ChildCustodyArrangementKeys, CitizenshipKey, CitizenshipKeys, CollectionContextKey, CollectionContextKeys, ContactInfoTypeKey, ContactInfoTypeKeys, ContactInfoUseTypeKey, ContactInfoUseTypeKeys, ContactLinkTypeKey, ContactLinkTypeKeys, ContactSafetyStatusKey, ContactSafetyStatusKeys, CoreFunctionsKey, CoreFunctionsKeys, CoreIndicatorKey, CoreIndicatorKeys, CoreInformationScopeKey, CoreInformationScopeKeys, CoreReferralOutcomeKey, CoreReferralOutcomeKeys, CountryKey, CountryKeys, CreatedBySystemKey, CreatedBySystemKeys, CriminalOrgCategoryKey, CriminalOrgCategoryKeys, DaIncidentArchiveReasonKey, DaIncidentArchiveReasonKeys, DaIncidentConfidenceKey, DaIncidentConfidenceKeys, DaIncidentDayApproxKey, DaIncidentDayApproxKeys, DaIncidentSeverityKey, DaIncidentSeverityKeys, DeterminationHelperCategoryKey, DeterminationHelperCategoryKeys, DeterminationLevelKey, DeterminationLevelKeys, DhStateKey, DhStateKeys, DisabilityReportingKey, DisabilityReportingKeys, DisabilitySubtypeKey, DisabilitySubtypeKeys, DiscretionLevelKey, DiscretionLevelKeys, EmergencyContactCallReasonKey, EmergencyContactCallReasonKeys, EmergencyContactPermissionsKey, EmergencyContactPermissionsKeys, EmergencyExitCascadeKey, EmergencyExitCascadeKeys, EmploymentStatusKey, EmploymentStatusKeys, EnglishProficiencyKey, EnglishProficiencyKeys, EnrollmentApplicationStatusKey, EnrollmentApplicationStatusKeys, ExitProcessChecklistItemKey, ExitProcessChecklistItemKeys, ExitReasonsKey, ExitReasonsKeys, ExploitationTypeKey, ExploitationTypeKeys, EyeColorKey, EyeColorKeys, FacialHairKey, FacialHairKeys, FacilitatorEntityTypeKey, FacilitatorEntityTypeKeys, FacilitatorLabelUsedInSourceKey, FacilitatorLabelUsedInSourceKeys, FacilitatorSubroleKey, FacilitatorSubroleKeys, FrequencyCadenceKey, FrequencyCadenceKeys, FunderKey, FunderKeys, GenderIdentityKey, GenderIdentityKeys, GenderReportingKey, GenderReportingKeys, GeneralDisabilityKey, GeneralDisabilityKeys, GoalCategoryKey, GoalCategoryKeys, GoalPriorityKey, GoalPriorityKeys, GoalStatusKey, GoalStatusKeys, GoalWithdrawalReasonKey, GoalWithdrawalReasonKeys, HairColorKey, HairColorKeys, HandlingFlagsKey, HandlingFlagsKeys, HasTattoosKey, HasTattoosKeys, HighestEducationLevelCompletedKey, HighestEducationLevelCompletedKeys, HivStatusKey, HivStatusKeys, HmisCurrentLivingSituationKey, HmisCurrentLivingSituationKeys, HmisProjectTypeKey, HmisProjectTypeKeys, HmisRelationshipToHohKey, HmisRelationshipToHohKeys, HomelessStatusKey, HomelessStatusKeys, HopeScaleCaptureContextKey, HopeScaleCaptureContextKeys, HopeScaleResponseOptionsKey, HopeScaleResponseOptionsKeys, HopeScaleTierKey, HopeScaleTierKeys, HousingSubsidyTypesKey, HousingSubsidyTypesKeys, HtTypeKey, HtTypeKeys, IdentificationStatusKey, IdentificationStatusKeys, ImmigrationLegalStatusChangeTypeKey, ImmigrationLegalStatusChangeTypeKeys, IncarcerationEpisodeTypeKey, IncarcerationEpisodeTypeKeys, IncidentInvolvementRoleKey, IncidentInvolvementRoleKeys, IncidentParticipationRoleKey, IncidentParticipationRoleKeys, IncomeBenefitsSourcesKey, IncomeBenefitsSourcesKeys, InferenceTypeKey, InferenceTypeKeys, InvestigativeRequestTypeKey, InvestigativeRequestTypeKeys, JuvenileJusticeEpisodeTypeKey, JuvenileJusticeEpisodeTypeKeys, JuvenileJusticeInvolvementStatusKey, JuvenileJusticeInvolvementStatusKeys, LanguagesKey, LanguagesKeys, LeReportStatusKey, LeReportStatusKeys, LegalActionTypeKey, LegalActionTypeKeys, LivingSituationKey, LivingSituationKeys, LocationTypeKey, LocationTypeKeys, MaritalStatusLegalKey, MaritalStatusLegalKeys, MentalHealthStatusKey, MentalHealthStatusKeys, MessageReportReasonKey, MessageReportReasonKeys, MidStayEventTypeKey, MidStayEventTypeKeys, MilestoneTypeKey, MilestoneTypeKeys, MilitaryBranchKey, MilitaryBranchKeys, MilitaryStatusKey, MilitaryStatusKeys, MinorAdultStatusKey, MinorAdultStatusKeys, NameTypeKey, NameTypeKeys, NeedsAssessmentChangeTypeKey, NeedsAssessmentChangeTypeKeys, NeedsResidentialAgainKey, NeedsResidentialAgainKeys, OffenderStatusFamilyKey, OffenderStatusFamilyKeys, OffenderStatusKey, OffenderStatusKeys, OrientationIdentityKey, OrientationIdentityKeys, PersonRelationshipsKey, PersonRelationshipsKeys, PetExitReasonKey, PetExitReasonKeys, PetRelationshipBasisKey, PetRelationshipBasisKeys, PoPetitionBasisKey, PoPetitionBasisKeys, PoStatusKey, PoStatusKeys, PoViolationStatusKey, PoViolationStatusKeys, PreferredContactMethodKey, PreferredContactMethodKeys, PrimaryLanguageKey, PrimaryLanguageKeys, ProgramEnrollmentChangeTypeKey, ProgramEnrollmentChangeTypeKeys, ProgramSpecificCodeKey, ProgramSpecificCodeKeys, PronounsKey, PronounsKeys, ProofOfIdTypeKey, ProofOfIdTypeKeys, ProvenanceSourceIdKey, ProvenanceSourceIdKeys, QualityFlagsKey, QualityFlagsKeys, RaceEthnicityKey, RaceEthnicityKeys, RaceEthnicityReportingKey, RaceEthnicityReportingKeys, RadiusBucketKey, RadiusBucketKeys, RecencyBandKey, RecencyBandKeys, RecipientRoleKey, RecipientRoleKeys, RecordRemovalReasonKey, RecordRemovalReasonKeys, ReferenceLinkTypeKey, ReferenceLinkTypeKeys, ReferralEntityCategoryKey, ReferralEntityCategoryKeys, ReferralOriginKey, ReferralOriginKeys, RelationshipConcernKey, RelationshipConcernKeys, RelationshipDynamicsKey, RelationshipDynamicsKeys, RelationshipStatusCurrentKey, RelationshipStatusCurrentKeys, RelationshipTiesKey, RelationshipTiesKeys, ReportingAudienceKey, ReportingAudienceKeys, ReportingRegimeKey, ReportingRegimeKeys, ReturnedToAbuserStatusKey, ReturnedToAbuserStatusKeys, RiskCategoryKey, RiskCategoryKeys, RiskIdentificationMilestoneKey, RiskIdentificationMilestoneKeys, RiskSeverityBandKey, RiskSeverityBandKeys, RoiMethodKey, RoiMethodKeys, RoiScopeKey, RoiScopeKeys, RoiStatusKey, RoiStatusKeys, RoleContextKey, RoleContextKeys, RomanticRelationshipChangeTypeKey, RomanticRelationshipChangeTypeKeys, RsvpResponseKey, RsvpResponseKeys, ServiceAudienceKey, ServiceAudienceKeys, ServiceCategoryKey, ServiceCategoryKeys, ServiceDeliveryChangeTypeKey, ServiceDeliveryChangeTypeKeys, ServiceDeliveryChannelKey, ServiceDeliveryChannelKeys, ServiceMechanismKey, ServiceMechanismKeys, ServicePlanClosureReasonKey, ServicePlanClosureReasonKeys, ServicePlanReviewSnoozeReasonKey, ServicePlanReviewSnoozeReasonKeys, ServiceSourceKey, ServiceSourceKeys, ServiceStateKey, ServiceStateKeys, SessionNoteVisibilityKey, SessionNoteVisibilityKeys, SessionStateKey, SessionStateKeys, SessionTemplateKey, SessionTemplateKeys, SeverityFollowUpKey, SeverityFollowUpKeys, SexProviderSubroleKey, SexProviderSubroleKeys, ShareCadenceKey, ShareCadenceKeys, SharePurposeKey, SharePurposeKeys, ShareReleaseBasisKey, ShareReleaseBasisKeys, ShareResponseReasonKey, ShareResponseReasonKeys, SignatureMethodKey, SignatureMethodKeys, SignatureTypeKey, SignatureTypeKeys, SitePurposeKey, SitePurposeKeys, SmtBodyLocationKey, SmtBodyLocationKeys, SmtNameRelationKey, SmtNameRelationKeys, SmtSignificanceFlagsKey, SmtSignificanceFlagsKeys, SmtTypeKey, SmtTypeKeys, SourceCategoryKey, SourceCategoryKeys, SourceInstrumentKey, SourceInstrumentKeys, SourceSubtypeKey, SourceSubtypeKeys, SourceSystemKey, SourceSystemKeys, SpecialNeedsDisabilitiesKey, SpecialNeedsDisabilitiesKeys, SubjectTypeKey, SubjectTypeKeys, SubstanceUseStatusKey, SubstanceUseStatusKeys, SuggestionSourceKey, SuggestionSourceKeys, SupportStrengthKey, SupportStrengthKeys, SupportTopicKey, SupportTopicKeys, ThreadStatusKey, ThreadStatusKeys, ThreadTypeKey, ThreadTypeKeys, TimeScopeKey, TimeScopeKeys, TraffickingRelevantRoleKey, TraffickingRelevantRoleKeys, TribesKey, TribesKeys, UserRoleKey, UserRoleKeys, VehicleBodyTypeKey, VehicleBodyTypeKeys, VehicleColorKey, VehicleColorKeys, VerificationMethodKey, VerificationMethodKeys, VerificationStatusKey, VerificationStatusKeys, VeteranStatusKey, VeteranStatusKeys, VictimAbuseTypesKey, VictimAbuseTypesKeys, VictimStatusFamilyKey, VictimStatusFamilyKeys, VisaTypeKey, VisaTypeKeys, WhyNotKey, WhyNotKeys } from './enums/index.js';
10
10
  export { CvcRegistryService, CvcRegistryServiceOptions, EntryLoader, ICvcEntry, ICvcRegistry, RegistryLoader, RegistryScope, applyEntryOverrides, cascadeExclusions, cvcVersionsToRecord, resolveRegistryWithInheritance } from './services/index.js';
11
11
  export { C as CreateInformationScopeResolverInput, I as INFORMATION_SCOPE_POLICY_VERSION_ROW_NOTE, a as INFORMATION_SCOPE_READABLE_VERSIONS, b as INFORMATION_SCOPE_SYSTEM_INFO, c as INFORMATION_SCOPE_VERSION, d as InformationScopeResolver, S as ScopeApp, e as ScopeApps, f as ScopeCodeReading, g as ScopeKindBranch, h as ScopeMigration, i as ScopeMigrationRule, j as ScopePersonKind, k as ScopeReadOptions, l as ScopeReading, m as ScopeReadingRule, n as ScopeReadingSubject, o as ScopeRetainedReading, p as ScopeRow, q as ScopeRowStatus, r as ScopeRowType, s as ScopeShareOptions, t as ScopeShareReason, u as ScopeShareVerdict, v as ScopeSpecialDataType, w as ScopeSubjectKind, x as StoredScopeList, y as createInformationScopeResolver, z as isScopeInstrumentRow, A as isScopeRestRow, B as isSelectableScopeRow, D as kindForPerson } from './informationScopeResolver-BYiubygD.js';
@@ -1,3 +1,3 @@
1
- export { a as CvcEntry, b as CvcRegistry, F as Form, P as PlatformFunction, d as PlatformRole, Q as Question, f as ScoringRule, h as Section } from '../cvcEntry-D787utvP.cjs';
1
+ export { a as CvcEntry, b as CvcRegistry, F as Form, P as PlatformFunction, d as PlatformRole, Q as Question, f as ScoringRule, h as Section } from '../cvcEntry-BLeRivoF.cjs';
2
2
  import 'mongoose';
3
- export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from '../index-XWSYon40.cjs';
3
+ export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from '../index-Bj-s0nZy.cjs';
@@ -1,3 +1,3 @@
1
- export { a as CvcEntry, b as CvcRegistry, F as Form, P as PlatformFunction, d as PlatformRole, Q as Question, f as ScoringRule, h as Section } from '../cvcEntry-D787utvP.js';
1
+ export { a as CvcEntry, b as CvcRegistry, F as Form, P as PlatformFunction, d as PlatformRole, Q as Question, f as ScoringRule, h as Section } from '../cvcEntry-BLeRivoF.js';
2
2
  import 'mongoose';
3
- export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from '../index-Bh1zO_Vu.js';
3
+ export { C as CvcEntryDoc, a as CvcRegistryDoc, F as FormDoc, P as PlatformFunctionDoc, b as PlatformModels, c as PlatformRoleDoc, Q as QuestionDoc, S as ScoringRuleDoc, d as SectionDoc, g as createPlatformModels, h as cvcEntryModel, i as cvcRegistryModel, j as formModel, p as platformFunctionModel, k as platformRoleModel, q as questionModel, s as scoringRuleModel, l as sectionModel } from '../index-DvAypMJV.js';
@@ -27,6 +27,7 @@ __export(orgMerge_exports, {
27
27
  THREAD_SAMPLE_ID_PREFIX: () => THREAD_SAMPLE_ID_PREFIX,
28
28
  YES: () => YES,
29
29
  appDatabaseProblem: () => appDatabaseProblem,
30
+ comparableId: () => comparableId,
30
31
  comparableName: () => comparableName,
31
32
  executeMerges: () => executeMerges,
32
33
  formatPlannedMerge: () => formatPlannedMerge,
@@ -41,6 +42,10 @@ var text = (v) => typeof v === "string" ? v.trim() : "";
41
42
  function comparableName(value) {
42
43
  return text(value).normalize("NFKD").toLowerCase().replace(/&/g, " and ").replace(/[^a-z0-9]+/g, " ").trim().replace(/^the /, "");
43
44
  }
45
+ function comparableId(value) {
46
+ const s = value.trim();
47
+ return /^[0-9a-fA-F]{24}$/.test(s) ? s.toLowerCase() : s;
48
+ }
44
49
  var sheetText = (v) => {
45
50
  const s = typeof v === "string" ? v : v == null ? "" : String(v);
46
51
  return /^[=+\-@\t\r]/.test(s) ? `'${s}` : s;
@@ -68,6 +73,12 @@ var PROGRAM_STATUS_VALUES = Object.freeze([
68
73
  PROGRAM_STATUS.ACTIVE,
69
74
  PROGRAM_STATUS.RETIRED
70
75
  ]);
76
+ function isLiveOrganizationProgram(row) {
77
+ return row.status !== PROGRAM_STATUS.RETIRED && row.reviewStatus !== PROGRAM_REVIEW_STATUS.REJECTED;
78
+ }
79
+ function programNameKey(name) {
80
+ return name.trim().toLowerCase();
81
+ }
71
82
 
72
83
  // src/orgDirectory/orgRecord.ts
73
84
  var ORG_REVIEW_STATUS = PROGRAM_REVIEW_STATUS;
@@ -641,14 +652,14 @@ var blank = (v) => v == null || typeof v === "string" && v.trim() === "";
641
652
  var idText = (v) => directoryIdString(v) ?? String(v);
642
653
  var HEX_242 = /^[0-9a-fA-F]{24}$/;
643
654
  var message = (err) => err instanceof Error ? err.message : String(err);
644
- var idOf = (driver, v) => typeof v === "string" ? v.trim().toLowerCase() : v instanceof driver.ObjectId ? v.toHexString() : null;
655
+ var idOf = (driver, v) => typeof v === "string" ? comparableId(v) : v instanceof driver.ObjectId ? v.toHexString() : null;
645
656
  function idForms(driver, id) {
646
657
  const s = idText(id);
647
658
  return HEX_242.test(s) ? [new driver.ObjectId(s.toLowerCase()), s.toLowerCase()] : [s];
648
659
  }
649
660
  function inFormOf(driver, from, keptId) {
650
661
  const s = idText(keptId);
651
- return from instanceof driver.ObjectId && HEX_242.test(s) ? new driver.ObjectId(s.toLowerCase()) : s.toLowerCase();
662
+ return from instanceof driver.ObjectId && HEX_242.test(s) ? new driver.ObjectId(s.toLowerCase()) : comparableId(s);
652
663
  }
653
664
  var THREAD_SAMPLE_ID_PREFIX = "64e4ff1c2a7dcd9cb5f4a";
654
665
  var APP_LABEL = { platform: "the platform", thread: "Thread", pave: "PAVE" };
@@ -685,16 +696,33 @@ var ORG_REFERENCES = Object.freeze([
685
696
  ]);
686
697
  var APP_DATABASE_KINDS = ["thread", "pave"];
687
698
  var APP_MARKER = { thread: "caserecords", pave: "protectedpeople" };
699
+ var PAVE_ONLY_COLLECTIONS = ["programhousingenrollments", "disclosure_records", "reportingdestinationconfigs"];
688
700
  async function appDatabaseProblem(app, name, db) {
689
- const found = await db.listCollections({ name: APP_MARKER[app] }, { nameOnly: true }).toArray();
690
- return found.length ? null : `'${name}' has no ${APP_MARKER[app]} collection, so it is not a ${APP_LABEL[app]} database (check the name)`;
701
+ const has = async (collection) => (await db.listCollections({ name: collection }, { nameOnly: true }).toArray()).length > 0;
702
+ if (!await has(APP_MARKER[app])) {
703
+ return `'${name}' has no ${APP_MARKER[app]} collection, so it is not a ${APP_LABEL[app]} database (check the name)`;
704
+ }
705
+ let paves = null;
706
+ for (const c of PAVE_ONLY_COLLECTIONS) {
707
+ if (await has(c)) {
708
+ paves = c;
709
+ break;
710
+ }
711
+ }
712
+ if (app === "thread" && paves) {
713
+ return `'${name}' has a ${paves} collection, which only PAVE's database has, so it is not a Thread database (check the name)`;
714
+ }
715
+ if (app === "pave" && !paves) {
716
+ return `'${name}' has none of the collections only PAVE's database has (${PAVE_ONLY_COLLECTIONS.join(", ")}), so it is not a PAVE database (check the name)`;
717
+ }
718
+ return null;
691
719
  }
692
720
  var refPath = (r) => r.kind === "rows" || r.kind === "answers" ? `${r.path}.${String(r.field)}` : r.path;
693
721
  function getPath(doc, path) {
694
722
  return path.split(".").reduce((v, k) => v && typeof v === "object" ? v[k] : void 0, doc);
695
723
  }
696
724
  function rewriteIds(driver, list, copy, kept) {
697
- const keptHex = idText(kept).toLowerCase();
725
+ const keptHex = comparableId(idText(kept));
698
726
  let hasKept = list.some((v) => idOf(driver, v) === keptHex);
699
727
  const out = [];
700
728
  for (const v of list) {
@@ -731,7 +759,7 @@ function rewriteAnswers(driver, answers, field, copy, kept) {
731
759
  }
732
760
  async function findReferences(driver, dbs, orgId, keptId) {
733
761
  const out = [];
734
- const copy = idText(orgId).toLowerCase();
762
+ const copy = comparableId(idText(orgId));
735
763
  for (const d of dbs) {
736
764
  for (const ref of ORG_REFERENCES.filter((r) => r.app === d.app)) {
737
765
  if (ref.kind === "count") continue;
@@ -748,7 +776,7 @@ async function findReferences(driver, dbs, orgId, keptId) {
748
776
  const before = getPath(doc, ref.path);
749
777
  if (!Array.isArray(before)) continue;
750
778
  const after = ref.kind === "list" ? rewriteIds(driver, before, copy, keptId) : ref.kind === "rows" ? rewriteRows(driver, before, String(ref.field), copy, keptId) : rewriteAnswers(driver, before, String(ref.field), copy, keptId);
751
- out.push({ ...base, docId: doc._id, from: copy, to: idText(keptId).toLowerCase(), before, after });
779
+ out.push({ ...base, docId: doc._id, from: copy, to: comparableId(idText(keptId)), before, after });
752
780
  }
753
781
  }
754
782
  }
@@ -781,7 +809,11 @@ async function holdsMerged(db, ref) {
781
809
  }
782
810
  var MERGE = "merge";
783
811
  var YES = "yes";
784
- async function planMerges(dbs, lines, driver) {
812
+ async function planMerges(dbs, lines, driver, opts) {
813
+ if (opts?.mergedBy !== "steward" && opts?.mergedBy !== "agency") {
814
+ throw new Error("planMerges: say who is merging (mergedBy: 'steward' or 'agency')");
815
+ }
816
+ const byAgency = opts.mergedBy === "agency";
785
817
  const platform = dbs[0];
786
818
  const orgs = platform.db.collection(ORGANIZATIONS_COLLECTION);
787
819
  const agencies = platform.db.collection(AGENCIES_COLLECTION);
@@ -824,7 +856,7 @@ async function planMerges(dbs, lines, driver) {
824
856
  const skip = (detail) => {
825
857
  out.push({ ...base, status: "skip", detail, flags });
826
858
  };
827
- if (line2.duplicateId.trim().toLowerCase() === line2.keptId.trim().toLowerCase()) {
859
+ if (comparableId(line2.duplicateId) === comparableId(line2.keptId)) {
828
860
  skip("the copy and the kept organization are the same row");
829
861
  continue;
830
862
  }
@@ -855,15 +887,45 @@ async function planMerges(dbs, lines, driver) {
855
887
  skip("the copy is an Agency's own organization (it names an Agency, or an Agency points at it): that is not a copy");
856
888
  continue;
857
889
  }
890
+ let programs;
858
891
  if (Array.isArray(dup.programs) && dup.programs.length) {
859
- skip("the copy has programs; merging programs is not supported");
860
- continue;
892
+ if (byAgency) {
893
+ skip("the copy has programs; merging programs is not supported");
894
+ continue;
895
+ }
896
+ const stored = async (id) => (await orgs.findOne({ _id: id }, { projection: { programs: 1 }, promoteValues: false }))?.programs;
897
+ const [keptRows, dupRows] = [await stored(kept._id), await stored(dup._id)];
898
+ if (!Array.isArray(dupRows) || dupRows.length !== dup.programs.length) {
899
+ skip("the copy's programs changed while the plan was read; plan again");
900
+ continue;
901
+ }
902
+ const keptHad = Array.isArray(keptRows);
903
+ const keptBefore = keptHad ? keptRows : [];
904
+ const idOfProgram = (r) => r && typeof r === "object" ? text4(r.programId) : "";
905
+ const keptIds = new Set(keptBefore.map(idOfProgram).filter(Boolean));
906
+ const twin = dupRows.map(idOfProgram).find((id) => id && keptIds.has(id));
907
+ if (twin) {
908
+ skip(`a program of the copy has the same id as a program of the kept organization (${twin}); two programs cannot share an id`);
909
+ continue;
910
+ }
911
+ programs = { keptHad, keptBefore, moved: dupRows };
912
+ const liveName = (r) => {
913
+ const row = r && typeof r === "object" ? r : {};
914
+ return typeof row.name === "string" && isLiveOrganizationProgram(row) ? programNameKey(row.name) : "";
915
+ };
916
+ const keptNames = new Set(keptBefore.map(liveName).filter(Boolean));
917
+ const same = programs.moved.filter((r) => liveName(r) && keptNames.has(liveName(r))).map((r) => text4(r.name));
918
+ if (same.length) {
919
+ flags.push(
920
+ `${same.length} program(s) of the copy have the name of a live program of the kept organization (${same.join(", ")}); both are kept, as two programs`
921
+ );
922
+ }
861
923
  }
862
924
  if (!isListedOrganization(kept)) {
863
925
  skip("the kept organization is inactive or declined: nothing is merged into a row that is not offered");
864
926
  continue;
865
927
  }
866
- if (await isUnitOf(kept, idText(dup._id).toLowerCase())) {
928
+ if (await isUnitOf(kept, comparableId(idText(dup._id)))) {
867
929
  skip("the kept organization is a unit of the copy (the copy is on its chain of parent organizations)");
868
930
  continue;
869
931
  }
@@ -879,10 +941,17 @@ async function planMerges(dbs, lines, driver) {
879
941
  const state = typeof viewer?.state === "string" ? viewer.state : "";
880
942
  const community = typeof kept.community === "string" ? kept.community : "";
881
943
  if (!sameList && !(state !== "" && state === community)) {
882
- skip(
883
- `the kept organization could not be seen by the agency whose list the copy is in: the copy is ${base.duplicateList} (that agency's state ${JSON.stringify(state)}), the kept row is ${base.keptList} (community ${JSON.stringify(community)}). An agency sees another list's organization only when its state is exactly that organization's community. The kept row's list or community is corrected first, by a deliberate edit`
884
- );
885
- continue;
944
+ if (byAgency) {
945
+ skip(
946
+ `the kept organization could not be seen by the agency whose list the copy is in: the copy is ${base.duplicateList} (that agency's state ${JSON.stringify(state)}), the kept row is ${base.keptList} (community ${JSON.stringify(community)}). An agency sees another list's organization only when its state is exactly that organization's community. The kept row's list or community is corrected first, by a deliberate edit`
947
+ );
948
+ continue;
949
+ }
950
+ if (viewer) {
951
+ flags.push(
952
+ `until Thread and PAVE show every agency the one organization list, ${text4(viewer.name) || "the agency that added the copy"} may not see the kept organization's name on its records that move` + (programs ? `, or pick the ${programs.moved.length} program(s) that move to it` : "")
953
+ );
954
+ }
886
955
  }
887
956
  const keyed = !blank(dup.key);
888
957
  if (keyed) {
@@ -898,6 +967,12 @@ async function planMerges(dbs, lines, driver) {
898
967
  const k = `${r.db} ${r.collection}.${refPath(r)}`;
899
968
  moves.set(k, (moves.get(k) ?? 0) + 1);
900
969
  }
970
+ if (programs && unchecked.length) {
971
+ const where = unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(" and ");
972
+ flags.push(
973
+ `${where} could not be checked: a record there that names the copy with one of its programs still names the copy, while the programs are the kept organization's now; run the merge again with every database to move those records`
974
+ );
975
+ }
901
976
  const why = [
902
977
  ...unchecked.length ? [`references in ${unchecked.map((k) => `${APP_LABEL[k]}'s database`).join(" and ")} could not be checked`] : [],
903
978
  ...grants ? [`${grants} sharing grant(s) name the copy, and sharing rules are never moved`] : []
@@ -906,7 +981,7 @@ async function planMerges(dbs, lines, driver) {
906
981
  out.push({
907
982
  ...base,
908
983
  status: "merge",
909
- detail: `${moves.size ? `moves ${[...moves].map(([k, n]) => `${n} in ${k}`).join(", ")}` : "nothing points at the copy"}; ${then}`,
984
+ detail: `${moves.size ? `moves ${[...moves].map(([k, n]) => `${n} in ${k}`).join(", ")}` : "nothing points at the copy"}; ${programs ? `its ${programs.moved.length} program(s) move to the kept organization; ` : ""}${then}`,
910
985
  flags,
911
986
  write: {
912
987
  duplicateId: dup._id,
@@ -916,7 +991,8 @@ async function planMerges(dbs, lines, driver) {
916
991
  duplicate: dup,
917
992
  refs,
918
993
  outcome,
919
- addsLegacyEntry: !listed
994
+ addsLegacyEntry: !listed,
995
+ ...programs ? { programs } : {}
920
996
  }
921
997
  });
922
998
  }
@@ -926,6 +1002,7 @@ function formatPlannedMerge(p) {
926
1002
  return ` ${p.status.padEnd(6)} ${p.line.duplicateId} ${p.duplicateName || "(no organization)"}${p.duplicateList ? ` (${p.duplicateList})` : ""} -> ${p.line.keptId} ${p.keptName || "(no organization)"}${p.keptList ? ` (${p.keptList})` : ""}
927
1003
  ${p.detail}${p.flags.map((f) => ` [${f}]`).join("")}`;
928
1004
  }
1005
+ var 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";
929
1006
  async function executeMerges(dbs, merges, now, driver) {
930
1007
  const orgs = dbs[0].db.collection(ORGANIZATIONS_COLLECTION);
931
1008
  const dbNamed = new Map(dbs.map((d) => [d.name, d.db]));
@@ -933,12 +1010,29 @@ async function executeMerges(dbs, merges, now, driver) {
933
1010
  for (const merge of merges) {
934
1011
  let moved = 0;
935
1012
  try {
1013
+ const programs = merge.programs;
936
1014
  const kept = await orgs.updateOne(
937
- { _id: merge.keptId, status: { $in: [null, ORGANIZATION_STATUS.ACTIVE] }, reviewStatus: { $ne: "rejected" } },
938
- { $addToSet: { "legacy_ids.merged_from": idText(merge.duplicateId) } }
1015
+ {
1016
+ _id: merge.keptId,
1017
+ status: { $in: [null, ORGANIZATION_STATUS.ACTIVE] },
1018
+ reviewStatus: { $ne: "rejected" },
1019
+ // The copy's programs join the kept row's only while that list is still exactly as the plan read it
1020
+ // (`null` matches a row that stores no list).
1021
+ ...programs ? { programs: programs.keptHad ? programs.keptBefore : null } : {}
1022
+ },
1023
+ {
1024
+ $addToSet: { "legacy_ids.merged_from": idText(merge.duplicateId) },
1025
+ // Added to the end: the kept row's own program rows are not rewritten, not even re-typed.
1026
+ ...programs ? programs.keptHad ? { $push: { programs: { $each: programs.moved } } } : { $set: { programs: programs.moved } } : {}
1027
+ }
939
1028
  );
940
1029
  if (kept.matchedCount !== 1) {
941
- out.push({ merge, status: "changed", moved, detail: "the kept organization is gone or no longer offered since the plan; nothing was written" });
1030
+ out.push({
1031
+ merge,
1032
+ status: "changed",
1033
+ moved,
1034
+ detail: `the kept organization is gone or no longer offered${programs ? ", or its programs changed," : ""} since the plan; nothing was written`
1035
+ });
942
1036
  continue;
943
1037
  }
944
1038
  let stale = 0;
@@ -951,14 +1045,14 @@ async function executeMerges(dbs, merges, now, driver) {
951
1045
  if (merge.outcome === "delete" && left === 0) {
952
1046
  const res2 = await orgs.deleteOne(asPlanned);
953
1047
  out.push(
954
- res2.deletedCount === 1 ? { merge, status: "deleted", moved } : { merge, status: "changed", moved, detail: "the copy changed since the plan and was left as it is; its references were moved" }
1048
+ res2.deletedCount === 1 ? { merge, status: "deleted", moved } : { 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 : ""}` }
955
1049
  );
956
1050
  continue;
957
1051
  }
958
- const res = await orgs.updateOne(asPlanned, { $set: { status: ORGANIZATION_STATUS.INACTIVE, updatedTime: now } });
1052
+ const res = await orgs.updateOne(asPlanned, { $set: { status: ORGANIZATION_STATUS.INACTIVE, updatedTime: now, ...programs ? { programs: [] } : {} } });
959
1053
  const why = merge.outcome === "delete" ? `${left} reference(s) still point at the copy${stale ? ` (${stale} changed since the plan)` : ""}, so it was not deleted` : left ? `${left} reference(s) still point at the copy` : void 0;
960
1054
  out.push(
961
- res.matchedCount === 1 ? { merge, status: "retired", moved, ...why ? { detail: why } : {} } : { merge, status: "changed", moved, detail: "the copy changed since the plan and was left as it is; its references were moved" }
1055
+ res.matchedCount === 1 ? { merge, status: "retired", moved, ...why ? { detail: why } : {} } : { 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 : ""}` }
962
1056
  );
963
1057
  } catch (err) {
964
1058
  out.push({ merge, status: "failed", moved, detail: message(err) });
@@ -979,7 +1073,15 @@ async function rollbackMerges(dbFor, images, opts, driver) {
979
1073
  let partial = false;
980
1074
  const before = image.duplicate;
981
1075
  const now = await orgs.findOne({ _id: image.duplicateId });
982
- const retiredHere = !!now && sameDocument(driver, now, { ...before, status: ORGANIZATION_STATUS.INACTIVE, updatedTime: images.appliedTime });
1076
+ const programs = image.programs;
1077
+ const retiredHere = !!now && sameDocument(driver, now, {
1078
+ ...before,
1079
+ status: ORGANIZATION_STATUS.INACTIVE,
1080
+ updatedTime: images.appliedTime,
1081
+ // A copy the merge kept as inactive was left with no programs (they moved).
1082
+ ...programs ? { programs: [] } : {}
1083
+ });
1084
+ let copyBack = true;
983
1085
  if (!now) {
984
1086
  said.push("put the deleted copy back exactly as it was");
985
1087
  if (!opts.dryRun) await orgs.insertOne(before);
@@ -990,6 +1092,7 @@ async function rollbackMerges(dbFor, images, opts, driver) {
990
1092
  said.push("the copy is as it was");
991
1093
  } else {
992
1094
  partial = true;
1095
+ copyBack = false;
993
1096
  said.push("the copy has changed since the merge: left as it is");
994
1097
  }
995
1098
  let back = 0;
@@ -1004,6 +1107,27 @@ async function rollbackMerges(dbFor, images, opts, driver) {
1004
1107
  said.push(`${back} of ${image.refs.length} reference(s) back to the copy${moved ? ` (${moved} changed since the merge: left alone)` : ""}`);
1005
1108
  }
1006
1109
  if (moved) partial = true;
1110
+ let programsBack = false;
1111
+ if (programs) {
1112
+ const merged = [...programs.keptBefore, ...programs.moved];
1113
+ const holds = await orgs.countDocuments({ _id: image.keptId, programs: merged }) === 1;
1114
+ const asBefore = await orgs.countDocuments({ _id: image.keptId, programs: programs.keptHad ? programs.keptBefore : null }) === 1;
1115
+ if (holds) {
1116
+ programsBack = true;
1117
+ said.push(`take the copy's ${programs.moved.length} program(s) off the kept organization`);
1118
+ if (!opts.dryRun) {
1119
+ await orgs.updateOne(
1120
+ { _id: image.keptId, programs: merged },
1121
+ programs.keptHad ? { $set: { programs: programs.keptBefore } } : { $unset: { programs: "" } }
1122
+ );
1123
+ }
1124
+ } else if (!asBefore) {
1125
+ partial = true;
1126
+ said.push(
1127
+ "the kept organization's programs have changed since the merge: left as they are" + (copyBack ? " (the copy has its programs back too, so the same program ids are on both organizations until one list is corrected)" : "")
1128
+ );
1129
+ }
1130
+ }
1007
1131
  const entry = idText(image.duplicateId);
1008
1132
  const listed = image.addsLegacyEntry ? await orgs.countDocuments({ _id: image.keptId, "legacy_ids.merged_from": entry }) : 0;
1009
1133
  if (listed) {
@@ -1016,7 +1140,7 @@ async function rollbackMerges(dbFor, images, opts, driver) {
1016
1140
  } else if (!image.addsLegacyEntry) {
1017
1141
  said.push("the copy's id stays on the kept organization's legacy_ids (an earlier run put it there)");
1018
1142
  }
1019
- const anything = !now || retiredHere || back > 0 || listed > 0;
1143
+ const anything = !now || retiredHere || back > 0 || listed > 0 || programsBack;
1020
1144
  out.push({
1021
1145
  image,
1022
1146
  status: !anything ? "skip" : partial ? "partial" : "restore",
@@ -1034,6 +1158,7 @@ async function rollbackMerges(dbFor, images, opts, driver) {
1034
1158
  THREAD_SAMPLE_ID_PREFIX,
1035
1159
  YES,
1036
1160
  appDatabaseProblem,
1161
+ comparableId,
1037
1162
  comparableName,
1038
1163
  executeMerges,
1039
1164
  formatPlannedMerge,