@htilabs/platform-common-models 0.86.0 → 0.87.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +20 -0
  2. package/dist/{index-XWSYon40.d.cts → index-Bj-s0nZy.d.cts} +1 -1
  3. package/dist/{index-Bh1zO_Vu.d.ts → index-DvAypMJV.d.ts} +1 -1
  4. package/dist/index.d.cts +2 -2
  5. package/dist/index.d.ts +2 -2
  6. package/dist/models/index.d.cts +2 -2
  7. package/dist/models/index.d.ts +2 -2
  8. package/dist/org-merge/index.cjs.map +1 -1
  9. package/dist/org-merge/index.js.map +1 -1
  10. package/dist/points-of-contact/index.cjs +222 -23
  11. package/dist/points-of-contact/index.cjs.map +1 -1
  12. package/dist/points-of-contact/index.d.cts +50 -5
  13. package/dist/points-of-contact/index.d.ts +50 -5
  14. package/dist/points-of-contact/index.js +219 -22
  15. package/dist/points-of-contact/index.js.map +1 -1
  16. package/dist/reader-BmhzOis-.d.ts +273 -0
  17. package/dist/reader-DfQtdw6n.d.cts +273 -0
  18. package/dist/schemas/index.d.cts +25 -25
  19. package/dist/schemas/index.d.ts +25 -25
  20. package/dist/seat-logs/index.cjs +815 -0
  21. package/dist/seat-logs/index.cjs.map +1 -0
  22. package/dist/seat-logs/index.d.cts +274 -0
  23. package/dist/seat-logs/index.d.ts +274 -0
  24. package/dist/seat-logs/index.js +742 -0
  25. package/dist/seat-logs/index.js.map +1 -0
  26. package/package.json +6 -1
  27. package/src/pointsOfContact/__tests__/seatContactLog.test.ts +170 -0
  28. package/src/pointsOfContact/readRules.ts +22 -4
  29. package/src/pointsOfContact/reader.ts +95 -1
  30. package/src/pointsOfContact/schemas.ts +4 -3
  31. package/src/seatLogs/__tests__/seatLogs.review.test.ts +222 -0
  32. package/src/seatLogs/__tests__/seatLogs.test.ts +335 -0
  33. package/src/seatLogs/index.ts +15 -0
  34. package/src/seatLogs/log.ts +700 -0
  35. package/src/seatLogs/personId.ts +100 -0
  36. package/src/seatLogs/personSlugWordlists.ts +40 -0
  37. package/src/seatLogs/reader.ts +143 -0
  38. package/src/seatLogs/schemas.ts +118 -0
  39. package/dist/{cvcEntry-D787utvP.d.cts → cvcEntry-BLeRivoF.d.cts} +8 -8
  40. package/dist/{cvcEntry-D787utvP.d.ts → cvcEntry-BLeRivoF.d.ts} +8 -8
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@htilabs/platform-common-models",
3
- "version": "0.86.0",
3
+ "version": "0.87.1",
4
4
  "description": "Shared constants, types, and models for HTI Labs applications",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -116,6 +116,11 @@
116
116
  "types": "./dist/grant-registry/index.d.ts",
117
117
  "import": "./dist/grant-registry/index.js",
118
118
  "require": "./dist/grant-registry/index.cjs"
119
+ },
120
+ "./seat-logs": {
121
+ "types": "./dist/seat-logs/index.d.ts",
122
+ "import": "./dist/seat-logs/index.js",
123
+ "require": "./dist/seat-logs/index.cjs"
119
124
  }
120
125
  },
