@htilabs/platform-common-models 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +51 -0
  2. package/dist/{index-uz57Fic9.d.ts → index-BHSRMJvd.d.ts} +1 -1
  3. package/dist/{index-1pWiqEBC.d.cts → index-DF469Qgd.d.cts} +1 -1
  4. package/dist/index.cjs +51 -0
  5. package/dist/index.cjs.map +1 -1
  6. package/dist/index.d.cts +3 -3
  7. package/dist/index.d.ts +3 -3
  8. package/dist/index.js +47 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/models/index.d.cts +2 -2
  11. package/dist/models/index.d.ts +2 -2
  12. package/dist/schemas/index.d.cts +25 -25
  13. package/dist/schemas/index.d.ts +25 -25
  14. package/dist/share-rules/index.cjs +822 -0
  15. package/dist/share-rules/index.cjs.map +1 -0
  16. package/dist/share-rules/index.d.cts +804 -0
  17. package/dist/share-rules/index.d.ts +804 -0
  18. package/dist/share-rules/index.js +736 -0
  19. package/dist/share-rules/index.js.map +1 -0
  20. package/dist/sharing-ceiling/index.cjs +51 -0
  21. package/dist/sharing-ceiling/index.cjs.map +1 -1
  22. package/dist/sharing-ceiling/index.d.cts +87 -1
  23. package/dist/sharing-ceiling/index.d.ts +87 -1
  24. package/dist/sharing-ceiling/index.js +47 -0
  25. package/dist/sharing-ceiling/index.js.map +1 -1
  26. package/package.json +6 -1
  27. package/src/shareRules/__tests__/caseShareLane.test.ts +259 -0
  28. package/src/shareRules/__tests__/magicLinkAddresses.test.ts +107 -0
  29. package/src/shareRules/__tests__/platformApps.test.ts +133 -0
  30. package/src/shareRules/__tests__/releaseTerms.test.ts +358 -0
  31. package/src/shareRules/__tests__/senderRoiPosture.test.ts +284 -0
  32. package/src/shareRules/__tests__/sharingMethods.test.ts +105 -0
  33. package/src/shareRules/caseShareLane.ts +289 -0
  34. package/src/shareRules/index.ts +31 -0
  35. package/src/shareRules/magicLinkAddresses.ts +185 -0
  36. package/src/shareRules/platformApps.ts +168 -0
  37. package/src/shareRules/releaseTerms.ts +359 -0
  38. package/src/shareRules/reportPurposes.ts +50 -0
  39. package/src/shareRules/senderRoiPosture.ts +296 -0
  40. package/src/shareRules/sharingMethods.ts +204 -0
  41. package/src/sharingCeiling/__tests__/threadLift.test.ts +353 -0
  42. package/src/sharingCeiling/coverage.ts +63 -0
  43. package/src/sharingCeiling/defaults.ts +106 -0
  44. package/src/sharingCeiling/index.ts +7 -0
  45. package/dist/{cvcEntry-DAuhe0cd.d.cts → cvcEntry-DQEoFVL2.d.cts} +8 -8
  46. package/dist/{cvcEntry-DAuhe0cd.d.ts → cvcEntry-DQEoFVL2.d.ts} +8 -8
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Ported from Thread `@thread/shared` `src/__tests__/roiUddAlignment.test.ts` @ thread develop
3
+ * f021be2, adapted only for import paths (the "release sending
4
+ * methods — CVC-332 tokens" block). NOT ported: the write-schema and ROI
5
+ * update-body cases (Thread's zod schemas, which stay in Thread) and the
6
+ * CVC-334 / CVC-333 blocks (not lifted).
7
+ */
8
+ /*
9
+ * ROI Data Object alignment (UDD § 4, rulings of 2026-10-20): sending methods
10
+ * are CVC-332 tokens; the two pre-alignment spellings read through an alias;
11
+ * `physical_mail` is retired and reads as itself.
12
+ */
13
+ import { describe, expect, it } from "vitest";
14
+ import { RoiMethodKeys } from "../../generated/cvc-enums.js";
15
+ import {
16
+ LEGACY_RELEASE_METHOD_ALIASES,
17
+ RELEASE_METHOD,
18
+ RELEASE_METHOD_VALUES,
19
+ RETIRED_RELEASE_METHODS,
20
+ SHARING_METHOD,
21
+ STORED_RELEASE_METHOD_VALUES,
22
+ isReleaseMethod,
23
+ normalizeReleaseMethod,
24
+ readReleaseMethods,
25
+ releaseMethodLabel,
26
+ releaseMethodOfShareMethod,
27
+ } from "../index.js";
28
+
29
+ describe("release sending methods — CVC-332 tokens", () => {
30
+ it("the token set is the SOT's roi_method keys minus its missingness rows", () => {
31
+ expect([...RELEASE_METHOD_VALUES].sort()).toEqual(
32
+ [
33
+ "email",
34
+ "fax",
35
+ "in_person",
36
+ "secure_portal",
37
+ "thread_caseshare",
38
+ "thread_magic_link",
39
+ ].sort(),
40
+ );
41
+ for (const token of RELEASE_METHOD_VALUES) {
42
+ expect(Object.keys(RoiMethodKeys)).toContain(token);
43
+ }
44
+ });
45
+
46
+ it("reads the two old spellings through the alias", () => {
47
+ expect(normalizeReleaseMethod(SHARING_METHOD.CASE_SHARE)).toBe(
48
+ RELEASE_METHOD.CASESHARE,
49
+ );
50
+ expect(normalizeReleaseMethod(SHARING_METHOD.MAGIC_LINK)).toBe(
51
+ RELEASE_METHOD.MAGIC_LINK,
52
+ );
53
+ expect(normalizeReleaseMethod("email")).toBe("email");
54
+ expect(Object.keys(LEGACY_RELEASE_METHOD_ALIASES).sort()).toEqual(
55
+ ["case_share", "magic_link"].sort(),
56
+ );
57
+ });
58
+
59
+ it("a stored physical_mail reads as itself and is reported, never crashed on", () => {
60
+ expect(RETIRED_RELEASE_METHODS).toEqual(["physical_mail"]);
61
+ expect(normalizeReleaseMethod("physical_mail")).toBe("physical_mail");
62
+ expect(isReleaseMethod("physical_mail")).toBe(false);
63
+ const read = readReleaseMethods([
64
+ "case_share",
65
+ "thread_caseshare",
66
+ "physical_mail",
67
+ "email",
68
+ ]);
69
+ expect(read.methods).toEqual(["thread_caseshare", "email"]);
70
+ expect(read.unrecognized).toEqual(["physical_mail"]);
71
+ expect(readReleaseMethods(undefined)).toEqual({
72
+ methods: [],
73
+ unrecognized: [],
74
+ });
75
+ });
76
+
77
+ it("stored values cover the tokens, the old spellings and the retired value", () => {
78
+ for (const v of [
79
+ ...RELEASE_METHOD_VALUES,
80
+ "case_share",
81
+ "magic_link",
82
+ "physical_mail",
83
+ ]) {
84
+ expect(STORED_RELEASE_METHOD_VALUES).toContain(v);
85
+ }
86
+ });
87
+
88
+ it("a share's method reads into the same space (absent = CaseShare)", () => {
89
+ expect(releaseMethodOfShareMethod(undefined)).toBe("thread_caseshare");
90
+ expect(releaseMethodOfShareMethod("")).toBe("thread_caseshare");
91
+ expect(releaseMethodOfShareMethod("case_share")).toBe("thread_caseshare");
92
+ expect(releaseMethodOfShareMethod("magic_link")).toBe("thread_magic_link");
93
+ expect(releaseMethodOfShareMethod("email")).toBe("email");
94
+ });
95
+
96
+ it("labels keep Thread's on-screen words for either spelling", () => {
97
+ expect(releaseMethodLabel("thread_caseshare")).toBe(
98
+ releaseMethodLabel("case_share"),
99
+ );
100
+ expect(releaseMethodLabel("thread_magic_link")).toBe(
101
+ releaseMethodLabel("magic_link"),
102
+ );
103
+ expect(releaseMethodLabel("physical_mail")).not.toBe("");
104
+ });
105
+ });
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Lifted unchanged from Thread `@thread/shared` `caseShareLane.ts` (the whole
3
+ * module, L1-L279) @ thread develop f021be2; its helpers now come from
4
+ * ./platformApps.ts (lifted with it). Behaviour and copy are Thread's,
5
+ * including Thread's recorded LEADS deviation and the refusal sentences that
6
+ * name Thread ("Thread could not read how …"). An app other than Thread that
7
+ * adopts this rule inherits both; changing them is a product decision, not
8
+ * part of this lift. Pure: no mongoose, no I/O, no SOT import. Thread's
9
+ * module note follows.
10
+ *
11
+ * Where a CaseShare LANDS — the ONE rule the composer (`resolveRowWireMethod`
12
+ * and its send gate, apps/web) and every send door (the queued-share create,
13
+ * the queue drain, `POST /shares` and PAVE "Retry delivery", apps/api
14
+ * `helpers/case-share-lane.ts`) read, so the client and the server can never
15
+ * disagree about a share's lane (th-fbb8e).
16
+ *
17
+ * Thread-local — NOT a platform CVC.
18
+ *
19
+ * ## Canon
20
+ *
21
+ * A share lands in the RECEIVING TEAM's app — `team.apps_used[0]` — for every
22
+ * on-platform recipient and every purpose. When the advocate names only an
23
+ * organization, it lands with that organization's default share team
24
+ * (`resolveDefaultShareTeamMono`, the front door). With no team at all, or a
25
+ * team with no app, canon falls back to PAVE, and any landing app other than
26
+ * pave / thread / leads is clamped to PAVE: `_landApp =
27
+ * _landTeam.apps_used[0] || "pave"` (monolith L340192, the clamp L340201). The
28
+ * advocate never picks an app: the composer offers one CaseShare channel, the
29
+ * landing app is stored on the sent row and the receipt reads "Claim it in
30
+ * <app>" (monolith L340168-340207, L337131, L346163-346255 @ prototype
31
+ * c2900116).
32
+ *
33
+ * ## Thread's one recorded deviation (CATALOG ShareComposer Known deviations
34
+ * #18, packages/shared CLAUDE.md edge case 28)
35
+ *
36
+ * A team whose first app is LEADS lands as a THREAD CaseShare: Thread cannot
37
+ * deliver into LEADS (canon relays through a LEADS bridge, L340272, Thread has
38
+ * none — Nate, 2026-10-16, as on develop before th-fbb8e). So does a
39
+ * LEADS-only agency (apps hold LEADS and neither THREAD nor PAVE) with no team
40
+ * or a team with no app: mandated and legal-override reports to LEADS-only
41
+ * agencies keep working.
42
+ *
43
+ * ## The only refusals
44
+ *
45
+ * A NAMED team that is gone or inactive (choose the team again), and a setup
46
+ * that cannot be READ — the teams, the configured default share team where it
47
+ * decides, or the agency's apps where the LEADS-only reading decides
48
+ * (retryable). Rep counts never choose the lane.
49
+ */
50
+
51
+ import { PLATFORM_TOOL } from "../constants/platform-auth.js";
52
+ import {
53
+ agencyIdKey,
54
+ recipientUsesApp,
55
+ teamLandingApp,
56
+ teamLandsInPave,
57
+ teamLandsInThread,
58
+ } from "./platformApps.js";
59
+
60
+ /** The two in-app lanes Thread delivers a CaseShare on. */
61
+ export const CASE_SHARE_LANE = { THREAD: "thread", PAVE: "pave" } as const;
62
+ export type CaseShareLane =
63
+ (typeof CASE_SHARE_LANE)[keyof typeof CASE_SHARE_LANE];
64
+
65
+ /**
66
+ * The refusal keys — the `<key>: <sentence>` prefix of a drain
67
+ * `failedReason` and the `code` of a door's refusal:
68
+ * - `MISMATCH` — the claimed lane is not the receiving team's (a browser on
69
+ * an older composer, a carried method state, a forged body). Permanent.
70
+ * - `TEAM_UNAVAILABLE` — the team the share names is gone or no longer
71
+ * active. Permanent: the advocate chooses the team again.
72
+ * - `UNVERIFIED` — what decides the lane (the teams, the configured default
73
+ * share team, or the agency's apps for the LEADS-only reading) could not
74
+ * be read. Retryable.
75
+ */
76
+ export const CASE_SHARE_LANE_FAILURE = {
77
+ MISMATCH: "case_share_lane_mismatch",
78
+ TEAM_UNAVAILABLE: "case_share_team_unavailable",
79
+ UNVERIFIED: "case_share_lane_unverified",
80
+ } as const;
81
+ export type CaseShareLaneFailureCode =
82
+ (typeof CASE_SHARE_LANE_FAILURE)[keyof typeof CASE_SHARE_LANE_FAILURE];
83
+
84
+ export interface CaseShareLaneFailure {
85
+ readonly code: CaseShareLaneFailureCode;
86
+ readonly message: string;
87
+ }
88
+
89
+ /** A receiving team as the rule reads it. */
90
+ export interface CaseShareLandingTeam {
91
+ readonly id: string;
92
+ readonly name: string;
93
+ /** Declared apps (strict uppercase PLATFORM_TOOL codes); the FIRST lands. */
94
+ readonly apps?: readonly unknown[] | null;
95
+ /** The account's declared default team (Admin Hub "Default team"). */
96
+ readonly defaultTeam?: boolean;
97
+ }
98
+
99
+ /** The answer of the rule: a lane, or why there is none. */
100
+ export type CaseShareLanding =
101
+ | {
102
+ readonly ok: true;
103
+ readonly lane: CaseShareLane;
104
+ /** The receiving team, or null when none resolved. */
105
+ readonly team: CaseShareLandingTeam | null;
106
+ }
107
+ | ({ readonly ok: false } & CaseShareLaneFailure);
108
+
109
+ /** The receiving team as resolved: a team, none, a stale named id, unread. */
110
+ export type CaseShareReceivingTeam =
111
+ | CaseShareLandingTeam
112
+ | null
113
+ | "stale"
114
+ | "unverified";
115
+
116
+ /** The recipient at the START of a sentence. */
117
+ function recipientSubject(name: string | undefined): string {
118
+ return name !== undefined && name.trim().length > 0 ? name : "The recipient";
119
+ }
120
+
121
+ /** The recipient MID-sentence. */
122
+ function recipientObject(name: string | undefined): string {
123
+ return name !== undefined && name.trim().length > 0 ? name : "the recipient";
124
+ }
125
+
126
+ function teamSubject(team: CaseShareLandingTeam): string {
127
+ return team.name.trim().length > 0
128
+ ? `The team "${team.name}"`
129
+ : "The receiving team";
130
+ }
131
+
132
+ /** The refusal for a named team that is gone or no longer active. */
133
+ export function caseShareStaleTeamFailure(
134
+ name: string | undefined,
135
+ ): CaseShareLaneFailure {
136
+ return {
137
+ code: CASE_SHARE_LANE_FAILURE.TEAM_UNAVAILABLE,
138
+ message: `The team you chose at ${recipientObject(name)} is no longer available — choose the team again.`,
139
+ };
140
+ }
141
+
142
+ /** The refusal when what decides the lane cannot be read. */
143
+ export function caseShareLaneUnverified(
144
+ name: string | undefined,
145
+ ): CaseShareLaneFailure {
146
+ return {
147
+ code: CASE_SHARE_LANE_FAILURE.UNVERIFIED,
148
+ message: `Thread could not read how ${recipientObject(name)} receives CaseShares, so the share was not sent. Try again in a few minutes.`,
149
+ };
150
+ }
151
+
152
+ /** Whether the agency is on LEADS and on neither Thread nor PAVE. */
153
+ function leadsOnly(agencyApps: unknown): boolean {
154
+ return (
155
+ recipientUsesApp(agencyApps, PLATFORM_TOOL.LEADS) &&
156
+ !recipientUsesApp(agencyApps, PLATFORM_TOOL.THREAD) &&
157
+ !recipientUsesApp(agencyApps, PLATFORM_TOOL.PAVE)
158
+ );
159
+ }
160
+
161
+ /**
162
+ * Whether the landing depends on the AGENCY's apps: no team resolved, or a
163
+ * team declaring no app — the only cases the LEADS-only reading decides.
164
+ * A door that cannot read the apps answers "unverified" only then.
165
+ */
166
+ export function caseShareLandingNeedsAgencyApps(
167
+ team: CaseShareReceivingTeam,
168
+ ): boolean {
169
+ if (team === "stale" || team === "unverified") return false;
170
+ return team === null || teamLandingApp(team.apps ?? undefined) === undefined;
171
+ }
172
+
173
+ /**
174
+ * The DEFAULT SHARE TEAM when a share names no team — canon's
175
+ * single-organization ladder (`resolveDefaultShareTeamMono`, monolith
176
+ * L346163-346255 @ c2900116): the admin-configured team, else the one
177
+ * declared default team (more than one declared is ambiguous and skipped),
178
+ * else the only team, else — when `inApp` is given — the only / first team in
179
+ * that app, else the first team by id. `null` only when there are no teams.
180
+ * The landing rule reads it with no app (canon passes `app = null` at
181
+ * landing); the intake-team resolver with the PAVE app.
182
+ */
183
+ export function pickDefaultShareTeam<T extends CaseShareLandingTeam>(
184
+ teams: readonly T[],
185
+ configuredDefaultShareTeamId: string | null,
186
+ inApp?: (team: T) => boolean,
187
+ ): { readonly team: T; readonly via: DefaultShareTeamVia } | null {
188
+ if (teams.length === 0) return null;
189
+ if (configuredDefaultShareTeamId !== null) {
190
+ const configured = teams.find(
191
+ (t) => agencyIdKey(t.id) === agencyIdKey(configuredDefaultShareTeamId),
192
+ );
193
+ if (configured) return { team: configured, via: "configured" };
194
+ }
195
+ const declared = teams.filter((t) => t.defaultTeam === true);
196
+ if (declared.length === 1) {
197
+ return { team: declared[0]!, via: "account_declared" };
198
+ }
199
+ if (teams.length === 1) return { team: teams[0]!, via: "auto_single" };
200
+ const app = inApp ? teams.filter(inApp) : [];
201
+ if (app.length === 1) return { team: app[0]!, via: "auto_single_in_app" };
202
+ const pool = [...(app.length > 0 ? app : teams)].sort((a, b) =>
203
+ a.id.localeCompare(b.id),
204
+ );
205
+ return {
206
+ team: pool[0]!,
207
+ via: app.length > 0 ? "first_in_app" : "first_team",
208
+ };
209
+ }
210
+
211
+ export type DefaultShareTeamVia =
212
+ | "configured"
213
+ | "account_declared"
214
+ | "auto_single"
215
+ | "auto_single_in_app"
216
+ | "first_in_app"
217
+ | "first_team";
218
+
219
+ /**
220
+ * The lane a CaseShare lands on with its receiving team (the one named, or the
221
+ * organization's default share team), or why there is none:
222
+ * - the team's first app THREAD → Thread; PAVE → PAVE; LEADS → Thread (the
223
+ * recorded deviation);
224
+ * - no team, or a team with no app → PAVE (canon's fallback) — except a
225
+ * LEADS-only agency → Thread (the deviation), which needs the agency's
226
+ * apps: when they could not be read (`agencyAppsUnread`) the answer is
227
+ * unverified;
228
+ * - any other first app → PAVE (canon's clamp);
229
+ * - a stale named team, or an unreadable directory → refused.
230
+ */
231
+ export function caseShareLandingLane(recipient: {
232
+ /** The recipient agency's display name (for the message). */
233
+ readonly name?: string;
234
+ /** The recipient agency's directory `apps` (the LEADS-only reading). */
235
+ readonly agencyApps?: unknown;
236
+ /** The agency's apps could not be read (failed or ambiguous). */
237
+ readonly agencyAppsUnread?: boolean;
238
+ readonly team: CaseShareReceivingTeam;
239
+ }): CaseShareLanding {
240
+ const { team, name } = recipient;
241
+ if (team === "unverified") {
242
+ return { ok: false, ...caseShareLaneUnverified(name) };
243
+ }
244
+ if (team === "stale") {
245
+ return { ok: false, ...caseShareStaleTeamFailure(name) };
246
+ }
247
+ const apps = team?.apps ?? undefined;
248
+ if (teamLandsInThread(apps)) {
249
+ return { ok: true, lane: CASE_SHARE_LANE.THREAD, team };
250
+ }
251
+ if (teamLandsInPave(apps)) {
252
+ return { ok: true, lane: CASE_SHARE_LANE.PAVE, team };
253
+ }
254
+ // Recorded deviation: Thread cannot deliver into LEADS.
255
+ if (teamLandingApp(apps) === PLATFORM_TOOL.LEADS) {
256
+ return { ok: true, lane: CASE_SHARE_LANE.THREAD, team };
257
+ }
258
+ if (caseShareLandingNeedsAgencyApps(team)) {
259
+ if (recipient.agencyAppsUnread === true) {
260
+ return { ok: false, ...caseShareLaneUnverified(name) };
261
+ }
262
+ if (leadsOnly(recipient.agencyApps)) {
263
+ return { ok: true, lane: CASE_SHARE_LANE.THREAD, team };
264
+ }
265
+ }
266
+ // Canon's fallback (no team / no app) and clamp (any other app): PAVE.
267
+ return { ok: true, lane: CASE_SHARE_LANE.PAVE, team };
268
+ }
269
+
270
+ /** The refusal for a CLAIMED lane that is not the landing one. */
271
+ export function caseShareLaneMismatch(
272
+ recipient: {
273
+ readonly name?: string;
274
+ readonly team: CaseShareLandingTeam | null;
275
+ },
276
+ landing: CaseShareLane,
277
+ claimed: CaseShareLane,
278
+ ): CaseShareLaneFailure | null {
279
+ if (landing === claimed) return null;
280
+ const app = landing === CASE_SHARE_LANE.THREAD ? "Thread" : "PAVE";
281
+ const who =
282
+ recipient.team !== null
283
+ ? `${teamSubject(recipient.team)} at ${recipientObject(recipient.name)}`
284
+ : recipientSubject(recipient.name);
285
+ return {
286
+ code: CASE_SHARE_LANE_FAILURE.MISMATCH,
287
+ message: `${who} receives CaseShares in ${app}, so this share was not sent as it was composed — compose it again.`,
288
+ };
289
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @htilabs/platform-common-models/share-rules
3
+ *
4
+ * The app-independent SHARE RULES the Next Steps share window and every send
5
+ * door read, lifted from Thread `@thread/shared` (thread develop f021be2) so
6
+ * Thread and PAVE — composers and servers — run one copy. A lift: behaviour
7
+ * and copy are Thread's, unchanged.
8
+ *
9
+ * - who a magic link reaches and is addressed to (`derivesOffPlatformRecipient`,
10
+ * `magicLinkAddresses`, `magicLinkToText`, …; ./magicLinkAddresses.ts);
11
+ * - the release's terms at the share boundary — R19 method, R21 end date
12
+ * (`releaseMethodRefusal`, `shareExpiryUnderRelease`, …; ./releaseTerms.ts);
13
+ * - where a CaseShare lands (`caseShareLandingLane`, `pickDefaultShareTeam`, …;
14
+ * ./caseShareLane.ts);
15
+ * - the sending account's release posture (`resolveSenderRoiPosture`,
16
+ * `senderRoiPostureForTeam`, …; ./senderRoiPosture.ts);
17
+ * - and what they stand on: the app-membership readings (./platformApps.ts),
18
+ * the share / release method vocabularies (./sharingMethods.ts) and the
19
+ * report purposes (./reportPurposes.ts).
20
+ *
21
+ * Pure TypeScript: no mongoose, no I/O, no React, no SOT import. Not
22
+ * re-exported from the package root.
23
+ */
24
+
25
+ export * from "./platformApps.js";
26
+ export * from "./sharingMethods.js";
27
+ export * from "./reportPurposes.js";
28
+ export * from "./magicLinkAddresses.js";
29
+ export * from "./releaseTerms.js";
30
+ export * from "./caseShareLane.js";
31
+ export * from "./senderRoiPosture.js";
@@ -0,0 +1,185 @@
1
+ /**
2
+ * The Magic Link partner rules, declared ONCE for every app and server.
3
+ *
4
+ * Lifted unchanged from Thread `@thread/shared` `magicLinkPartner.ts`
5
+ * L19-L172 (the whole module) @ thread develop f021be2; the one change is
6
+ * that `recipientPlatformFromApps` now comes from ./platformApps.ts (lifted
7
+ * with it). Thread's module note follows.
8
+ *
9
+ * th-9aynm — the two rules both apps of the share flow need about a Magic Link
10
+ * partner, declared ONCE (the API directory and the web composer / secure-link
11
+ * section read the same functions).
12
+ *
13
+ * 1. {@link derivesOffPlatformRecipient} — whether a recipient is reached by
14
+ * a secure link: not the caller's own agency, and the A7 derivation over
15
+ * its apps (`recipientPlatformFromApps`, the one rule every send door and
16
+ * the drain run) finds no casework app. A recipient with no `apps` at all
17
+ * (an Organization, an ROI-external) derives the same way, as the create
18
+ * door reads it.
19
+ * 2. {@link magicLinkAddresses} — the ONE order / de-dup rule for the
20
+ * addresses a magic link is emailed to (th-333y1; th-9aynm's single
21
+ * `pickContactEmail` seed is retired).
22
+ *
23
+ * PAVE twin to retire: pave-2.0 `packages/domain/src/magicLinkAddresses.ts`
24
+ * (same cap of 25, same canon sentence; see the Thread re-point note for the
25
+ * differences).
26
+ *
27
+ * Pure: no mongoose, no I/O, no SOT import.
28
+ */
29
+ import { recipientPlatformFromApps } from "./platformApps.js";
30
+
31
+ /** Whether this recipient is a Magic Link partner (see the module note). */
32
+ export function derivesOffPlatformRecipient(recipient: {
33
+ readonly isSelf?: boolean | undefined;
34
+ readonly apps?: readonly unknown[] | null | undefined;
35
+ }): boolean {
36
+ return (
37
+ recipient.isSelf !== true &&
38
+ !recipientPlatformFromApps(recipient.apps).recipientOnPlatform
39
+ );
40
+ }
41
+
42
+ /**
43
+ * th-333y1 — one of a partner's Referrals (magic link) contacts, as the apps
44
+ * carry it: the Point of contact's display name (null when it has none) and
45
+ * the PREFERRED email the magic link is addressed to.
46
+ *
47
+ * Read from platform-db `pointsofcontact` through the platform-common reader
48
+ * (`listReferralContactsForPartner`, `@htilabs/platform-common-models/points-of-contact`):
49
+ * every ACTIVE, CONFIRMED, non-confidential contact on the partner tagged
50
+ * `REFERRALS_MAGIC_LINK`, one per distinct email (Crysta 2026-08-23 / POC-
51
+ * UNIFIED-CONTACT-MODEL R1, restated in the prototype kickoff
52
+ * `KICKOFF_SERVICE_LISTING_AND_PARTNER_CONTACT_BUILD_2026-10-14.md` @ c6380f73
53
+ * L13, D2: "The magic link is addressed to every `REFERRALS_MAGIC_LINK`
54
+ * holder on the recipient"). Another advocate's pending contact (an in-app add
55
+ * HTI Labs has not confirmed) is never read; the asking advocate's own are,
56
+ * marked `pending`.
57
+ */
58
+ export interface MagicLinkContact {
59
+ readonly name: string | null;
60
+ readonly email: string;
61
+ /**
62
+ * The ASKING advocate's own in-app add, still waiting for HTI Labs to
63
+ * confirm it (Nate 2026-10-15; the reader's `includeOwnPendingFor`). Shown
64
+ * "pending HTI review". Nobody else's pending add is ever read.
65
+ */
66
+ readonly pending?: true;
67
+ }
68
+
69
+ /** The most addresses one magic-link share is emailed to (wire bound). */
70
+ export const MAGIC_LINK_MAX_ADDRESSES = 25;
71
+
72
+ /**
73
+ * th-333y1 — the addresses ONE magic-link share is emailed to, in order:
74
+ * trimmed, empty entries dropped, de-duplicated case-insensitively (the first
75
+ * spelling wins), capped at {@link MAGIC_LINK_MAX_ADDRESSES}. The composer
76
+ * (what the review card prints), the create door and the drain (what is
77
+ * sent) all read this one rule.
78
+ */
79
+ export function magicLinkAddresses(
80
+ ...lists: ReadonlyArray<ReadonlyArray<string | null | undefined>>
81
+ ): string[] {
82
+ const out: string[] = [];
83
+ const seen = new Set<string>();
84
+ for (const list of lists) {
85
+ for (const raw of list) {
86
+ const v = (raw ?? "").trim();
87
+ if (v.length === 0) continue;
88
+ const key = v.toLowerCase();
89
+ if (seen.has(key)) continue;
90
+ seen.add(key);
91
+ out.push(v);
92
+ if (out.length >= MAGIC_LINK_MAX_ADDRESSES) return out;
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /**
99
+ * th-333y1 — how many distinct addresses {@link magicLinkAddresses} leaves
100
+ * out at the cap (0 when none). Callers log the count / show "+N not
101
+ * included" — never the addresses.
102
+ */
103
+ export function magicLinkAddressOverflow(
104
+ ...lists: ReadonlyArray<ReadonlyArray<string | null | undefined>>
105
+ ): number {
106
+ const seen = new Set<string>();
107
+ for (const list of lists) {
108
+ for (const raw of list) {
109
+ const v = (raw ?? "").trim().toLowerCase();
110
+ if (v.length > 0) seen.add(v);
111
+ }
112
+ }
113
+ return Math.max(0, seen.size - MAGIC_LINK_MAX_ADDRESSES);
114
+ }
115
+
116
+ /**
117
+ * pl-iza — the ONE sentence every sender-facing surface uses for who a magic
118
+ * link goes to: the visible addresses, then how many CONFIDENTIAL holders
119
+ * also receive it — never their address or name (canon CVC-338
120
+ * `REFERRALS_MAGIC_LINK`: "A confidential holder still receives it; the
121
+ * sender never sees the address."; ruling Nate 2026-10-15).
122
+ *
123
+ * Verbatim port of the prototype's `window.HTI_MAGIC_LINK_TO_TEXT`
124
+ * (`HTI-LEADS-PAVE-Thread-prototype.html` @ 184893b6 L164656-L164663):
125
+ * "a@x, b@y + 1 confidential recipient" · "1 confidential recipient" ·
126
+ * "2 confidential recipients" · "" (nobody).
127
+ */
128
+ export function magicLinkToText(
129
+ to: ReadonlyArray<string> | null | undefined,
130
+ confidentialCount: number | null | undefined,
131
+ ): string {
132
+ const v = (to ?? []).join(", ");
133
+ const n = confidentialCount ?? 0;
134
+ const c = n ? n + " confidential recipient" + (n === 1 ? "" : "s") : "";
135
+ return v && c ? v + " + " + c : v || c;
136
+ }
137
+
138
+ /**
139
+ * pl-iza — how many confidential holders the cap leaves out: the send emails
140
+ * the visible addresses first, then the confidential holders up to
141
+ * {@link MAGIC_LINK_MAX_ADDRESSES} in all (`confidential.deliver(sendOne,
142
+ * { capacity: 25 - visible })`). A count derived from two counts only, so it
143
+ * discloses nothing a sender does not already see. Folded into every
144
+ * "(+N not included)" note.
145
+ */
146
+ export function magicLinkConfidentialOverflow(
147
+ visibleCount: number,
148
+ confidentialCount: number | null | undefined,
149
+ ): number {
150
+ const n = confidentialCount ?? 0;
151
+ return Math.max(0, visibleCount + n - MAGIC_LINK_MAX_ADDRESSES);
152
+ }
153
+
154
+ /** The slice of a queued `poc` the magic-link address rules read. */
155
+ export interface MagicLinkPocAddresses {
156
+ readonly email?: string | null | undefined;
157
+ readonly contactEmails?: readonly string[] | null | undefined;
158
+ readonly addedEmails?: readonly string[] | null | undefined;
159
+ readonly confidentialCount?: number | null | undefined;
160
+ }
161
+
162
+ /** Whether a queued `poc` names a visible address: typed, reviewed, or added. */
163
+ export function magicLinkPocHasVisibleAddress(
164
+ poc: MagicLinkPocAddresses | null | undefined,
165
+ ): boolean {
166
+ if (!poc) return false;
167
+ return (
168
+ (poc.email ?? "").trim().length > 0 ||
169
+ (poc.contactEmails ?? []).length > 0 ||
170
+ (poc.addedEmails ?? []).length > 0
171
+ );
172
+ }
173
+
174
+ /**
175
+ * pl-iza — a magic-link `poc` whose ONLY address is the confidential-holder
176
+ * count (canon D(ii): a confidential holder is a holder). The create door's
177
+ * schema accepts it; the handler then requires the server to see a holder.
178
+ */
179
+ export function magicLinkConfidentialOnly(
180
+ poc: MagicLinkPocAddresses | null | undefined,
181
+ ): boolean {
182
+ return (
183
+ !magicLinkPocHasVisibleAddress(poc) && (poc?.confidentialCount ?? 0) > 0
184
+ );
185
+ }