create-ailk 0.19.0 → 0.20.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 (197) hide show
  1. package/README.md +64 -7
  2. package/dist/add-module.js +7 -2
  3. package/dist/cli.js +35 -0
  4. package/dist/copy.d.ts +41 -0
  5. package/dist/copy.js +87 -21
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/lib/fetch-template-snapshot.d.ts +21 -0
  9. package/dist/lib/fetch-template-snapshot.js +205 -0
  10. package/dist/lib/merge-three-way.d.ts +31 -0
  11. package/dist/lib/merge-three-way.js +65 -0
  12. package/dist/lib/scaffold-render-sweep.d.ts +23 -0
  13. package/dist/lib/scaffold-render-sweep.js +52 -0
  14. package/dist/module-architecture.js +64 -5
  15. package/dist/programmatic.d.ts +7 -1
  16. package/dist/programmatic.js +40 -3
  17. package/dist/site-roster.js +21 -4
  18. package/dist/spoke-checkout.d.ts +7 -0
  19. package/dist/spoke-checkout.js +8 -1
  20. package/dist/surfaces.d.ts +14 -0
  21. package/dist/surfaces.js +98 -3
  22. package/dist/template-record.d.ts +59 -0
  23. package/dist/template-record.js +183 -0
  24. package/dist/topology.js +29 -1
  25. package/dist/update.d.ts +48 -0
  26. package/dist/update.js +504 -0
  27. package/package.json +3 -3
  28. package/templates/.claude/cloudparity-repo-hooks.json +9 -0
  29. package/templates/.claude/hooks/architecture-check.sh +8 -0
  30. package/templates/.claude/rules/loop-contract.md +129 -0
  31. package/templates/.claude/settings.json +3 -2
  32. package/templates/.env.example +13 -0
  33. package/templates/CLAUDE.md +1 -1
  34. package/templates/CONVENTIONS.md +3 -2
  35. package/templates/_gitignore +162 -0
  36. package/templates/apps/api/.env.example +17 -1
  37. package/templates/apps/api/CLAUDE.md +18 -8
  38. package/templates/apps/api/package.json +2 -1
  39. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +41 -2
  40. package/templates/apps/api/src/__tests__/setup.ts +7 -0
  41. package/templates/apps/api/src/__tests__/stripe-boot.test.ts +132 -0
  42. package/templates/apps/api/src/bin/__tests__/rate-limit-probe.test.ts +184 -0
  43. package/templates/apps/api/src/bin/rate-limit-probe.ts +53 -0
  44. package/templates/apps/api/src/lib/__mocks__/prisma.ts +8 -0
  45. package/templates/apps/api/src/lib/__tests__/consent-ledger-double.ts +237 -0
  46. package/templates/apps/api/src/lib/__tests__/consent-store.test.ts +334 -0
  47. package/templates/apps/api/src/lib/__tests__/stripe-admission.test.ts +217 -0
  48. package/templates/apps/api/src/lib/__tests__/stripe.test.ts +7 -0
  49. package/templates/apps/api/src/lib/consent-store.ts +335 -0
  50. package/templates/apps/api/src/lib/proposal-paid-store.ts +49 -0
  51. package/templates/apps/api/src/lib/rate-limit-probe.ts +165 -0
  52. package/templates/apps/api/src/lib/rate-limit-store.ts +142 -0
  53. package/templates/apps/api/src/lib/stripe.ts +97 -5
  54. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +13 -4
  55. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +2 -0
  56. package/templates/apps/api/src/middleware/__tests__/rate-limit-cross-isolate.db.test.ts +220 -0
  57. package/templates/apps/api/src/middleware/__tests__/rate-limit-store.test.ts +430 -0
  58. package/templates/apps/api/src/middleware/__tests__/rate-limit.test.ts +72 -14
  59. package/templates/apps/api/src/middleware/auth.ts +16 -4
  60. package/templates/apps/api/src/middleware/default-tenant.ts +9 -0
  61. package/templates/apps/api/src/middleware/rate-limit.ts +295 -82
  62. package/templates/apps/api/src/routes/checkout/__tests__/live-key.test.ts +167 -0
  63. package/templates/apps/api/src/routes/checkout/session.ts +3 -3
  64. package/templates/apps/api/src/routes/checkout/sessions.ts +6 -4
  65. package/templates/apps/api/src/routes/consent/cookie.ts +90 -0
  66. package/templates/apps/api/src/routes/consent/index.ts +18 -0
  67. package/templates/apps/api/src/routes/consent/unsubscribe.ts +127 -0
  68. package/templates/apps/api/src/routes/leads/index.ts +15 -0
  69. package/templates/apps/api/src/routes/project-listings/__tests__/drafts.test.ts +5 -0
  70. package/templates/apps/api/src/routes/webhooks/README.md +33 -5
  71. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +17 -4
  72. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-idempotency.test.ts +2 -0
  73. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode-live.test.ts +159 -0
  74. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-livemode.test.ts +158 -0
  75. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-proposal-paid.test.ts +369 -0
  76. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-rate-limit.test.ts +2 -0
  77. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +442 -0
  78. package/templates/apps/api/src/routes/webhooks/stripe.ts +201 -6
  79. package/templates/apps/api/src/server.ts +125 -18
  80. package/templates/apps/api/src/services/__tests__/audit-log.test.ts +91 -0
  81. package/templates/apps/api/src/services/__tests__/consent-ledger.test.ts +503 -0
  82. package/templates/apps/api/src/services/__tests__/consent.test.ts +18 -3
  83. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +115 -4
  84. package/templates/apps/api/src/services/__tests__/person.test.ts +392 -0
  85. package/templates/apps/api/src/services/__tests__/request-confirm.test.ts +87 -0
  86. package/templates/apps/api/src/services/__tests__/revalidation.test.ts +57 -17
  87. package/templates/apps/api/src/services/audit-log.ts +72 -10
  88. package/templates/apps/api/src/services/consent.ts +488 -3
  89. package/templates/apps/api/src/services/default-tenant.ts +12 -3
  90. package/templates/apps/api/src/services/hub-sign-in.ts +2 -1
  91. package/templates/apps/api/src/services/lead-routing.ts +105 -12
  92. package/templates/apps/api/src/services/person.ts +501 -1
  93. package/templates/apps/api/src/services/project-listings.ts +7 -2
  94. package/templates/apps/api/src/services/public-site-resolver.ts +21 -2
  95. package/templates/apps/api/src/services/request-confirm.ts +52 -0
  96. package/templates/apps/api/src/services/revalidation.ts +11 -1
  97. package/templates/apps/api/vercel.json +1 -1
  98. package/templates/apps/mcp/CLAUDE.md +19 -7
  99. package/templates/apps/mcp/__tests__/catalog-drift.test.ts +95 -8
  100. package/templates/apps/mcp/src/tools/person_notes.ts +25 -0
  101. package/templates/apps/mcp/src/tools/proposals.ts +27 -0
  102. package/templates/apps/mcp/src/workspace-server.ts +16 -0
  103. package/templates/apps/web/_gitignore +6 -0
  104. package/templates/apps/web/app/[locale]/(auth)/sign-up/__tests__/sign-up-card.test.tsx +165 -0
  105. package/templates/apps/web/app/[locale]/(auth)/sign-up/page.tsx +19 -0
  106. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up-card.tsx +106 -23
  107. package/templates/apps/web/app/[locale]/(auth)/sign-up/sign-up.actions.ts +125 -0
  108. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/account-frame-sign-out.test.tsx +175 -0
  109. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/agreements-prompt.test.tsx +281 -0
  110. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/billing.test.tsx +17 -3
  111. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/general.test.tsx +154 -53
  112. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +116 -27
  113. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/item.test.tsx +57 -2
  114. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout-sign-out.test.tsx +146 -0
  115. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/layout.test.tsx +124 -18
  116. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/notifications.test.tsx +116 -18
  117. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/onboarding.test.tsx +323 -0
  118. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/privacy.test.tsx +365 -0
  119. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/security.test.tsx +290 -20
  120. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/settings.test.tsx +56 -0
  121. package/templates/apps/web/app/[locale]/(authed)/account/account-frame.tsx +74 -4
  122. package/templates/apps/web/app/[locale]/(authed)/account/actions.ts +8 -0
  123. package/templates/apps/web/app/[locale]/(authed)/account/agreements-actions.ts +170 -0
  124. package/templates/apps/web/app/[locale]/(authed)/account/agreements-prompt.tsx +181 -0
  125. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/page.tsx +88 -3
  126. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/pay-form.tsx +65 -0
  127. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/[pieceId]/review-form.tsx +27 -0
  128. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/page.test.tsx +176 -3
  129. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/pay.test.tsx +193 -0
  130. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/__tests__/review.test.tsx +188 -0
  131. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-actions.ts +65 -4
  132. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/artifact-data.ts +17 -0
  133. package/templates/apps/web/app/[locale]/(authed)/account/artifacts/page.tsx +15 -9
  134. package/templates/apps/web/app/[locale]/(authed)/account/billing/page.tsx +3 -3
  135. package/templates/apps/web/app/[locale]/(authed)/account/general/contact-actions.ts +81 -0
  136. package/templates/apps/web/app/[locale]/(authed)/account/general/page.tsx +70 -27
  137. package/templates/apps/web/app/[locale]/(authed)/account/layout.tsx +26 -3
  138. package/templates/apps/web/app/[locale]/(authed)/account/notifications/page.tsx +65 -19
  139. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/actions.ts +120 -0
  140. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/onboarding-form.tsx +322 -0
  141. package/templates/apps/web/app/[locale]/(authed)/account/onboarding/page.tsx +126 -0
  142. package/templates/apps/web/app/[locale]/(authed)/account/page.tsx +43 -1
  143. package/templates/apps/web/app/[locale]/(authed)/account/privacy/actions.ts +65 -0
  144. package/templates/apps/web/app/[locale]/(authed)/account/privacy/page.tsx +226 -0
  145. package/templates/apps/web/app/[locale]/(authed)/account/security/page.tsx +89 -37
  146. package/templates/apps/web/app/[locale]/(authed)/account/security/security-panel.tsx +102 -0
  147. package/templates/apps/web/app/[locale]/(authed)/account/security/security-source.ts +62 -0
  148. package/templates/apps/web/app/[locale]/(authed)/account/settings-frame.tsx +44 -34
  149. package/templates/apps/web/app/[locale]/(authed)/account/sign-in-method.ts +1 -1
  150. package/templates/apps/web/app/[locale]/consent-banner.tsx +32 -0
  151. package/templates/apps/web/app/[locale]/consent.actions.ts +71 -0
  152. package/templates/apps/web/app/[locale]/contact/contact.actions.ts +13 -1
  153. package/templates/apps/web/app/[locale]/flows/[slug]/flow.actions.ts +25 -3
  154. package/templates/apps/web/app/[locale]/layout.tsx +23 -2
  155. package/templates/apps/web/app/[locale]/newsletter/newsletter.actions.ts +12 -1
  156. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe-rsc-boundary.test.tsx +209 -0
  157. package/templates/apps/web/app/[locale]/unsubscribe/__tests__/unsubscribe.test.tsx +158 -0
  158. package/templates/apps/web/app/[locale]/unsubscribe/page.tsx +54 -0
  159. package/templates/apps/web/app/[locale]/unsubscribe/unsubscribe-button.tsx +73 -0
  160. package/templates/apps/web/app/[locale]/unsubscribe/unsubscribe.actions.ts +55 -0
  161. package/templates/apps/web/app/robots.txt/route.ts +13 -10
  162. package/templates/apps/web/auth.ts +20 -1
  163. package/templates/apps/web/jest.config.cjs +3 -0
  164. package/templates/apps/web/lib/__tests__/auth-email.test.ts +84 -0
  165. package/templates/apps/web/lib/__tests__/consent-visitor.test.ts +163 -0
  166. package/templates/apps/web/lib/__tests__/relay.test.ts +49 -0
  167. package/templates/apps/web/lib/__tests__/structured-data.test.tsx +96 -7
  168. package/templates/apps/web/lib/account-config.ts +31 -16
  169. package/templates/apps/web/lib/auth-email.ts +45 -10
  170. package/templates/apps/web/lib/consent-visitor.ts +103 -0
  171. package/templates/apps/web/lib/relay.ts +20 -0
  172. package/templates/apps/web/lib/topology.generated.ts +9 -0
  173. package/templates/apps/web/messages/en.json +121 -18
  174. package/templates/apps/web/next.config.mjs +8 -2
  175. package/templates/database/CHANGELOG.md +55 -0
  176. package/templates/database/__tests__/consent-ledger.db.test.ts +345 -0
  177. package/templates/database/__tests__/fence-fan-out.db.test.ts +6 -2
  178. package/templates/database/__tests__/fixtures/person-contact-backfill.json +182 -0
  179. package/templates/database/__tests__/outbound-message-action.db.test.ts +80 -0
  180. package/templates/database/__tests__/person-contact.db.test.ts +563 -0
  181. package/templates/database/__tests__/person-notes.db.test.ts +249 -0
  182. package/templates/database/__tests__/person.db.test.ts +3 -1
  183. package/templates/database/__tests__/piece-kind-migration.test.ts +67 -0
  184. package/templates/database/__tests__/piece-kind.db.test.ts +208 -0
  185. package/templates/database/_gitignore +8 -0
  186. package/templates/database/inbox/schema.prisma +114 -22
  187. package/templates/database/migrations/20261014120000_consent_ledger/migration.sql +122 -0
  188. package/templates/database/migrations/20261014120000_person_contact/migration.sql +231 -0
  189. package/templates/database/migrations/20261015120000_person_notes/migration.sql +77 -0
  190. package/templates/database/migrations/20261015120000_rate_limit_counters/migration.sql +43 -0
  191. package/templates/database/migrations/20261016120000_piece_kind/migration.sql +95 -0
  192. package/templates/database/migrations/20261017120000_outbound_message_action/migration.sql +30 -0
  193. package/templates/database/ops/schema.prisma +16 -0
  194. package/templates/database/package.json +1 -1
  195. package/templates/project.yaml +6 -3
  196. package/versions.json +35 -35
  197. package/templates/.claude/rules/preserve-existing-style.md +0 -51