121
126
  "files": [
@@ -0,0 +1,170 @@
1
+ /**
2
+ * pl-9h4: a seat-linked point of contact reads the seat's contact log
3
+ * (`seat_contacts`) when the seat resolver is wrapped in `withSeatContactLogs`.
4
+ */
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ import { addSeatContact, setPreferredSeatContact } from "../../seatLogs/log.js";
8
+ import type { SeatContactEntry, SeatLogSubject } from "../../seatLogs/schemas.js";
9
+ import {
10
+ pocIdentityKey,
11
+ seatContactListsFromLog,
12
+ toNetworkView,
13
+ toStewardView,
14
+ withSeatContactLogs,
15
+ type PointOfContactDoc,
16
+ type SeatReach,
17
+ type SeatResolver,
18
+ } from "../index.js";
19
+
20
+ const SEAT: SeatLogSubject = { subject_type: "user", subject_id: "u-seat" };
21
+ let n = 0;
22
+ const ctx = { actor: "u-admin", at: "2026-11-16T15:00:00.000Z", mintId: () => `ci-${++n}` };
23
+
24
+ function log(): SeatContactEntry[] {
25
+ let es: SeatContactEntry[] = [];
26
+ es = addSeatContact(es, SEAT, { contact_type: "email", value: "Old@A.org" }, ctx).entries;
27
+ es = addSeatContact(es, SEAT, { contact_type: "email", value: "New@A.org" }, ctx).entries;
28
+ es = addSeatContact(es, SEAT, { contact_type: "phone", value: "4026773902" }, ctx).entries;
29
+ es = addSeatContact(es, SEAT, { contact_type: "phone", value: "4025550100" }, ctx).entries;
30
+ const newer = es.find((e) => e.value === "New@A.org")!;
31
+ return setPreferredSeatContact(es, SEAT, newer.entry_id, ctx).entries;
32
+ }
33
+
34
+ function seatRow(): PointOfContactDoc {
35
+ const d: PointOfContactDoc = {
36
+ id: "poc-seat", subject_type: "agency", subject_id: "agency-a", agency_id: "agency-a",
37
+ org_id: "org-a", user_id: "u-seat", person_id: null, display_name: null, emails: [], phones: [],
38
+ purposes: [], urgent_methods: [], is_primary: false, is_confidential: false, active: true,
39
+ notes: null, status: "confirmed", origin: "admin_hub", added_in_app: "platform",
40
+ identity_key: "x", confirmed_by: "steward", confirmed_at: "2026-10-14T00:00:00.000Z",
41
+ deactivated_by: null, deactivated_at: null, version: 1, createdBy: "u1",
42
+ createdAt: "2026-10-14T00:00:00.000Z", updatedBy: "u1", updatedAt: "2026-10-14T00:00:00.000Z",
43
+ };
44
+ return { ...d, identity_key: pocIdentityKey(d) };
45
+ }
46
+
47
+ const flat: SeatResolver = async (ids) => new Map<string, SeatReach>(
48
+ ids.map((id) => [id, { email: "flat@a.org", phone: "555-0000", name: "Sam Seat" }]),
49
+ );
50
+
51
+ function dbWith(rows: SeatContactEntry[]) {
52
+ const asked: string[] = [];
53
+ return {
54
+ asked,
55
+ db: {
56
+ collection: (name: string) => {
57
+ asked.push(name);
58
+ return {
59
+ find: (f: Record<string, unknown>) => ({
60
+ toArray: async () => rows.filter((r) =>
61
+ r.subject_type === f.subject_type &&
62
+ ((f.subject_id as { $in: string[] }).$in).includes(r.subject_id)),
63
+ }),
64
+ };
65
+ },
66
+ },
67
+ };
68
+ }
69
+
70
+ describe("seat contact log in points of contact (pl-9h4)", () => {
71
+ it("lists every live email and phone with the log's preferred mark", () => {
72
+ expect(seatContactListsFromLog(log())).toEqual({
73
+ emails: [{ value: "old@a.org", is_preferred: false }, { value: "new@a.org", is_preferred: true }],
74
+ phones: [
75
+ { value: "(402) 677-3902", is_preferred: true },
76
+ { value: "(402) 555-0100", is_preferred: false },
77
+ ],
78
+ });
79
+ expect(seatContactListsFromLog([])).toBeNull();
80
+ });
81
+
82
+ it("a seat-linked contact reads the log; a seat with no log keeps users' email and phone", async () => {
83
+ const { db, asked } = dbWith(log());
84
+ const resolve = withSeatContactLogs(db, flat);
85
+ const seats = await resolve(["u-seat", "u-other"]);
86
+ expect(asked).toEqual(["seat_contacts"]);
87
+
88
+ const v = toNetworkView(seatRow(), seats.get("u-seat"))!;
89
+ expect(v.email).toBe("new@a.org");
90
+ expect(v.emails.map((e) => e.value)).toEqual(["old@a.org", "new@a.org"]);
91
+ expect(v.phone).toBe("(402) 677-3902");
92
+ expect(v.phones).toHaveLength(2);
93
+ expect(v.display_name).toBe("Sam Seat");
94
+
95
+ const other = toNetworkView(seatRow(), seats.get("u-other"))!;
96
+ expect([other.emails, other.phones]).toEqual([
97
+ [{ value: "flat@a.org", is_preferred: true }],
98
+ [{ value: "555-0000", is_preferred: true }],
99
+ ]);
100
+ });
101
+
102
+ it("the steward view's seat is a copy, never the resolver's arrays", async () => {
103
+ const { db } = dbWith(log());
104
+ const seats = await withSeatContactLogs(db, flat)(["u-seat"]);
105
+ const seat = seats.get("u-seat")!;
106
+ const s = toStewardView(seatRow(), seat);
107
+ expect(s.seat?.emails).toEqual(seat.emails);
108
+ expect(s.seat?.emails).not.toBe(seat.emails);
109
+ expect(s.email).toBe("new@a.org");
110
+ });
111
+ });
112
+
113
+ describe("withSeatContactLogs: pre-review fixes (B1, B2, S3, S5)", () => {
114
+ const phoneOnly = () =>
115
+ addSeatContact([], SEAT, { contact_type: "phone", value: "4025550100" }, ctx).entries;
116
+ const emailOnly = () =>
117
+ addSeatContact([], SEAT, { contact_type: "email", value: "Log@A.org" }, ctx).entries;
118
+
119
+ it("B1: a seat the base resolver left out (ended, unknown) stays out", async () => {
120
+ const { db } = dbWith(phoneOnly());
121
+ const ended: SeatResolver = async () => new Map();
122
+ const seats = await withSeatContactLogs(db, ended)(["u-seat"]);
123
+ expect(seats.has("u-seat")).toBe(false);
124
+ const v = toNetworkView(seatRow(), seats.get("u-seat"))!;
125
+ expect([v.emails, v.phones]).toEqual([[], []]);
126
+ });
127
+
128
+ it("B2: a phone-only log keeps the flat email; an email-only log keeps the flat phone", async () => {
129
+ const p = (await withSeatContactLogs(dbWith(phoneOnly()).db, flat)(["u-seat"])).get("u-seat")!;
130
+ const pv = toNetworkView(seatRow(), p)!;
131
+ expect([pv.email, pv.phone]).toEqual(["flat@a.org", "(402) 555-0100"]);
132
+ const e = (await withSeatContactLogs(dbWith(emailOnly()).db, flat)(["u-seat"])).get("u-seat")!;
133
+ const ev = toNetworkView(seatRow(), e)!;
134
+ expect([ev.email, ev.phone]).toEqual(["log@a.org", "555-0000"]);
135
+ });
136
+
137
+ it("S3: a seat id asked upper-case reads the log stored lower-case", async () => {
138
+ const hex = "0123456789abcdef01234567";
139
+ const subject = { subject_type: "user" as const, subject_id: hex };
140
+ const es = addSeatContact([], subject, { contact_type: "email", value: "hex@a.org" }, ctx).entries;
141
+ const seats = await withSeatContactLogs(dbWithForms(es).db, flat)([hex.toUpperCase()]);
142
+ expect(seats.get(hex.toUpperCase())?.email).toBe("hex@a.org");
143
+ });
144
+
145
+ it("S5: a malformed row is skipped for its seat (per-type fallback), never thrown", async () => {
146
+ const bad = { ...phoneOnly()[0], entry_id: "ci-bad", notes: undefined } as unknown as SeatContactEntry;
147
+ const good = emailOnly();
148
+ const skipped: string[] = [];
149
+ const seats = await withSeatContactLogs(dbWith([...good, bad]).db, flat, {
150
+ onInvalidRow: (e) => skipped.push(e.entryId ?? ""),
151
+ })(["u-seat"]);
152
+ const v = toNetworkView(seatRow(), seats.get("u-seat"))!;
153
+ expect([v.email, v.phone]).toEqual(["log@a.org", "555-0000"]);
154
+ expect(skipped).toEqual(["ci-bad"]);
155
+ });
156
+ });
157
+
158
+ /** Like `dbWith`, but matches `subject_id` exactly as Mongo would (no case folding). */
159
+ function dbWithForms(rows: SeatContactEntry[]) {
160
+ return {
161
+ db: {
162
+ collection: () => ({
163
+ find: (f: Record<string, unknown>) => ({
164
+ toArray: async () => rows.filter((r) =>
165
+ ((f.subject_id as { $in: string[] }).$in).includes(r.subject_id)),
166
+ }),
167
+ }),
168
+ },
169
+ };
170
+ }
@@ -62,6 +62,14 @@ export interface SeatReach {
62
62
  email: string | null;
63
63
  phone: string | null;
64
64
  name: string | null;
65
+ /**
66
+ * The seat's live emails from its contact log (pl-9h4), preferred marked.
67
+ * When present, a seat-linked contact reads these instead of `email`.
68
+ * Absent = the seat has no contact log yet: `email` is read as one entry.
69
+ */
70
+ emails?: PocContactEntry[];
71
+ /** The seat's live phones from its contact log; the same rule against `phone`. */
72
+ phones?: PocContactEntry[];
65
73
  }
66
74
 
67
75
  /** The steward view: everything but the identity key, seat resolved. */
@@ -89,7 +97,7 @@ export interface PointOfContactNetworkView {
89
97
  agency_id: string | null;
90
98
  org_id: string | null;
91
99
  display_name: string | null;
92
- /** The row's emails, or the seat's email as one preferred entry when the contact is seat-linked and a seat resolver was given. */
100
+ /** The row's emails, or for a seat-linked contact (a seat resolver given) the seat's contact-log emails, else its email as one preferred entry. */
93
101
  emails: PocContactEntry[];
94
102
  /** The row's phones, or the seat's phone as one preferred entry (the same rules as `emails`). */
95
103
  phones: PocContactEntry[];
@@ -140,6 +148,7 @@ const copyEntries = (list: readonly PocContactEntry[]): PocContactEntry[] =>
140
148
 
141
149
  /**
142
150
  * Where the contact is reached: the row's own lists, or for a seat-linked row
151
+ * the seat's contact-log lists when the resolver carried them (pl-9h4), else
143
152
  * the seat's email (trimmed, lowercased) and phone as one preferred entry
144
153
  * each. Always fresh arrays.
145
154
  */
@@ -151,11 +160,20 @@ function reachOf(
151
160
  const one = (v: string | null | undefined): PocContactEntry[] =>
152
161
  v ? [{ value: v, is_preferred: true }] : [];
153
162
  return {
154
- emails: one(seat?.email?.trim().toLowerCase()),
155
- phones: one(seat?.phone?.trim()),
163
+ emails: seat?.emails ? copyEntries(seat.emails) : one(seat?.email?.trim().toLowerCase()),
164
+ phones: seat?.phones ? copyEntries(seat.phones) : one(seat?.phone?.trim()),
156
165
  };
157
166
  }
158
167
 
168
+ /** A copy of the seat's reach (its lists too), so a view never shares the resolver's arrays. */
169
+ function copySeat(seat: SeatReach | null | undefined): SeatReach | null {
170
+ if (!seat) return null;
171
+ const out: SeatReach = { ...seat };
172
+ if (seat.emails) out.emails = copyEntries(seat.emails);
173
+ if (seat.phones) out.phones = copyEntries(seat.phones);
174
+ return out;
175
+ }
176
+
159
177
  const preferredValue = (list: readonly PocContactEntry[]): string | null =>
160
178
  preferredContactEntry(list)?.value ?? null;
161
179
 
@@ -173,7 +191,7 @@ export function toStewardView(
173
191
  purposes: [...d.purposes],
174
192
  urgent_methods: [...d.urgent_methods],
175
193
  purpose_labels: d.purposes.map(contactPurposeLabel),
176
- seat: d.user_id ? (seat ?? null) : null,
194
+ seat: d.user_id ? copySeat(seat) : null,
177
195
  email: preferredValue(reach.emails),
178
196
  phone: preferredValue(reach.phones),
179
197
  };
@@ -16,6 +16,9 @@
16
16
  * ObjectId filter for `users._id`; the reader passes a {@link SeatResolver}
17
17
  * that reads its own `users`. The partner rollup REQUIRES one, so a reader
18
18
  * cannot silently drop seat-linked referral contacts.
19
+ * Wrap it in {@link withSeatContactLogs} to read each seat's contact log
20
+ * (every email and phone, with the log's preferred mark) instead of the one
21
+ * email and phone on `users` (pl-9h4).
19
22
  *
20
23
  * ## Confidential Referrals (magic link) holders (pl-iza, 0.32.0)
21
24
  *
@@ -31,7 +34,21 @@
31
34
  * row that may be confidential is counted, never thrown.
32
35
  */
33
36
 
34
- import { POINTS_OF_CONTACT_COLLECTION, type PointOfContactDoc } from "./schemas.js";
37
+ import {
38
+ liveSeatContacts,
39
+ preferredSeatContact,
40
+ } from "../seatLogs/log.js";
41
+ import {
42
+ readSeatContactLogs,
43
+ type SeatLogDbLike,
44
+ type SeatLogShapeError,
45
+ } from "../seatLogs/reader.js";
46
+ import type { SeatContactEntry } from "../seatLogs/schemas.js";
47
+ import {
48
+ POINTS_OF_CONTACT_COLLECTION,
49
+ type PocContactEntry,
50
+ type PointOfContactDoc,
51
+ } from "./schemas.js";
35
52
  import {
36
53
  byContactReadingOrder,
37
54
  normalizePointOfContact,
@@ -59,6 +76,83 @@ export interface PocDbLike {
59
76
  /** Resolves seat ids (platform-db `users._id`, string form) to their reach. Missing ids are simply absent. */
60
77
  export type SeatResolver = (userIds: readonly string[]) => Promise<ReadonlyMap<string, SeatReach>>;
61
78
 
79
+ /**
80
+ * A seat's contact log → the lists a seat-linked contact reads (pl-9h4): the
81
+ * live emails (lowercased, as this module keeps emails) and phones, each with
82
+ * the log's preferred mark (one per type; the first when none is marked).
83
+ * `null` when the log has no live entry of either type — the caller then
84
+ * keeps the seat's flat `email` / `phone`.
85
+ */
86
+ export function seatContactListsFromLog(
87
+ entries: readonly SeatContactEntry[],
88
+ ): { emails: PocContactEntry[]; phones: PocContactEntry[] } | null {
89
+ const live = liveSeatContacts(entries);
90
+ if (!live.length) return null;
91
+ const listOf = (type: "email" | "phone"): PocContactEntry[] => {
92
+ const pref = preferredSeatContact(live, type);
93
+ const seen = new Set<string>();
94
+ const out: PocContactEntry[] = [];
95
+ for (const e of live) {
96
+ if (e.contact_type !== type) continue;
97
+ const value = type === "email" ? e.value.trim().toLowerCase() : e.value.trim();
98
+ if (!value || seen.has(value)) continue;
99
+ seen.add(value);
100
+ out.push({ value, is_preferred: e === pref });
101
+ }
102
+ return out;
103
+ };
104
+ return { emails: listOf("email"), phones: listOf("phone") };
105
+ }
106
+
107
+ /**
108
+ * Wrap a seat resolver so seat-linked contacts read each seat's contact log
109
+ * (`seat_contacts`, subject_type `user`) instead of the single `users`
110
+ * email / phone (pl-9h4).
111
+ *
112
+ * - Only seats `resolve` returned are enriched. A seat it leaves out (an
113
+ * ended seat in the network read, an id with no `users` row) stays out:
114
+ * its log never publishes it.
115
+ * - Per type: the log's emails (with `email` = its preferred) replace the
116
+ * seat's flat email only when the log has a live email; likewise phones.
117
+ * A type the log has no live entry of keeps what `resolve` returned.
118
+ * - Ids are matched case-insensitively, as the base resolvers match
119
+ * `users._id`; the result is keyed by the id as asked.
120
+ * - A stored log row that does not match the entry shape is skipped for its
121
+ * seat (reported to `onInvalidRow`) and never fails the read; a read ERROR
122
+ * propagates.
123
+ */
124
+ export function withSeatContactLogs(
125
+ db: SeatLogDbLike,
126
+ resolve: SeatResolver,
127
+ opts: { onInvalidRow?: (error: SeatLogShapeError) => void } = {},
128
+ ): SeatResolver {
129
+ return async (userIds) => {
130
+ const base = await resolve(userIds);
131
+ const ids = userIds.filter((id) => base.has(id));
132
+ const out = new Map<string, SeatReach>(base);
133
+ if (!ids.length) return out;
134
+ const logs = await readSeatContactLogs(db, ids, "user", {
135
+ invalid: "skip",
136
+ onInvalidRow: opts.onInvalidRow,
137
+ });
138
+ for (const id of ids) {
139
+ const lists = seatContactListsFromLog(logs.get(id) ?? []);
140
+ if (!lists) continue;
141
+ const next: SeatReach = { ...base.get(id)! };
142
+ if (lists.emails.length) {
143
+ next.emails = lists.emails;
144
+ next.email = lists.emails.find((e) => e.is_preferred)?.value ?? null;
145
+ }
146
+ if (lists.phones.length) {
147
+ next.phones = lists.phones;
148
+ next.phone = lists.phones.find((e) => e.is_preferred)?.value ?? null;
149
+ }
150
+ out.set(id, next);
151
+ }
152
+ return out;
153
+ };
154
+ }
155
+
62
156
  /**
63
157
  * A subject, always read together with its agency where ids can collide.
64
158
  * Program, team and location ids can be slugs two agencies share, so their reads
@@ -59,9 +59,10 @@
59
59
  *
60
60
  * ## Known deviations (0.30.0)
61
61
  *
62
- * - A seat-linked contact still reads ONE email and ONE phone from `users`
63
- * until a person Contact log exists (pl-9h4). Canon's motivating case
64
- * (Crysta's own seat-linked contact) is therefore not yet met.
62
+ * - A seat-linked contact reads the seat's contact log (`seat_contacts`)
63
+ * when the reader's seat resolver carries it (`withSeatContactLogs`,
64
+ * pl-9h4, 0.87.0); a seat with no log yet still reads ONE email and ONE
65
+ * phone from `users`.
65
66
  * - An entry is removed, not retired: canon's write-in ledger keeps retired
66
67
  * entries stamped `retiredOn` (retire-not-remove, L8181-L8185); this list
67
68
  * keeps only the live ones.
@@ -0,0 +1,222 @@
1
+ /**
2
+ * The pre-review fix batch (B3, S1, S2, S3, S4, S5, S6, S7). Each case failed
3
+ * on the branch before the fix.
4
+ */
5
+ import { describe, expect, it } from "vitest";
6
+
7
+ import {
8
+ SeatLogRefusal,
9
+ addSeatContact,
10
+ addSeatName,
11
+ correctSeatContact,
12
+ correctSeatName,
13
+ liveSeatNames,
14
+ isPersonId,
15
+ mintPersonId,
16
+ readSeatContactLogs,
17
+ retireSeatName,
18
+ seatEmailProjection,
19
+ setPreferredSeatContact,
20
+ setSeatDisplayName,
21
+ type SeatContactEntry,
22
+ type SeatLogSubject,
23
+ type SeatNameEntry,
24
+ } from "../index.js";
25
+
26
+ const S: SeatLogSubject = { subject_type: "user", subject_id: "u1" };
27
+ let n = 0;
28
+ const ctx = (extra: Record<string, unknown> = {}) => ({
29
+ actor: "a",
30
+ at: "2026-11-16T15:00:00.000Z",
31
+ mintId: (k: "name" | "contact") => `${k}-${++n}`,
32
+ ...extra,
33
+ });
34
+ const later = (extra: Record<string, unknown> = {}) => ({ ...ctx(extra), at: "2026-12-01T09:00:00.000Z" });
35
+ const acts = (e: { events?: { act: string }[] }) => (e.events ?? []).map((x) => x.act);
36
+
37
+ /** Ava (display) + Avie, then Avie retired. */
38
+ function namesWithRetired(): { es: SeatNameEntry[]; ava: string; avie: string } {
39
+ const es0 = addSeatName([], S, { raw: "Avie", name_type: "alias" }, ctx({ flatName: "Ava" })).entries;
40
+ const ava = es0.find((e) => e.raw === "Ava")!.entry_id;
41
+ const avie = es0.find((e) => e.raw === "Avie")!.entry_id;
42
+ const es = retireSeatName(es0, S, avie, ctx()).entries;
43
+ return { es, ava, avie };
44
+ }
45
+
46
+ describe("B3: the default entry-id minter", () => {
47
+ it("never collides seeding and adding on a seat with no name log (many iterations)", () => {
48
+ const seen = new Set<string>();
49
+ for (let i = 0; i < 5000; i++) {
50
+ const r = addSeatName([], S, { raw: "B", name_type: "alias" }, { actor: "a", flatName: "A" });
51
+ expect(r.inserted).toHaveLength(2);
52
+ for (const e of r.inserted) {
53
+ expect(e.entry_id.startsWith("nm-u1-rt")).toBe(true);
54
+ expect(seen.has(e.entry_id)).toBe(false);
55
+ seen.add(e.entry_id);
56
+ }
57
+ }
58
+ });
59
+
60
+ it("re-mints when an injected minter returns an id already in the log", () => {
61
+ const ids = ["dup", "dup", "fresh"];
62
+ let i = 0;
63
+ const r = addSeatName([], S, { raw: "B", name_type: "alias" },
64
+ { actor: "a", flatName: "A", mintId: () => ids[i++] });
65
+ expect(r.inserted.map((e) => e.entry_id)).toEqual(["dup", "fresh"]);
66
+ });
67
+ });
68
+
69
+ describe("S1: acts on a retired entry are refused and change nothing", () => {
70
+ const refusedUnchanged = (fn: () => unknown) => {
71
+ expect(fn).toThrow(SeatLogRefusal);
72
+ try { fn(); } catch (e) { expect((e as SeatLogRefusal).code).toBe("entry_not_live"); }
73
+ };
74
+
75
+ it("starring, retiring again and correcting a retired name", () => {
76
+ const { es, avie } = namesWithRetired();
77
+ const snapshot = JSON.stringify(es);
78
+ refusedUnchanged(() => setSeatDisplayName(es, S, avie, ctx()));
79
+ refusedUnchanged(() => retireSeatName(es, S, avie, later()));
80
+ refusedUnchanged(() => correctSeatName(es, S, avie, "Avy", ctx()));
81
+ expect(JSON.stringify(es)).toBe(snapshot);
82
+ expect(liveSeatNames(es).filter((e) => e.is_display).map((e) => e.raw)).toEqual(["Ava"]);
83
+ });
84
+
85
+ it("preferring and correcting a retired email", () => {
86
+ let es: SeatContactEntry[] = addSeatContact([], S, { contact_type: "email", value: "a@x.org" }, ctx()).entries;
87
+ es = addSeatContact(es, S, { contact_type: "email", value: "b@x.org" }, ctx()).entries;
88
+ const b = es.find((e) => e.value === "b@x.org")!.entry_id;
89
+ es = correctSeatContact(es, S, b, "c@x.org", ctx()).entries; // b retired
90
+ refusedUnchanged(() => setPreferredSeatContact(es, S, b, ctx()));
91
+ refusedUnchanged(() => correctSeatContact(es, S, b, "d@x.org", ctx()));
92
+ expect(seatEmailProjection(es)).toBe("a@x.org");
93
+ });
94
+ });
95
+
96
+ describe("S2: correcting a name to the same text", () => {
97
+ it("is a no-op on a logged name", () => {
98
+ const es = addSeatName([], S, { raw: "A", name_type: "legal" }, ctx()).entries;
99
+ const r = correctSeatName(es, S, es[0].entry_id, " A ", ctx());
100
+ expect([r.inserted, r.updated]).toEqual([[], []]);
101
+ });
102
+
103
+ it("is a no-op on the __flat__ row (nothing is seeded)", () => {
104
+ const r = correctSeatName([], S, "__flat__", "A", ctx({ flatName: "A" }));
105
+ expect(r.entries).toEqual([]);
106
+ });
107
+ });
108
+
109
+ describe("S7: events are stamped as the prototype store stamps them", () => {
110
+ it("an archived target reads cascade, archive", () => {
111
+ const { es, avie } = namesWithRetired();
112
+ expect(acts(es.find((e) => e.entry_id === avie)!)).toEqual(["add", "cascade", "archive"]);
113
+ });
114
+
115
+ it("a correction of the display name: the new row and the old row", () => {
116
+ const es0 = addSeatName([], S, { raw: "A", name_type: "legal" }, ctx()).entries;
117
+ const r = correctSeatName(es0, S, es0[0].entry_id, "B", ctx());
118
+ const added = r.inserted[0];
119
+ const old = r.updated[0];
120
+ expect(acts(added)).toEqual(["add", "cascade", "set_display", "cascade", "set_preferred"]);
121
+ // cleared by set_display, cleared by set_preferred, then dated by archive
122
+ expect(acts(old)).toEqual(["add", "cascade", "cascade", "cascade", "archive"]);
123
+ });
124
+
125
+ it("an add that takes the preferred mark leaves its own events at add", () => {
126
+ const r = addSeatContact([], S, { contact_type: "phone", value: "4026773902" }, ctx());
127
+ expect(acts(r.inserted[0])).toEqual(["add"]);
128
+ });
129
+ });
130
+
131
+ describe("S6: mintPersonId", () => {
132
+ const words = { first: ["a", "b"], second: ["x", "y"] };
133
+
134
+ it("clamps an out-of-range random draw", () => {
135
+ expect(mintPersonId(words, [], () => 1)).toBe("per-b-y");
136
+ expect(mintPersonId(words, [], () => -0.5)).toBe("per-a-x");
137
+ expect(mintPersonId(words, [], () => Number.NaN)).toBe("per-a-x");
138
+ });
139
+
140
+ it("finds the last free pair by scanning after the random draws", () => {
141
+ const all = ["per-a-x", "per-a-y", "per-b-x", "per-b-y"];
142
+ expect(mintPersonId(words, all.slice(0, 3), () => 0)).toBe("per-b-y");
143
+ });
144
+
145
+ it("a full pair pool mints a numeric suffix (the records generator's rule), unique vs taken", () => {
146
+ const all = ["per-a-x", "per-a-y", "per-b-x", "per-b-y"];
147
+ const id = mintPersonId(words, all)!;
148
+ expect(id).toMatch(/^per-[ab]-[xy]-\d{1,3}$/);
149
+ expect(all).not.toContain(id);
150
+ // random() = 0 always draws per-a-x-0: taken too, so the scan takes the next free one.
151
+ expect(mintPersonId(words, [...all, "per-a-x-0"], () => 0)).toBe("per-a-y-0");
152
+ // every pair at every suffix 0-999 taken: the scan goes past 999 and still ends.
153
+ const huge: string[] = [...all];
154
+ for (const p of all) for (let i = 0; i < 1000; i++) huge.push(`${p}-${i}`);
155
+ expect(mintPersonId(words, huge, () => 0)).toBe("per-a-x-1000");
156
+ });
157
+
158
+ it("null only when there are no wordlists", () => {
159
+ expect(mintPersonId(null, [])).toBeNull();
160
+ expect(mintPersonId({ first: ["a"], second: [] })).toBeNull();
161
+ });
162
+
163
+ it("the id pattern accepts both forms", () => {
164
+ expect(isPersonId("per-amber-beacon")).toBe(true);
165
+ expect(isPersonId("per-amber-beacon-42")).toBe(true);
166
+ expect(isPersonId("per-amber-beacon-")).toBe(false);
167
+ expect(isPersonId("per-amber")).toBe(false);
168
+ expect(isPersonId("per-Amber-beacon")).toBe(false);
169
+ });
170
+ });
171
+
172
+ describe("S3 + S4 + S5: reading a log", () => {
173
+ const row = (subject_id: string, entry_id: string, value: string): Record<string, unknown> => ({
174
+ entry_id, subject_id, subject_type: "user", contact_type: "email", value, use: "",
175
+ is_preferred: false, safety_status: "", period_start: "", period_end: "",
176
+ source: "admin_hub", method: "direct_entry", notes: "",
177
+ });
178
+ const dbOf = (rows: Record<string, unknown>[]) => {
179
+ const asked: unknown[] = [];
180
+ return {
181
+ asked,
182
+ db: {
183
+ collection: () => ({
184
+ find: (f: Record<string, unknown>) => {
185
+ asked.push(f.subject_id);
186
+ const ids = (f.subject_id as { $in: string[] }).$in;
187
+ const hit = rows.filter((r) => ids.includes(r.subject_id as string));
188
+ return { toArray: async () => hit };
189
+ },
190
+ }),
191
+ },
192
+ };
193
+ };
194
+ const HEX = "0123456789abcdef01234567";
195
+
196
+ it("matches a seat id asked upper-case to its log stored lower-case, keyed as asked", async () => {
197
+ const { db } = dbOf([row(HEX, "ci-1", "a@x.org")]);
198
+ const m = await readSeatContactLogs(db, [HEX.toUpperCase()]);
199
+ expect(m.get(HEX.toUpperCase())?.map((e) => e.value)).toEqual(["a@x.org"]);
200
+ });
201
+
202
+ it("lists a subject's entries in entry_id order", async () => {
203
+ const { db } = dbOf([
204
+ row("u1", "ci-c", "c@x.org"), row("u1", "ci-a", "a@x.org"), row("u1", "ci-b", "b@x.org"),
205
+ ]);
206
+ const m = await readSeatContactLogs(db, ["u1"]);
207
+ expect(m.get("u1")?.map((e) => e.entry_id)).toEqual(["ci-a", "ci-b", "ci-c"]);
208
+ });
209
+
210
+ it("skips a malformed row when asked to, keeping the subject's good rows", async () => {
211
+ const bad = { ...row("u1", "ci-bad", "z@x.org"), notes: undefined };
212
+ const { db } = dbOf([row("u1", "ci-a", "a@x.org"), bad, row("u2", "ci-b", "b@x.org")]);
213
+ const seen: string[] = [];
214
+ const m = await readSeatContactLogs(db, ["u1", "u2"], "user", {
215
+ invalid: "skip", onInvalidRow: (e) => seen.push(e.entryId ?? ""),
216
+ });
217
+ expect(m.get("u1")?.map((e) => e.entry_id)).toEqual(["ci-a"]);
218
+ expect(m.get("u2")?.map((e) => e.entry_id)).toEqual(["ci-b"]);
219
+ expect(seen).toEqual(["ci-bad"]);
220
+ await expect(readSeatContactLogs(db, ["u1"])).rejects.toThrow("ci-bad");
221
+ });
222
+ });