@@ -127,19 +127,49 @@ model Lead {
127
127
  /// writer wins. `planOffering` is written by a later phase (Epic 2's
128
128
  /// checkout-lead rule); this slice only carries the column.
129
129
  model Person {
130
- id String @id @default(dbgenerated("('person_'::text || (uuidv7())::text)")) @db.Text
131
- workspaceId String @map("workspace_id")
132
- email String @db.VarChar(254)
133
- name String? @db.VarChar(200)
134
- userId String? @map("user_id")
135
- billingProvider String? @map("billing_provider") @db.VarChar(32)
136
- billingCustomerId String? @map("billing_customer_id") @db.VarChar(255)
137
- planOffering String? @map("plan_offering") @db.VarChar(100)
138
- createdAt DateTime @default(now()) @map("created_at")
139
- updatedAt DateTime @updatedAt @map("updated_at")
130
+ id String @id @default(dbgenerated("('person_'::text || (uuidv7())::text)")) @db.Text
131
+ workspaceId String @map("workspace_id")
132
+ email String @db.VarChar(254)
133
+ name String? @db.VarChar(200)
134
+ userId String? @map("user_id")
135
+ billingProvider String? @map("billing_provider") @db.VarChar(32)
136
+ billingCustomerId String? @map("billing_customer_id") @db.VarChar(255)
137
+ planOffering String? @map("plan_offering") @db.VarChar(100)
138
+ // #8435 D1 — contact details, to the standard (option A). Every column is
139
+ // nullable: a capture fills only a blank one (D4), an edit overwrites (D9,
140
+ // D11). The address is the magnet's six parts, stored whole or not at all
141
+ // (people_address_complete).
142
+ givenName String? @map("given_name") @db.VarChar(100)
143
+ familyName String? @map("family_name") @db.VarChar(100)
144
+ telephone String? @db.VarChar(16)
145
+ addressLine1 String? @map("address_line1") @db.VarChar(100)
146
+ addressLine2 String? @map("address_line2") @db.VarChar(60)
147
+ addressCity String? @map("address_city") @db.VarChar(60)
148
+ addressRegion String? @map("address_region") @db.VarChar(40)
149
+ addressPostalCode String? @map("address_postal_code") @db.VarChar(20)
150
+ addressCountry String? @map("address_country") @db.Char(2)
151
+ companyName String? @map("company_name") @db.VarChar(200)
152
+ jobTitle String? @map("job_title") @db.VarChar(100)
153
+ // Who last saved the contact by hand — "operator" (the Person page) or
154
+ // "client" (their account) — and when. NULL until a human saves it; while
155
+ // NULL and `userId` is NULL, a capture may fill a blank field (D4).
156
+ contactConfirmedAt DateTime? @map("contact_confirmed_at")
157
+ contactConfirmedBy String? @map("contact_confirmed_by") @db.VarChar(16)
158
+ // #8514 D1 — the team's private note on this client: one per Person, never
159
+ // served to the client. Who last saved it (a user id of the auth namespace,
160
+ // no foreign key — ADR 0009) and when; both NULL until the first save.
161
+ // When an agent saved it, which agent (its person is notesUpdatedBy).
162
+ notes String? @db.VarChar(5000)
163
+ notesUpdatedAt DateTime? @map("notes_updated_at")
164
+ notesUpdatedBy String? @map("notes_updated_by")
165
+ notesUpdatedByAgent String? @map("notes_updated_by_agent")
166
+ createdAt DateTime @default(now()) @map("created_at")
167
+ updatedAt DateTime @updatedAt @map("updated_at")
140
168
 
141
169
  pieces Piece[]
142
170
  interactions Interaction[]
171
+ callbacks Callback[]
172
+ subscribers Subscriber[]
143
173
 
144
174
  @@unique([workspaceId, email])
145
175
  @@unique([workspaceId, userId])
@@ -152,7 +182,7 @@ model Person {
152
182
  @@map("people")
153
183
  }
154
184
 
155
- /// Piece — one deliverable for one client (#7877). Written only through
185
+ /// Piece — one deliverable or proposal for one client (#7877, #8516). Written only through
156
186
  /// tenantDb(tenant).memberArea; read by a client only through
157
187
  /// lib/member-store.ts. `stage` is one of the workspace's declared stages
158
188
  /// (WorkspacePieceStages), checked at write time, never an enum.
@@ -162,16 +192,32 @@ model Person {
162
192
  /// review lands. Approval is a piece-level fact; the version's own `review`
163
193
  /// records which version was approved.
164
194
  model Piece {
165
- id String @id @default(dbgenerated("('piece_'::text || (uuidv7())::text)")) @db.Text
166
- workspaceId String @map("workspace_id")
167
- personId String @map("person_id")
168
- title String @db.VarChar(200)
169
- stage String @db.VarChar(40)
170
- needsClient Boolean @default(false) @map("needs_client")
171
- updatedBy String @map("updated_by")
172
- approvedAt DateTime? @map("approved_at")
173
- createdAt DateTime @default(now()) @map("created_at")
174
- updatedAt DateTime @updatedAt @map("updated_at")
195
+ id String @id @default(dbgenerated("('piece_'::text || (uuidv7())::text)")) @db.Text
196
+ workspaceId String @map("workspace_id")
197
+ personId String @map("person_id")
198
+ title String @db.VarChar(200)
199
+ stage String @db.VarChar(40)
200
+ needsClient Boolean @default(false) @map("needs_client")
201
+ updatedBy String @map("updated_by")
202
+ approvedAt DateTime? @map("approved_at")
203
+ // #8516 D1 — what the piece is: a `deliverable` (every row before #8516) or a
204
+ // `proposal` the client approves or sends back. Never changes after create.
205
+ kind String @default("deliverable") @db.VarChar(16)
206
+ // A proposal's price, in minor units of a two-decimal currency; both or
207
+ // neither, and only on a proposal.
208
+ priceAmount Int? @map("price_amount")
209
+ priceCurrency String? @map("price_currency") @db.Char(3)
210
+ // The client's current Stripe Checkout Session (#8516 D11) — its id, URL and
211
+ // expiry. Never served to the operator. Replaced once five minutes or less
212
+ // remain; the replaced session is expired at Stripe.
213
+ checkoutSessionId String? @unique @map("checkout_session_id")
214
+ checkoutUrl String? @map("checkout_url") @db.VarChar(2048)
215
+ checkoutExpiresAt DateTime? @map("checkout_expires_at")
216
+ // When Stripe reported the proposal paid, and the session that paid it (D13).
217
+ paidAt DateTime? @map("paid_at")
218
+ paidSessionId String? @map("paid_session_id")
219
+ createdAt DateTime @default(now()) @map("created_at")
220
+ updatedAt DateTime @updatedAt @map("updated_at")
175
221
 
176
222
  person Person @relation(fields: [personId, workspaceId], references: [id, workspaceId], onDelete: Restrict, map: "pieces_person_fk")
177
223
  versions PieceVersion[]
@@ -227,7 +273,9 @@ model PieceVersion {
227
273
  ///
228
274
  /// #8168 D3/D4 — `direction` is `outbound` (an operator's message, #7877) or
229
275
  /// `inbound` (a client's own write); `kind` is `message`, `quote` or
230
- /// `review`. An outbound row is always a `message` with no `payload`
276
+ /// `review`. An outbound row is always a `message` whose `payload` is null
277
+ /// or, since #8515 D6, exactly `{ "action": "onboarding" }` — the one outbound
278
+ /// action, rendered by the client's site as a link to `/account/onboarding`
231
279
  /// (`interactions_outbound_shape`); a `quote` or `review` row carries the
232
280
  /// stored payload `packages/validation`'s member.ts types. Every existing
233
281
  /// reader filters to `direction: "outbound"`, so an inbound row is invisible
@@ -269,9 +317,14 @@ model Subscriber {
269
317
  email String
270
318
  source String
271
319
  createdAt DateTime @default(now()) @map("created_at")
320
+ // #8435 D1/D5 — the Person this subscription belongs to; composite FK onto
321
+ // people(id, workspace_id), the #7877 shape. NULL is not checked.
322
+ personId String? @map("person_id")
323
+ person Person? @relation(fields: [personId, workspaceId], references: [id, workspaceId], onDelete: Restrict, map: "subscribers_person_fk")
272
324
 
273
325
  @@unique([siteId, email])
274
326
  @@index([siteId])
327
+ @@index([personId])
275
328
  @@index([workspaceId])
276
329
  @@map("subscribers")
277
330
  }
@@ -338,7 +391,14 @@ model Callback {
338
391
  /// that update IS the durable idempotency key.
339
392
  paidAt DateTime? @map("paid_at")
340
393
 
394
+ // #8435 D1/D5 — the Person this request belongs to (its payload.email, or
395
+ // the buyer email at confirm). Composite FK onto people(id, workspace_id):
396
+ // "a Person of the same workspace" is a database fact. NULL is not checked.
397
+ personId String? @map("person_id")
398
+ person Person? @relation(fields: [personId, workspaceId], references: [id, workspaceId], onDelete: Restrict, map: "callbacks_person_fk")
399
+
341
400
  @@index([siteId])
401
+ @@index([personId])
342
402
  @@index([createdAt])
343
403
  @@index([stripePaymentLinkId])
344
404
  @@index([stripeInvoiceId])
@@ -1243,6 +1303,18 @@ model ConsentGrant {
1243
1303
  locale String
1244
1304
  statement String @db.Text
1245
1305
  statementHash String @map("statement_hash")
1306
+ // #8438 D2 — the Person this row counts toward. A plain scalar with no
1307
+ // foreign key (this table's own D10 posture): a row about a visitor or a
1308
+ // listing has none, and a ledger row must outlive anything it names.
1309
+ personId String? @map("person_id")
1310
+ // #8438 D2 — where the answer came from (CONSENT_SOURCES). NOT NULL with no
1311
+ // default after the migration: every new row must say. Rows stored before
1312
+ // this column read `legacy`.
1313
+ source String @db.Text
1314
+ // The magnet slug when `source` is `magnet`.
1315
+ sourceRef String? @map("source_ref") @db.VarChar(200)
1316
+ // The registry's policy version the person read. NULL only for `legacy` rows.
1317
+ policyVersion Int? @map("policy_version")
1246
1318
  createdAt DateTime @default(now()) @map("created_at")
1247
1319
 
1248
1320
  // "What did this subject agree to" — every row for one subject, newest last.
@@ -1250,9 +1322,29 @@ model ConsentGrant {
1250
1322
  // "Who agreed to this purpose" — the cross-surface count the id exists for (D1/D2).
1251
1323
  @@index([siteId, purposeId])
1252
1324
  @@index([workspaceId])
1325
+ // #8438 D2 — "current state per purpose" for one Person (DISTINCT ON).
1326
+ @@index([workspaceId, personId, purposeId, createdAt])
1253
1327
  @@map("consent_grants")
1254
1328
  }
1255
1329
 
1330
+ // #8438 D2 — links a banner visitor (a random browser-held id) to the Person a
1331
+ // later form or sign-in identifies, so the Person's cookie history can include
1332
+ // the visitor's own rows without ever editing them. Append-only like the
1333
+ // ledger: a database trigger refuses any change to a stored row. No relation
1334
+ // directive (ADR-0009 invariant #1); no IP, user-agent or device column.
1335
+ model ConsentVisitorLink {
1336
+ id String @id @default(dbgenerated("('cvlink_'::text || (uuidv7())::text)")) @db.Text
1337
+ workspaceId String @map("workspace_id")
1338
+ visitorId String @map("visitor_id")
1339
+ personId String @map("person_id")
1340
+ source String @db.Text
1341
+ createdAt DateTime @default(now()) @map("created_at")
1342
+
1343
+ @@unique([workspaceId, visitorId, personId])
1344
+ @@index([workspaceId, personId])
1345
+ @@map("consent_visitor_links")
1346
+ }
1347
+
1256
1348
  /// Appointment — a Cal.com booking, normalized from the webhook receiver (#6085, brief H7).
1257
1349
  ///
1258
1350
  /// siteId-scoped with no FK, like every other inbox model (ADR 0009 D2). The
@@ -0,0 +1,122 @@
1
+ -- #8438 — the consent ledger (spec docs/specs/8438-consent-registry-and-ledger-step-spec.md D2).
2
+ --
3
+ -- consent_grants (inbox) — the existing append-only table (#5275)
4
+ -- becomes THE ledger. It gains the Person a
5
+ -- row counts toward, the source it came
6
+ -- from, the magnet slug, and the policy
7
+ -- version read. Every row stored before this
8
+ -- migration reads source = 'legacy' with no
9
+ -- policy version, honestly: those rows
10
+ -- recorded neither. Every row written after
11
+ -- it must name its source and version.
12
+ -- consent_visitor_links (inbox) — a banner visitor id linked to the Person a
13
+ -- later form or sign-in identifies. A second
14
+ -- append-only table, so a visitor's own rows
15
+ -- are never edited to point at a Person.
16
+ --
17
+ -- Both tables are APPEND-ONLY, and now the database says so: a trigger refuses
18
+ -- any change to a stored row and any truncation. The triggers bind the
19
+ -- application's database role; a table owner can still disable them. A later
20
+ -- migration that must rewrite or erase rows disables them explicitly inside its
21
+ -- own transaction, which makes the act a reviewed migration rather than
22
+ -- something application code can do.
23
+ --
24
+ -- person_id is a plain scalar with no foreign key, the table's own posture
25
+ -- (ADR 0009 invariant 1, #5275 D10): a row about a visitor or a listing has no
26
+ -- Person, and a ledger row must outlive anything it names. Neither table
27
+ -- carries any network or browser evidence column (spec section 2.3).
28
+ --
29
+ -- ADDITIVE: ADD COLUMN with a constant default, then the default dropped, so no
30
+ -- existing row fails a new CHECK. Deploy this migration BEFORE any code that
31
+ -- writes the new columns; code written before it never names them.
32
+ --
33
+ -- Rollback (safe while nothing but #8438 writes the new surface):
34
+ -- DROP TABLE "consent_visitor_links";
35
+ -- ALTER TABLE "consent_grants" DISABLE TRIGGER USER;
36
+ -- ALTER TABLE "consent_grants"
37
+ -- DROP COLUMN "person_id", DROP COLUMN "source", DROP COLUMN "source_ref", DROP COLUMN "policy_version";
38
+ -- ALTER TABLE "consent_grants" ENABLE TRIGGER USER; -- after dropping the three triggers and the function
39
+ -- DROP FUNCTION "consent_ledger_append_only"();
40
+
41
+ -- AlterTable
42
+ -- source: every row already stored reads 'legacy'; the default is dropped
43
+ -- straight after, so every new row has to say where it came from.
44
+ ALTER TABLE "consent_grants" ADD COLUMN "person_id" TEXT,
45
+ ADD COLUMN "source" TEXT NOT NULL DEFAULT 'legacy',
46
+ ADD COLUMN "source_ref" VARCHAR(200),
47
+ ADD COLUMN "policy_version" INTEGER;
48
+ ALTER TABLE "consent_grants" ALTER COLUMN "source" DROP DEFAULT;
49
+
50
+ -- CreateIndex
51
+ -- "Current state per purpose" for one Person: DISTINCT ON (purpose_id) over
52
+ -- workspace_id = $1 AND person_id = $2 ORDER BY purpose_id, created_at DESC.
53
+ CREATE INDEX "consent_grants_workspace_id_person_id_purpose_id_created_at_idx" ON "consent_grants"("workspace_id", "person_id", "purpose_id", "created_at");
54
+
55
+ -- The source vocabulary is packages/validation CONSENT_SOURCES. 'legacy' is
56
+ -- read-only in practice: only the default above ever writes it.
57
+ ALTER TABLE "consent_grants" ADD CONSTRAINT "consent_grants_source_known"
58
+ CHECK ("source" IN ('cookie_banner', 'sign_up', 'magnet', 'account_settings', 'email_unsubscribe', 'api', 'legacy'));
59
+ -- A new row records the policy version it was read at; only a legacy row may not.
60
+ ALTER TABLE "consent_grants" ADD CONSTRAINT "consent_grants_policy_version_present"
61
+ CHECK ("source" = 'legacy' OR "policy_version" IS NOT NULL);
62
+ ALTER TABLE "consent_grants" ADD CONSTRAINT "consent_grants_policy_version_positive"
63
+ CHECK ("policy_version" IS NULL OR "policy_version" >= 1);
64
+ ALTER TABLE "consent_grants" ADD CONSTRAINT "consent_grants_person_id_format"
65
+ CHECK ("person_id" IS NULL OR "person_id" ~ '^person_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
66
+
67
+ -- CreateTable
68
+ CREATE TABLE "consent_visitor_links" (
69
+ "id" TEXT NOT NULL DEFAULT ('cvlink_'::text || (uuidv7())::text),
70
+ "workspace_id" TEXT NOT NULL,
71
+ "visitor_id" TEXT NOT NULL,
72
+ "person_id" TEXT NOT NULL,
73
+ "source" TEXT NOT NULL,
74
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
75
+
76
+ CONSTRAINT "consent_visitor_links_pkey" PRIMARY KEY ("id")
77
+ );
78
+
79
+ -- CreateIndex
80
+ -- A repeat link is a no-op: the writer inserts and ignores a conflict here.
81
+ CREATE UNIQUE INDEX "consent_visitor_links_workspace_id_visitor_id_person_id_key" ON "consent_visitor_links"("workspace_id", "visitor_id", "person_id");
82
+
83
+ -- CreateIndex
84
+ -- A Person's linked visitors: workspace_id = $1 AND person_id = $2.
85
+ CREATE INDEX "consent_visitor_links_workspace_id_person_id_idx" ON "consent_visitor_links"("workspace_id", "person_id");
86
+
87
+ -- ADR-0031 rule 3 — consent_visitor_links: cvlink_ (registered in
88
+ -- packages/ids/src/registry.ts ENTITY_PREFIX.consentVisitorLink; this
89
+ -- migration's path is added to migration-sync.test.ts's PK_CHECK_MIGRATIONS).
90
+ -- Each reference column carries the format CHECK of the entity it names.
91
+ ALTER TABLE "consent_visitor_links" ALTER COLUMN "id" TYPE text COLLATE "C";
92
+ ALTER TABLE "consent_visitor_links" ALTER COLUMN "id" SET DEFAULT ('cvlink_'::text || (uuidv7())::text);
93
+ ALTER TABLE "consent_visitor_links" ADD CONSTRAINT "consent_visitor_links_id_format" CHECK ("id" ~ '^cvlink_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
94
+ ALTER TABLE "consent_visitor_links" ADD CONSTRAINT "consent_visitor_links_workspace_id_format" CHECK ("workspace_id" ~ '^wksp_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
95
+ ALTER TABLE "consent_visitor_links" ADD CONSTRAINT "consent_visitor_links_person_id_format" CHECK ("person_id" ~ '^person_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
96
+ -- A visitor id is a random version-4 UUID the site's own server minted.
97
+ ALTER TABLE "consent_visitor_links" ADD CONSTRAINT "consent_visitor_links_visitor_id_format" CHECK ("visitor_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
98
+ ALTER TABLE "consent_visitor_links" ADD CONSTRAINT "consent_visitor_links_source_known"
99
+ CHECK ("source" IN ('magnet', 'api', 'account_settings'));
100
+
101
+ -- SEC-8438-7 — append-only, enforced. One function, three triggers per table.
102
+ CREATE FUNCTION "consent_ledger_append_only"() RETURNS trigger
103
+ LANGUAGE plpgsql AS $$
104
+ BEGIN
105
+ RAISE EXCEPTION '% is append-only', TG_TABLE_NAME
106
+ USING ERRCODE = 'restrict_violation';
107
+ END;
108
+ $$;
109
+
110
+ CREATE TRIGGER "consent_grants_no_update" BEFORE UPDATE ON "consent_grants"
111
+ FOR EACH ROW EXECUTE FUNCTION "consent_ledger_append_only"();
112
+ CREATE TRIGGER "consent_grants_no_delete" BEFORE DELETE ON "consent_grants"
113
+ FOR EACH ROW EXECUTE FUNCTION "consent_ledger_append_only"();
114
+ CREATE TRIGGER "consent_grants_no_truncate" BEFORE TRUNCATE ON "consent_grants"
115
+ FOR EACH STATEMENT EXECUTE FUNCTION "consent_ledger_append_only"();
116
+
117
+ CREATE TRIGGER "consent_visitor_links_no_update" BEFORE UPDATE ON "consent_visitor_links"
118
+ FOR EACH ROW EXECUTE FUNCTION "consent_ledger_append_only"();
119
+ CREATE TRIGGER "consent_visitor_links_no_delete" BEFORE DELETE ON "consent_visitor_links"
120
+ FOR EACH ROW EXECUTE FUNCTION "consent_ledger_append_only"();
121
+ CREATE TRIGGER "consent_visitor_links_no_truncate" BEFORE TRUNCATE ON "consent_visitor_links"
122
+ FOR EACH STATEMENT EXECUTE FUNCTION "consent_ledger_append_only"();
@@ -0,0 +1,231 @@
1
+ -- #8435 — contact details on the client record (spec
2
+ -- docs/specs/8435-contact-details-on-the-client-spec.md D1, D2).
3
+ --
4
+ -- people (13 columns) — given name, family name, an E.164 telephone, the
5
+ -- magnet's six-part address, a company name, a job title,
6
+ -- and the confirmation pair (who last saved the contact by
7
+ -- hand, and when). Every column is nullable and has no
8
+ -- default, so Postgres changes only the catalog.
9
+ -- callbacks.person_id, subscribers.person_id — the Person a request or a
10
+ -- subscription belongs to: a composite foreign key onto
11
+ -- people(id, workspace_id), the #7877 shape, so "a Person
12
+ -- of the row's own workspace" is a database fact. NULL is
13
+ -- not checked (MATCH SIMPLE).
14
+ --
15
+ -- PURELY ADDITIVE, DDL ONLY. No existing row's values change here: the
16
+ -- backfill is the next migration, 20261014121000_person_contact_backfill,
17
+ -- split out so its row updates never run under the exclusive locks these
18
+ -- ALTER TABLEs take. Prisma runs this file as one transaction, so each ALTER
19
+ -- TABLE's ACCESS EXCLUSIVE lock on "people", "callbacks" and "subscribers"
20
+ -- is held until the file commits. Every CHECK and foreign key below is added
21
+ -- NOT VALID and then VALIDATEd over an all-NULL column or a table with no
22
+ -- person_id yet, and none of the three is the large "leads" table; the window
23
+ -- is accepted, as #852 accepted the same on "leads" (SEC-852-E, SEC-8435-C).
24
+ --
25
+ -- Rollout: deploy this migration BEFORE the API code that writes the columns;
26
+ -- code without them fails every callback and subscription write.
27
+ --
28
+ -- Rollback: ALTER TABLE "callbacks" DROP CONSTRAINT "callbacks_person_fk",
29
+ -- DROP COLUMN "person_id"; ALTER TABLE "subscribers" DROP CONSTRAINT
30
+ -- "subscribers_person_fk", DROP COLUMN "person_id"; ALTER TABLE "people"
31
+ -- DROP COLUMN "given_name", DROP COLUMN "family_name", DROP COLUMN
32
+ -- "telephone", DROP COLUMN "address_line1", DROP COLUMN "address_line2",
33
+ -- DROP COLUMN "address_city", DROP COLUMN "address_region", DROP COLUMN
34
+ -- "address_postal_code", DROP COLUMN "address_country", DROP COLUMN
35
+ -- "company_name", DROP COLUMN "job_title", DROP COLUMN "contact_confirmed_at",
36
+ -- DROP COLUMN "contact_confirmed_by"; (the indexes and CHECKs go with them).
37
+
38
+ -- AlterTable
39
+ ALTER TABLE "people" ADD COLUMN "address_city" VARCHAR(60),
40
+ ADD COLUMN "address_country" CHAR(2),
41
+ ADD COLUMN "address_line1" VARCHAR(100),
42
+ ADD COLUMN "address_line2" VARCHAR(60),
43
+ ADD COLUMN "address_postal_code" VARCHAR(20),
44
+ ADD COLUMN "address_region" VARCHAR(40),
45
+ ADD COLUMN "company_name" VARCHAR(200),
46
+ ADD COLUMN "contact_confirmed_at" TIMESTAMP(3),
47
+ ADD COLUMN "contact_confirmed_by" VARCHAR(16),
48
+ ADD COLUMN "family_name" VARCHAR(100),
49
+ ADD COLUMN "given_name" VARCHAR(100),
50
+ ADD COLUMN "job_title" VARCHAR(100),
51
+ ADD COLUMN "telephone" VARCHAR(16);
52
+
53
+ -- AlterTable
54
+ ALTER TABLE "callbacks" ADD COLUMN "person_id" TEXT;
55
+
56
+ -- AlterTable
57
+ ALTER TABLE "subscribers" ADD COLUMN "person_id" TEXT;
58
+
59
+ -- CreateIndex
60
+ CREATE INDEX "callbacks_person_id_idx" ON "callbacks"("person_id");
61
+
62
+ -- CreateIndex
63
+ CREATE INDEX "subscribers_person_id_idx" ON "subscribers"("person_id");
64
+
65
+ -- A stored telephone is E.164 (the form the phone field posts) or NULL.
66
+ ALTER TABLE "people" ADD CONSTRAINT "people_telephone_e164"
67
+ CHECK ("telephone" IS NULL OR "telephone" ~ '^\+[1-9][0-9]{6,14}$') NOT VALID;
68
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_telephone_e164";
69
+
70
+ -- The country is the upper-case ISO 3166-1 alpha-2 code.
71
+ ALTER TABLE "people" ADD CONSTRAINT "people_address_country_format"
72
+ CHECK ("address_country" IS NULL OR "address_country" ~ '^[A-Z]{2}$') NOT VALID;
73
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_address_country_format";
74
+
75
+ -- An address is stored whole or not at all: all six parts NULL, or every
76
+ -- part but the optional second line present.
77
+ ALTER TABLE "people" ADD CONSTRAINT "people_address_complete"
78
+ CHECK (
79
+ ("address_line1" IS NULL AND "address_line2" IS NULL AND "address_city" IS NULL AND "address_region" IS NULL AND "address_postal_code" IS NULL AND "address_country" IS NULL)
80
+ OR
81
+ ("address_line1" IS NOT NULL AND "address_city" IS NOT NULL AND "address_region" IS NOT NULL AND "address_postal_code" IS NOT NULL AND "address_country" IS NOT NULL)
82
+ ) NOT VALID;
83
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_address_complete";
84
+
85
+ -- The confirmation pair is written together, and the actor is one of two.
86
+ ALTER TABLE "people" ADD CONSTRAINT "people_contact_confirmed"
87
+ CHECK (
88
+ ("contact_confirmed_at" IS NULL AND "contact_confirmed_by" IS NULL)
89
+ OR
90
+ ("contact_confirmed_at" IS NOT NULL AND "contact_confirmed_by" IS NOT NULL AND "contact_confirmed_by" IN ('operator', 'client'))
91
+ ) NOT VALID;
92
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_contact_confirmed";
93
+
94
+ -- The two new reference columns carry the person_ format CHECK (the #852
95
+ -- shape), added NOT VALID and then validated over an all-NULL column.
96
+ ALTER TABLE "callbacks" ADD CONSTRAINT "callbacks_person_id_format" CHECK ("person_id" ~ '^person_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;
97
+ ALTER TABLE "callbacks" VALIDATE CONSTRAINT "callbacks_person_id_format";
98
+ ALTER TABLE "subscribers" ADD CONSTRAINT "subscribers_person_id_format" CHECK ("person_id" ~ '^person_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;
99
+ ALTER TABLE "subscribers" VALIDATE CONSTRAINT "subscribers_person_id_format";
100
+
101
+ -- AddForeignKey
102
+ -- A callback / subscriber names a Person of ITS OWN workspace; deleting a
103
+ -- Person with one is refused (the pieces_person_fk shape, #7877).
104
+ ALTER TABLE "callbacks" ADD CONSTRAINT "callbacks_person_fk" FOREIGN KEY ("person_id", "workspace_id") REFERENCES "people"("id", "workspace_id") ON DELETE RESTRICT ON UPDATE CASCADE NOT VALID;
105
+ ALTER TABLE "callbacks" VALIDATE CONSTRAINT "callbacks_person_fk";
106
+ ALTER TABLE "subscribers" ADD CONSTRAINT "subscribers_person_fk" FOREIGN KEY ("person_id", "workspace_id") REFERENCES "people"("id", "workspace_id") ON DELETE RESTRICT ON UPDATE CASCADE NOT VALID;
107
+ ALTER TABLE "subscribers" VALIDATE CONSTRAINT "subscribers_person_fk";
108
+
109
+ -- ===== #8435 contact backfill (idempotent; runs after the DDL above) =====
110
+ -- #8435 — the contact backfill (spec
111
+ -- docs/specs/8435-contact-details-on-the-client-spec.md D2).
112
+ --
113
+ -- Gives every newsletter subscriber and every callback that carries a
114
+ -- storable email a Person, stamps subscribers.person_id and
115
+ -- callbacks.person_id, and fills a Person's blank telephone from the oldest
116
+ -- callback phone that is already E.164 once spaces and punctuation are
117
+ -- removed. Set-based and idempotent: every insert is ON CONFLICT DO NOTHING
118
+ -- and every update is guarded by IS NULL, so running this text twice changes
119
+ -- nothing the first run wrote.
120
+ --
121
+ --
122
+ -- Normalization — the SQL twin of apps/api/src/services/person.ts's
123
+ -- normalizePersonEmail / isStorablePersonEmail (#852's expressions verbatim):
124
+ -- N(x) = lower(btrim(x, E' \t\n\r\f\x0B') COLLATE "C")
125
+ -- (\x0B is vertical tab; an E-string has no \v escape — E'\v'
126
+ -- is the letter v, which would strip the v of every .dev)
127
+ -- VALID(e) = e ~ '^[!-?A-~]+@[!-?A-~]+$' AND length(e) <= 254
128
+ -- NAME(x) = C0/C1 controls and bidi controls removed, trimmed, cut to
129
+ -- 200 characters; empty → NULL
130
+ -- A row whose email is not VALID makes no Person and keeps person_id NULL.
131
+ --
132
+ -- A callback's email is its payload.email when that is a JSON string and
133
+ -- VALID, else its buyer_email when VALID — the order the live code links in
134
+ -- (capture first, the confirm step only when capture left it NULL;
135
+ -- SEC-8435-G).
136
+ --
137
+ -- Rollback: nothing to undo on its own — dropping 20261014120000_person_contact's
138
+ -- columns removes the stamps and the telephones this wrote; the Persons it
139
+ -- created are ordinary Persons and are left in place.
140
+
141
+ -- 1. Subscribers, oldest first: one Person per (workspace, normalized email).
142
+ INSERT INTO "people" ("workspace_id", "email", "created_at", "updated_at")
143
+ SELECT DISTINCT ON (s."workspace_id", lower(btrim(s."email", E' \t\n\r\f\x0B') COLLATE "C"))
144
+ s."workspace_id",
145
+ lower(btrim(s."email", E' \t\n\r\f\x0B') COLLATE "C"),
146
+ s."created_at",
147
+ now()
148
+ FROM "subscribers" s
149
+ WHERE lower(btrim(s."email", E' \t\n\r\f\x0B') COLLATE "C") ~ '^[!-?A-~]+@[!-?A-~]+$'
150
+ AND length(lower(btrim(s."email", E' \t\n\r\f\x0B') COLLATE "C")) <= 254
151
+ ORDER BY s."workspace_id", lower(btrim(s."email", E' \t\n\r\f\x0B') COLLATE "C"), s."created_at" ASC, s."id" ASC
152
+ ON CONFLICT ("workspace_id", "email") DO NOTHING;
153
+
154
+ -- 2. Callbacks, oldest first: one Person per (workspace, normalized email),
155
+ -- named from the callback's own name. A Person a lead or a subscriber
156
+ -- already made keeps its name and created_at (ON CONFLICT DO NOTHING).
157
+ INSERT INTO "people" ("workspace_id", "email", "name", "created_at", "updated_at")
158
+ SELECT DISTINCT ON (ce."workspace_id", ce."email_n")
159
+ ce."workspace_id",
160
+ ce."email_n",
161
+ NULLIF(left(btrim(regexp_replace(ce."name", '[\x01-\x1F\x7F-\x9F‎‏‪-‮⁦-⁩]', '', 'g')), 200), ''),
162
+ ce."created_at",
163
+ now()
164
+ FROM (
165
+ SELECT c."id", c."workspace_id", c."name", c."phone", c."created_at",
166
+ (
167
+ SELECT v."e"
168
+ FROM (VALUES
169
+ (1, lower(btrim(CASE WHEN jsonb_typeof(c."payload" -> 'email') = 'string' THEN c."payload" ->> 'email' END, E' \t\n\r\f\x0B') COLLATE "C")),
170
+ (2, lower(btrim(c."buyer_email", E' \t\n\r\f\x0B') COLLATE "C"))
171
+ ) v("ord", "e")
172
+ WHERE v."e" ~ '^[!-?A-~]+@[!-?A-~]+$' AND length(v."e") <= 254
173
+ ORDER BY v."ord"
174
+ LIMIT 1
175
+ ) AS "email_n"
176
+ FROM "callbacks" c
177
+ ) ce
178
+ WHERE ce."email_n" IS NOT NULL
179
+ ORDER BY ce."workspace_id", ce."email_n", ce."created_at" ASC, ce."id" ASC
180
+ ON CONFLICT ("workspace_id", "email") DO NOTHING;
181
+
182
+ -- 3. Stamps: every subscriber and callback with a storable email points at
183
+ -- its workspace's Person; a row already stamped is left alone.
184
+ UPDATE "subscribers"
185
+ SET "person_id" = p."id"
186
+ FROM "people" p
187
+ WHERE "subscribers"."person_id" IS NULL
188
+ AND p."workspace_id" = "subscribers"."workspace_id"
189
+ AND p."email" = lower(btrim("subscribers"."email", E' \t\n\r\f\x0B') COLLATE "C");
190
+
191
+ UPDATE "callbacks"
192
+ SET "person_id" = p."id"
193
+ FROM (
194
+ SELECT c."id" AS "callback_id", c."workspace_id",
195
+ (
196
+ SELECT v."e"
197
+ FROM (VALUES
198
+ (1, lower(btrim(CASE WHEN jsonb_typeof(c."payload" -> 'email') = 'string' THEN c."payload" ->> 'email' END, E' \t\n\r\f\x0B') COLLATE "C")),
199
+ (2, lower(btrim(c."buyer_email", E' \t\n\r\f\x0B') COLLATE "C"))
200
+ ) v("ord", "e")
201
+ WHERE v."e" ~ '^[!-?A-~]+@[!-?A-~]+$' AND length(v."e") <= 254
202
+ ORDER BY v."ord"
203
+ LIMIT 1
204
+ ) AS "email_n"
205
+ FROM "callbacks" c
206
+ WHERE c."person_id" IS NULL
207
+ ) ce
208
+ JOIN "people" p ON p."workspace_id" = ce."workspace_id" AND p."email" = ce."email_n"
209
+ WHERE "callbacks"."id" = ce."callback_id"
210
+ AND "callbacks"."person_id" IS NULL;
211
+
212
+ -- 4. Telephone: for an uncurated Person (no linked user, never confirmed by
213
+ -- hand — the rule a capture obeys, D4) with no telephone, the oldest
214
+ -- stamped callback's phone with spaces and punctuation removed, when that
215
+ -- is E.164. A national-format phone fills nothing.
216
+ UPDATE "people" p
217
+ SET "telephone" = c."tel",
218
+ "updated_at" = now()
219
+ FROM (
220
+ SELECT DISTINCT ON (cb."person_id")
221
+ cb."person_id",
222
+ regexp_replace(cb."phone", '[ ().-]', '', 'g') AS "tel"
223
+ FROM "callbacks" cb
224
+ WHERE cb."person_id" IS NOT NULL
225
+ AND regexp_replace(cb."phone", '[ ().-]', '', 'g') ~ '^\+[1-9][0-9]{6,14}$'
226
+ ORDER BY cb."person_id", cb."created_at" ASC, cb."id" ASC
227
+ ) c
228
+ WHERE p."id" = c."person_id"
229
+ AND p."telephone" IS NULL
230
+ AND p."user_id" IS NULL
231
+ AND p."contact_confirmed_at" IS NULL;
@@ -0,0 +1,77 @@
1
+ -- #8514 — the client record's private notes (spec
2
+ -- docs/specs/8514-redesign-the-person-record-page-spec.md D1, D2).
3
+ --
4
+ -- people (4 columns) — the team's one note on a client (never served to the
5
+ -- client), who last saved it (a user id of the auth
6
+ -- namespace, no foreign key — ADR 0009, the
7
+ -- piece_versions.delivered_by precedent), when, and which
8
+ -- agent when an agent saved it. Every column is nullable
9
+ -- and has no default, so Postgres changes only the catalog.
10
+ --
11
+ -- DDL first, then one data statement (D2b, below the marker): the DDL adds
12
+ -- columns and CHECKs only; the data half removes inert client grants from
13
+ -- agents of members. One directory, per the one-migration-per-milestone
14
+ -- check (the #8435 person_contact shape). Prisma runs this file as one
15
+ -- transaction; each CHECK below is added NOT VALID and then VALIDATEd over an
16
+ -- all-NULL column, and the data half touches "agents" alone.
17
+ --
18
+ -- Rollout: deploy this migration BEFORE the API code that reads and writes the
19
+ -- notes and gives members the client rows; code without the columns fails
20
+ -- every notes read, and code before the grant reset would switch the inert
21
+ -- grants on (SEC-8514-B).
22
+ --
23
+ -- Rollback: ALTER TABLE "people" DROP COLUMN "notes", DROP COLUMN
24
+ -- "notes_updated_at", DROP COLUMN "notes_updated_by", DROP COLUMN
25
+ -- "notes_updated_by_agent"; (the CHECKs go with them). The grant reset needs
26
+ -- none: every grant it removes was inert.
27
+
28
+ -- AlterTable
29
+ ALTER TABLE "people" ADD COLUMN "notes" VARCHAR(5000),
30
+ ADD COLUMN "notes_updated_at" TIMESTAMP(3),
31
+ ADD COLUMN "notes_updated_by" TEXT,
32
+ ADD COLUMN "notes_updated_by_agent" TEXT;
33
+
34
+ -- The editor is a user id of the auth namespace (the delivered_by shape).
35
+ ALTER TABLE "people" ADD CONSTRAINT "people_notes_updated_by_format"
36
+ CHECK ("notes_updated_by" IS NULL OR "notes_updated_by" ~ '^user_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;
37
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_notes_updated_by_format";
38
+
39
+ -- The agent, when one saved it, is an agent id (the agents_id_format shape).
40
+ ALTER TABLE "people" ADD CONSTRAINT "people_notes_updated_by_agent_format"
41
+ CHECK ("notes_updated_by_agent" IS NULL OR "notes_updated_by_agent" ~ '^agent_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;
42
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_notes_updated_by_agent_format";
43
+
44
+ -- Who and when are written together.
45
+ ALTER TABLE "people" ADD CONSTRAINT "people_notes_edit_pair"
46
+ CHECK (("notes_updated_at" IS NULL) = ("notes_updated_by" IS NULL)) NOT VALID;
47
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_notes_edit_pair";
48
+
49
+ -- An agent's save always names the agent's person.
50
+ ALTER TABLE "people" ADD CONSTRAINT "people_notes_agent_has_person"
51
+ CHECK ("notes_updated_by_agent" IS NULL OR "notes_updated_by" IS NOT NULL) NOT VALID;
52
+ ALTER TABLE "people" VALIDATE CONSTRAINT "people_notes_agent_has_person";
53
+
54
+ -- ===== #8514 D2b member agent grant reset (data only; runs after the DDL above) =====
55
+ -- #8514 — dormant client grants cleared from agents of members (spec
56
+ -- docs/specs/8514-redesign-the-person-record-page-spec.md D2b, SEC-8514-B).
57
+ --
58
+ -- Until #8514 a member held neither people-read nor member-pieces-manage, so
59
+ -- the agent clamp (`can(personTenant.role, p)`) dropped either grant stored on
60
+ -- a member's agent: it was inert. #8514 gives members both by role, and the
61
+ -- clamp would then switch those stored grants on with no admin action. This
62
+ -- removes them first, so a member's agent holds either only once an owner or
63
+ -- admin grants it after the deploy.
64
+ --
65
+ -- DATA ONLY. Changes no effective permission at the time it runs (every grant
66
+ -- it removes is inert). Idempotent: a second run matches no row.
67
+ --
68
+ -- Rollout: in the same deploy as, and BEFORE, the #8514 API code.
69
+ --
70
+ -- Rollback: none needed — every removed grant was inert.
71
+
72
+ UPDATE "agents" a
73
+ SET "grants" = array_remove(array_remove(a."grants", 'people-read'), 'member-pieces-manage')
74
+ FROM "memberships" m
75
+ WHERE m."id" = a."responsible_membership_id"
76
+ AND m."role" = 'member'
77
+ AND a."grants" && ARRAY['people-read', 'member-pieces-manage']::text[];