create-ailk 0.14.0 → 0.16.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 (184) hide show
  1. package/README.md +124 -0
  2. package/component-catalog.json +3 -3
  3. package/dist/add-module.d.ts +7 -0
  4. package/dist/add-module.js +80 -3
  5. package/dist/add-route.js +26 -2
  6. package/dist/adopt.d.ts +74 -0
  7. package/dist/adopt.js +314 -0
  8. package/dist/apply-design.d.ts +12 -1
  9. package/dist/apply-design.js +36 -4
  10. package/dist/cli.js +103 -3
  11. package/dist/derive-architecture.d.ts +37 -2
  12. package/dist/derive-architecture.js +92 -7
  13. package/dist/design-package.js +3 -2
  14. package/dist/index.d.ts +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/lib/chrome-readers.d.ts +21 -0
  17. package/dist/lib/chrome-readers.js +100 -0
  18. package/dist/lib/declared-env.d.ts +142 -0
  19. package/dist/lib/declared-env.js +985 -0
  20. package/dist/lib/env-catalog.d.ts +17 -0
  21. package/dist/lib/env-catalog.js +234 -0
  22. package/dist/lib/extract-module-bundle.d.ts +20 -0
  23. package/dist/lib/extract-module-bundle.js +53 -6
  24. package/dist/lib/license-key-files.d.ts +6 -1
  25. package/dist/lib/license-key-files.js +9 -4
  26. package/dist/lib/module-tier.d.ts +2 -0
  27. package/dist/lib/module-tier.js +4 -0
  28. package/dist/module-architecture.d.ts +9 -0
  29. package/dist/module-architecture.js +82 -0
  30. package/dist/parse-args.d.ts +27 -0
  31. package/dist/parse-args.js +89 -0
  32. package/dist/programmatic.d.ts +28 -0
  33. package/dist/programmatic.js +181 -11
  34. package/dist/seed-flows.d.ts +65 -0
  35. package/dist/seed-flows.js +350 -0
  36. package/dist/site-chrome.d.ts +4 -0
  37. package/dist/site-chrome.js +34 -3
  38. package/dist/site-manifest.d.ts +55 -5
  39. package/dist/site-manifest.js +121 -12
  40. package/dist/site-roster.d.ts +13 -0
  41. package/dist/site-roster.js +22 -8
  42. package/dist/spoke-checkout.d.ts +42 -0
  43. package/dist/spoke-checkout.js +359 -0
  44. package/dist/surfaces.js +7 -0
  45. package/dist/sync-routes.js +29 -5
  46. package/dist/topology.d.ts +246 -0
  47. package/dist/topology.js +942 -0
  48. package/package.json +3 -3
  49. package/site-templates/designs/minimalism/DESIGN.md +3 -3
  50. package/templates/.env.example +10 -0
  51. package/templates/apps/api/CLAUDE.md +21 -4
  52. package/templates/apps/api/package.json +1 -0
  53. package/templates/apps/api/src/__tests__/factories/agent-caller.ts +5 -1
  54. package/templates/apps/api/src/__tests__/factories/in-memory-prisma.ts +95 -16
  55. package/templates/apps/api/src/__tests__/openapi-keyless-hub.test.ts +122 -0
  56. package/templates/apps/api/src/__tests__/support/hub-sign-in-fake-db.ts +362 -0
  57. package/templates/apps/api/src/bin/spokes.ts +62 -1
  58. package/templates/apps/api/src/config/__tests__/hub-require-spoke-key.test.ts +75 -0
  59. package/templates/apps/api/src/config/index.ts +35 -0
  60. package/templates/apps/api/src/lib/__mocks__/prisma.ts +99 -0
  61. package/templates/apps/api/src/lib/__tests__/agent-store.test.ts +114 -1
  62. package/templates/apps/api/src/lib/__tests__/deliverable-asset-store.test.ts +66 -5
  63. package/templates/apps/api/src/lib/__tests__/hub-sign-in-store.test.ts +209 -0
  64. package/templates/apps/api/src/lib/__tests__/site.test.ts +54 -0
  65. package/templates/apps/api/src/lib/__tests__/spoke-store.test.ts +20 -0
  66. package/templates/apps/api/src/lib/agent-store.ts +95 -3
  67. package/templates/apps/api/src/lib/deliverable-asset-store.ts +24 -5
  68. package/templates/apps/api/src/lib/hub-sign-in-store.ts +419 -0
  69. package/templates/apps/api/src/lib/site.ts +37 -0
  70. package/templates/apps/api/src/lib/spoke-store.ts +41 -3
  71. package/templates/apps/api/src/middleware/__tests__/auth.bearer-path.test.ts +4 -0
  72. package/templates/apps/api/src/middleware/__tests__/auth.hub-session-path.test.ts +310 -0
  73. package/templates/apps/api/src/middleware/__tests__/default-tenant.test.ts +22 -0
  74. package/templates/apps/api/src/middleware/auth.ts +129 -0
  75. package/templates/apps/api/src/openapi/__tests__/openapi.test.ts +23 -0
  76. package/templates/apps/api/src/openapi/spec.ts +38 -2
  77. package/templates/apps/api/src/routes/auth/__tests__/hub-sign-in.test.ts +483 -0
  78. package/templates/apps/api/src/routes/auth/hub-sign-in.ts +201 -0
  79. package/templates/apps/api/src/routes/checkout/__tests__/sessions.test.ts +50 -2
  80. package/templates/apps/api/src/routes/checkout/sessions.ts +7 -0
  81. package/templates/apps/api/src/routes/leads/__tests__/index.test.ts +282 -0
  82. package/templates/apps/api/src/routes/leads/index.ts +69 -6
  83. package/templates/apps/api/src/routes/webhooks/README.md +39 -0
  84. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-flow-checkout.test.ts +105 -0
  85. package/templates/apps/api/src/routes/webhooks/__tests__/stripe-site-filter.test.ts +366 -0
  86. package/templates/apps/api/src/routes/webhooks/stripe.ts +133 -2
  87. package/templates/apps/api/src/server.ts +105 -0
  88. package/templates/apps/api/src/services/__tests__/deliverable-fulfillment.test.ts +4 -4
  89. package/templates/apps/api/src/services/__tests__/hub-sign-in.test.ts +854 -0
  90. package/templates/apps/api/src/services/__tests__/lead-routing.test.ts +492 -0
  91. package/templates/apps/api/src/services/__tests__/person.test.ts +553 -0
  92. package/templates/apps/api/src/services/default-tenant.ts +41 -7
  93. package/templates/apps/api/src/services/hub-sign-in.ts +471 -0
  94. package/templates/apps/api/src/services/lead-routing.ts +278 -30
  95. package/templates/apps/api/src/services/person.ts +541 -0
  96. package/templates/apps/api/src/services/public-site-resolver.ts +48 -0
  97. package/templates/apps/mcp/__tests__/index.test.ts +5 -5
  98. package/templates/apps/mcp/src/index.ts +6 -4
  99. package/templates/apps/mcp/src/lib/content-adapter.ts +2 -2
  100. package/templates/apps/mcp/src/lib/topology.generated.ts +24 -0
  101. package/templates/apps/web/.env.example +58 -5
  102. package/templates/apps/web/CLAUDE.md +1 -0
  103. package/templates/apps/web/app/[locale]/(auth)/sign-in/next-path.ts +0 -0
  104. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/hub-mode.test.tsx +206 -0
  105. package/templates/apps/web/app/[locale]/(authed)/account/__tests__/page.test.tsx +256 -3
  106. package/templates/apps/web/app/[locale]/(authed)/account/account-data.ts +5 -8
  107. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/__tests__/route.test.ts +205 -0
  108. package/templates/apps/web/app/[locale]/(authed)/account/inbox/message/[id]/file/route.ts +82 -0
  109. package/templates/apps/web/app/[locale]/(authed)/account/settings/page.tsx +98 -29
  110. package/templates/apps/web/app/[locale]/(authed)/account/support-actions.ts +6 -3
  111. package/templates/apps/web/app/[locale]/(authed)/layout.tsx +19 -101
  112. package/templates/apps/web/app/[locale]/(authed)/signed-out-gate.generated.tsx +90 -0
  113. package/templates/apps/web/app/[locale]/[slug]/[detail]/__tests__/page.test.tsx +3 -0
  114. package/templates/apps/web/app/[locale]/[slug]/__tests__/page.test.tsx +3 -0
  115. package/templates/apps/web/app/[locale]/contact/__tests__/page-renderer-migration.test.tsx +66 -14
  116. package/templates/apps/web/app/[locale]/contact/__tests__/site-contact-lines.test.ts +105 -11
  117. package/templates/apps/web/app/[locale]/contact/site-contact-lines.ts +12 -8
  118. package/templates/apps/web/app/[locale]/layout.tsx +83 -18
  119. package/templates/apps/web/app/[locale]/newsletter/__tests__/page.test.tsx +3 -0
  120. package/templates/apps/web/app/[locale]/projects/__tests__/page-renderer-migration.test.tsx +5 -2
  121. package/templates/apps/web/app/[locale]/thanks/[slug]/__tests__/page.test.tsx +3 -0
  122. package/templates/apps/web/app/api/auth/hub/authorize/__tests__/route.test.ts +295 -0
  123. package/templates/apps/web/app/api/auth/hub/authorize/route.ts +156 -0
  124. package/templates/apps/web/app/api/hub-session/__tests__/routes.test.ts +341 -0
  125. package/templates/apps/web/app/api/hub-session/callback/route.ts +168 -0
  126. package/templates/apps/web/app/api/hub-session/sign-in/route.ts +76 -0
  127. package/templates/apps/web/app/api/hub-session/sign-out/route.ts +63 -0
  128. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +104 -1
  129. package/templates/apps/web/app/openapi.json/route.ts +72 -7
  130. package/templates/apps/web/auth.ts +29 -2
  131. package/templates/apps/web/components/sign-out-trigger.tsx +20 -1
  132. package/templates/apps/web/components/signed-in-nav.tsx +17 -3
  133. package/templates/apps/web/instrumentation.ts +7 -4
  134. package/templates/apps/web/lib/__tests__/account-config.test.ts +5 -2
  135. package/templates/apps/web/lib/__tests__/closing-footer-path.test.ts +96 -0
  136. package/templates/apps/web/lib/__tests__/listings-config.test.ts +83 -0
  137. package/templates/apps/web/lib/__tests__/listings.test.tsx +49 -0
  138. package/templates/apps/web/lib/__tests__/meeting-slugs.test.ts +49 -1
  139. package/templates/apps/web/lib/__tests__/relay.test.ts +317 -0
  140. package/templates/apps/web/lib/__tests__/site-brand.test.ts +52 -0
  141. package/templates/apps/web/lib/account-config.ts +130 -1
  142. package/templates/apps/web/lib/api-origin.generated.ts +11 -0
  143. package/templates/apps/web/lib/closing-footer-path.ts +50 -0
  144. package/templates/apps/web/lib/hub-session/__tests__/hub-session.test.ts +262 -0
  145. package/templates/apps/web/lib/hub-session/config.ts +104 -0
  146. package/templates/apps/web/lib/hub-session/index.ts +23 -0
  147. package/templates/apps/web/lib/hub-session/seal.ts +82 -0
  148. package/templates/apps/web/lib/hub-session/session.ts +180 -0
  149. package/templates/apps/web/lib/hub-session/sign-in-gate.tsx +79 -0
  150. package/templates/apps/web/lib/listings-config.ts +31 -0
  151. package/templates/apps/web/lib/listings.tsx +7 -3
  152. package/templates/apps/web/lib/meeting-slugs.ts +11 -1
  153. package/templates/apps/web/lib/next-path.ts +35 -0
  154. package/templates/apps/web/lib/relay.ts +209 -3
  155. package/templates/apps/web/lib/server-api.ts +11 -1
  156. package/templates/apps/web/lib/site-brand.tsx +22 -1
  157. package/templates/apps/web/lib/site-chrome.ts +3 -0
  158. package/templates/apps/web/lib/topology.generated.ts +33 -0
  159. package/templates/apps/web/messages/en.json +32 -3
  160. package/templates/apps/web/package.json +1 -1
  161. package/templates/database/CHANGELOG.md +51 -0
  162. package/templates/database/__tests__/agents.db.test.ts +85 -0
  163. package/templates/database/__tests__/fixtures/person-backfill.json +264 -0
  164. package/templates/database/__tests__/lead-idempotency-key.db.test.ts +92 -0
  165. package/templates/database/__tests__/member-area.db.test.ts +245 -0
  166. package/templates/database/__tests__/person.db.test.ts +584 -0
  167. package/templates/database/auth/schema.prisma +24 -0
  168. package/templates/database/config/schema.prisma +13 -0
  169. package/templates/database/inbox/schema.prisma +111 -0
  170. package/templates/database/jest.config.cjs +7 -11
  171. package/templates/database/migrations/20261008120000_user_last_workspace/migration.sql +35 -0
  172. package/templates/database/migrations/20261008130000_lead_idempotency_key/migration.sql +20 -0
  173. package/templates/database/migrations/20261009120000_agent_grants/migration.sql +33 -0
  174. package/templates/database/migrations/20261010120000_person/migration.sql +106 -0
  175. package/templates/database/migrations/20261010121000_person_backfill/migration.sql +132 -0
  176. package/templates/database/migrations/20261010130000_agent_grants_people_read/migration.sql +20 -0
  177. package/templates/database/migrations/20261011120000_member_area/migration.sql +158 -0
  178. package/templates/database/migrations/20261011130000_agent_grants_member_pieces_manage/migration.sql +21 -0
  179. package/templates/database/package.json +1 -1
  180. package/templates/database/scripts/person-backfill.sql +132 -0
  181. package/templates/database/tenancy.ts +53 -0
  182. package/templates/tools/check-declared-env.ts +37 -0
  183. package/templates/tools/declared-env.ts +1163 -0
  184. package/versions.json +35 -34
@@ -0,0 +1,158 @@
1
+ -- #7877 — the member area contract (spec
2
+ -- docs/specs/7877-the-member-area-contract-a-spec.md D1, D2, D3).
3
+ --
4
+ -- pieces (inbox) — one deliverable for one client: a title, a stage
5
+ -- drawn from the workspace's declared list, a
6
+ -- needs-client flag. Written only through
7
+ -- apps/api's tenantDb(tenant).memberArea.
8
+ -- interactions (inbox) — one outbound message on the 'member' channel to
9
+ -- one client, optionally carrying a workspace
10
+ -- library asset. The original CRM spec's
11
+ -- Interaction table cut to one channel and one
12
+ -- direction; an inbound reply is a later second
13
+ -- direction value on this table.
14
+ -- workspace_piece_stages (config) — a workspace's declared piece stages,
15
+ -- in order, one row per workspace. No row means the
16
+ -- product default, which lives in apps/api only.
17
+ -- people_id_workspace_id_key — a unique index over a pair the PK already
18
+ -- makes unique: the target of the composite
19
+ -- (person_id, workspace_id) foreign keys, so "a
20
+ -- Person of the same workspace" is a database fact.
21
+ --
22
+ -- Both foreign keys stay inside the inbox namespace (ADR 0009 invariant 1).
23
+ -- workspace_id, asset_id, created_by and updated_by name rows of other
24
+ -- namespaces: plain columns with format CHECKs, no foreign key. Neither new
25
+ -- inbox table carries an email.
26
+ --
27
+ -- PURELY ADDITIVE, DDL ONLY: three new tables and one unique index on
28
+ -- "people". No existing row changes. The unique index builds under the
29
+ -- file's transaction, holding a SHARE lock on "people" (writes wait, reads do
30
+ -- not) for one scan of a table that is one row per client.
31
+ --
32
+ -- Rollout: deploy this migration BEFORE the API code that reads or writes
33
+ -- these tables; code without them fails every member-area read and write.
34
+ --
35
+ -- Rollback: DROP TABLE "interactions"; DROP TABLE "pieces"; DROP TABLE
36
+ -- "workspace_piece_stages"; DROP INDEX "people_id_workspace_id_key"; (the
37
+ -- indexes, foreign keys and CHECKs go with them). Safe while nothing but
38
+ -- #7877's own code reads them.
39
+
40
+ -- CreateTable
41
+ CREATE TABLE "workspace_piece_stages" (
42
+ "id" TEXT NOT NULL DEFAULT ('pstages_'::text || (uuidv7())::text),
43
+ "workspace_id" TEXT NOT NULL,
44
+ "stages" TEXT[],
45
+ "created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
46
+ "updated_at" TIMESTAMPTZ NOT NULL,
47
+
48
+ CONSTRAINT "workspace_piece_stages_pkey" PRIMARY KEY ("id")
49
+ );
50
+
51
+ -- CreateTable
52
+ CREATE TABLE "pieces" (
53
+ "id" TEXT NOT NULL DEFAULT ('piece_'::text || (uuidv7())::text),
54
+ "workspace_id" TEXT NOT NULL,
55
+ "person_id" TEXT NOT NULL,
56
+ "title" VARCHAR(200) NOT NULL,
57
+ "stage" VARCHAR(40) NOT NULL,
58
+ "needs_client" BOOLEAN NOT NULL DEFAULT false,
59
+ "updated_by" TEXT NOT NULL,
60
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
61
+ "updated_at" TIMESTAMP(3) NOT NULL,
62
+
63
+ CONSTRAINT "pieces_pkey" PRIMARY KEY ("id")
64
+ );
65
+
66
+ -- CreateTable
67
+ CREATE TABLE "interactions" (
68
+ "id" TEXT NOT NULL DEFAULT ('intx_'::text || (uuidv7())::text),
69
+ "workspace_id" TEXT NOT NULL,
70
+ "person_id" TEXT NOT NULL,
71
+ "channel" VARCHAR(16) NOT NULL,
72
+ "direction" VARCHAR(16) NOT NULL,
73
+ "subject" VARCHAR(200) NOT NULL,
74
+ "body" TEXT NOT NULL,
75
+ "asset_id" TEXT,
76
+ "created_by" TEXT NOT NULL,
77
+ "created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
78
+ "read_at" TIMESTAMP(3),
79
+
80
+ CONSTRAINT "interactions_pkey" PRIMARY KEY ("id")
81
+ );
82
+
83
+ -- CreateIndex
84
+ -- One stage list per workspace — the WorkspaceMeetings shape.
85
+ CREATE UNIQUE INDEX "workspace_piece_stages_workspace_id_key" ON "workspace_piece_stages"("workspace_id");
86
+
87
+ -- CreateIndex
88
+ -- A client's pieces: workspace_id = $1 AND person_id = $2 ORDER BY created_at DESC.
89
+ CREATE INDEX "pieces_workspace_id_person_id_created_at_idx" ON "pieces"("workspace_id", "person_id", "created_at");
90
+
91
+ -- CreateIndex
92
+ -- A client's messages, the same read shape as pieces.
93
+ CREATE INDEX "interactions_workspace_id_person_id_created_at_idx" ON "interactions"("workspace_id", "person_id", "created_at");
94
+
95
+ -- CreateIndex
96
+ -- The public asset read's "is this asset attached to any message" count (D18).
97
+ CREATE INDEX "interactions_asset_id_idx" ON "interactions"("asset_id");
98
+
99
+ -- CreateIndex
100
+ -- Redundant with the PK; the composite foreign keys below need it as their target.
101
+ CREATE UNIQUE INDEX "people_id_workspace_id_key" ON "people"("id", "workspace_id");
102
+
103
+ -- AddForeignKey
104
+ -- A piece names a Person of ITS OWN workspace; deleting a Person with a piece is refused.
105
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_person_fk" FOREIGN KEY ("person_id", "workspace_id") REFERENCES "people"("id", "workspace_id") ON DELETE RESTRICT ON UPDATE CASCADE;
106
+
107
+ -- AddForeignKey
108
+ -- The same rule for a message.
109
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_person_fk" FOREIGN KEY ("person_id", "workspace_id") REFERENCES "people"("id", "workspace_id") ON DELETE RESTRICT ON UPDATE CASCADE;
110
+
111
+ -- ADR-0031 rule 3 — pieces: piece_, interactions: intx_,
112
+ -- workspace_piece_stages: pstages_ (registered in
113
+ -- packages/ids/src/registry.ts; this migration's path is added to
114
+ -- migration-sync.test.ts's PK_CHECK_MIGRATIONS). Each reference column
115
+ -- carries the format CHECK of the entity it names, in the person-migration
116
+ -- shape.
117
+ ALTER TABLE "pieces" ALTER COLUMN "id" TYPE text COLLATE "C";
118
+ ALTER TABLE "pieces" ALTER COLUMN "id" SET DEFAULT ('piece_'::text || (uuidv7())::text);
119
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_id_format" CHECK ("id" ~ '^piece_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
120
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_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}$');
121
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_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}$');
122
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_updated_by_format" CHECK ("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}$');
123
+
124
+ ALTER TABLE "interactions" ALTER COLUMN "id" TYPE text COLLATE "C";
125
+ ALTER TABLE "interactions" ALTER COLUMN "id" SET DEFAULT ('intx_'::text || (uuidv7())::text);
126
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_id_format" CHECK ("id" ~ '^intx_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
127
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_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}$');
128
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_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}$');
129
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_created_by_format" CHECK ("created_by" ~ '^user_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
130
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_asset_id_format" CHECK ("asset_id" ~ '^asset_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
131
+
132
+ ALTER TABLE "workspace_piece_stages" ALTER COLUMN "id" TYPE text COLLATE "C";
133
+ ALTER TABLE "workspace_piece_stages" ALTER COLUMN "id" SET DEFAULT ('pstages_'::text || (uuidv7())::text);
134
+ ALTER TABLE "workspace_piece_stages" ADD CONSTRAINT "workspace_piece_stages_id_format" CHECK ("id" ~ '^pstages_[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');
135
+ ALTER TABLE "workspace_piece_stages" ADD CONSTRAINT "workspace_piece_stages_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}$');
136
+
137
+ -- A piece's title is 1–200 characters once trimmed; a stage is a slug. Which
138
+ -- slugs a workspace accepts is its declared list, checked at write time by
139
+ -- the API — never an enum here or in packages/validation.
140
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_title_length"
141
+ CHECK (char_length(btrim("title")) BETWEEN 1 AND 200);
142
+ ALTER TABLE "pieces" ADD CONSTRAINT "pieces_stage_format"
143
+ CHECK ("stage" ~ '^[a-z0-9][a-z0-9-]{0,39}$');
144
+
145
+ -- One channel and one direction in this slice. An inbound reply widens
146
+ -- interactions_direction_allowed in its own migration.
147
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_channel_allowed"
148
+ CHECK ("channel" = 'member');
149
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_direction_allowed"
150
+ CHECK ("direction" = 'outbound');
151
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_subject_length"
152
+ CHECK (char_length(btrim("subject")) BETWEEN 1 AND 200);
153
+ ALTER TABLE "interactions" ADD CONSTRAINT "interactions_body_length"
154
+ CHECK (char_length(btrim("body")) BETWEEN 1 AND 10000);
155
+
156
+ -- A declared list holds 1–20 stages (never NULL: no row is the default).
157
+ ALTER TABLE "workspace_piece_stages" ADD CONSTRAINT "workspace_piece_stages_count"
158
+ CHECK ("stages" IS NOT NULL AND cardinality("stages") BETWEEN 1 AND 20);
@@ -0,0 +1,21 @@
1
+ -- #7878 — an agent key may be granted member-pieces-manage: a client's
2
+ -- pieces, plan and outbound messages (#7877's operator writes).
3
+ --
4
+ -- Widens the agents_grants_allowed CHECK from the six #852 permissions to
5
+ -- seven. The CHECK names the same seven as @working-theory/validation's
6
+ -- AGENT_GRANTABLE_PERMISSIONS; database/__tests__/agents.db.test.ts reads
7
+ -- this file and fails if the two lists differ (SEC-7864-G).
8
+ --
9
+ -- PURELY ADDITIVE in effect: the new CHECK admits every row the old one
10
+ -- admitted, so re-adding it cannot fail on existing data. No row changes.
11
+ --
12
+ -- Rollback: ALTER TABLE "agents" DROP CONSTRAINT "agents_grants_allowed";
13
+ -- then re-add the six-id CHECK from 20261010130000_agent_grants_people_read.
14
+ -- That re-add FAILS while any row holds member-pieces-manage — remove those
15
+ -- grants first.
16
+
17
+ ALTER TABLE "agents" DROP CONSTRAINT "agents_grants_allowed";
18
+
19
+ -- Only the seven grantable permissions may be stored.
20
+ ALTER TABLE "agents" ADD CONSTRAINT "agents_grants_allowed"
21
+ CHECK ("grants" <@ ARRAY['content-edit','content-publish','assets-write','magnets-manage','meeting-types-manage','people-read','member-pieces-manage']::TEXT[]);
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@working-theory/database",
3
- "version": "0.36.0",
3
+ "version": "0.38.0",
4
4
  "license": "Apache-2.0",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -0,0 +1,132 @@
1
+ -- #852 — the Person backfill (spec
2
+ -- docs/specs/852-person-the-per-workspace-client-spec.md D2, D4).
3
+ --
4
+ -- Fills "people" from the rows the hub already holds and stamps
5
+ -- leads.person_id and appointments.person_id, so the People list is not
6
+ -- empty on the day it ships. Set-based and idempotent: every insert is
7
+ -- ON CONFLICT DO NOTHING and every update is guarded by IS NULL, so running
8
+ -- this text twice changes nothing the first run wrote.
9
+ --
10
+ -- THE SAME TEXT, byte for byte, is database/scripts/person-backfill.sql. The
11
+ -- previous deployment keeps writing leads and appointments without a
12
+ -- person_id between this migration and the cutover to the new code; run
13
+ -- that script ONCE against the hub database after the cutover to stamp them.
14
+ -- database/__tests__/person.db.test.ts asserts the two files are identical
15
+ -- and that a second run changes no row.
16
+ --
17
+ -- Normalization — the SQL twin of apps/api/src/services/person.ts's
18
+ -- normalizePersonEmail / isStorablePersonEmail:
19
+ -- N(x) = lower(btrim(x, E' \t\n\r\f\x0B') COLLATE "C")
20
+ -- (\x0B is vertical tab; an E-string has no \v escape — E'\v'
21
+ -- is the letter v, which would strip the v of every .dev)
22
+ -- VALID(e) = e ~ '^[!-?A-~]+@[!-?A-~]+$' AND length(e) <= 254
23
+ -- NAME(x) = C0/C1 controls and bidi controls removed, trimmed, cut to
24
+ -- 200 characters; empty → NULL
25
+ -- A row whose email is not VALID makes no Person and keeps person_id NULL.
26
+ --
27
+ -- Sources, in order: leads (oldest first), then completed hub FlowCheckouts
28
+ -- through their lead (the customer id, first writer wins), then appointments
29
+ -- by attendee email. Subscriber is NOT a source; FlowSession, ProjectListing
30
+ -- and DeliverableGrant reach a Person through their lead at read time.
31
+ -- The join to "users" reads the auth namespace inside this one-off
32
+ -- statement only; it adds no foreign key (ADR 0009 invariant 1).
33
+ --
34
+ -- Rollback: nothing to undo on its own — dropping 20261010120000_person's
35
+ -- table and columns removes everything this wrote.
36
+
37
+ -- 1. Leads, oldest first: one Person per (workspace, normalized email). The
38
+ -- name is the oldest lead's payload.name when it is a JSON string.
39
+ INSERT INTO "people" ("workspace_id", "email", "name", "created_at", "updated_at")
40
+ SELECT DISTINCT ON (l."workspace_id", lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"))
41
+ l."workspace_id",
42
+ lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"),
43
+ CASE WHEN jsonb_typeof(l."payload" -> 'name') = 'string'
44
+ THEN NULLIF(left(btrim(regexp_replace(l."payload" ->> 'name', '[\x01-\x1F\x7F-\x9F\u200E\u200F\u202A-\u202E\u2066-\u2069]', '', 'g')), 200), '')
45
+ END,
46
+ l."created_at",
47
+ now()
48
+ FROM "leads" l
49
+ WHERE lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C") ~ '^[!-?A-~]+@[!-?A-~]+$'
50
+ AND length(lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C")) <= 254
51
+ ORDER BY l."workspace_id", lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"), l."created_at" ASC, l."id" ASC
52
+ ON CONFLICT ("workspace_id", "email") DO NOTHING;
53
+
54
+ -- 2. Hub FlowCheckouts, through their lead (same workspace): the oldest
55
+ -- completed checkout with a customer id writes it onto a Person that has
56
+ -- none. First writer wins — oldest by completed_at, then created_at, then id.
57
+ UPDATE "people" p
58
+ SET "billing_provider" = 'stripe',
59
+ "billing_customer_id" = c."stripe_customer_id",
60
+ "updated_at" = now()
61
+ FROM (
62
+ SELECT DISTINCT ON (fc."workspace_id", lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"))
63
+ fc."workspace_id",
64
+ lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C") AS "email",
65
+ fc."stripe_customer_id"
66
+ FROM "flow_checkouts" fc
67
+ JOIN "leads" l ON l."id" = fc."lead_id" AND l."workspace_id" = fc."workspace_id"
68
+ WHERE fc."status" = 'completed'
69
+ AND fc."stripe_customer_id" IS NOT NULL
70
+ AND fc."stripe_customer_id" <> ''
71
+ AND length(fc."stripe_customer_id") <= 255
72
+ ORDER BY fc."workspace_id", lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"),
73
+ fc."completed_at" ASC NULLS LAST, fc."created_at" ASC, fc."id" ASC
74
+ ) c
75
+ WHERE p."workspace_id" = c."workspace_id"
76
+ AND p."email" = c."email"
77
+ AND p."billing_customer_id" IS NULL;
78
+
79
+ -- 3. Appointments, by attendee email: a Person a lead already made keeps its
80
+ -- lead-derived name and created_at (ON CONFLICT DO NOTHING).
81
+ INSERT INTO "people" ("workspace_id", "email", "name", "created_at", "updated_at")
82
+ SELECT DISTINCT ON (a."workspace_id", lower(btrim(a."attendee_email", E' \t\n\r\f\x0B') COLLATE "C"))
83
+ a."workspace_id",
84
+ lower(btrim(a."attendee_email", E' \t\n\r\f\x0B') COLLATE "C"),
85
+ NULLIF(left(btrim(regexp_replace(a."attendee_name", '[\x01-\x1F\x7F-\x9F\u200E\u200F\u202A-\u202E\u2066-\u2069]', '', 'g')), 200), ''),
86
+ a."created_at",
87
+ now()
88
+ FROM "appointments" a
89
+ WHERE lower(btrim(a."attendee_email", E' \t\n\r\f\x0B') COLLATE "C") ~ '^[!-?A-~]+@[!-?A-~]+$'
90
+ AND length(lower(btrim(a."attendee_email", E' \t\n\r\f\x0B') COLLATE "C")) <= 254
91
+ ORDER BY a."workspace_id", lower(btrim(a."attendee_email", E' \t\n\r\f\x0B') COLLATE "C"), a."created_at" ASC, a."id" ASC
92
+ ON CONFLICT ("workspace_id", "email") DO NOTHING;
93
+
94
+ -- 4. Stamps: every lead and appointment with a storable email points at its
95
+ -- workspace's Person; a row already stamped is left alone.
96
+ UPDATE "leads"
97
+ SET "person_id" = p."id"
98
+ FROM "people" p
99
+ WHERE "leads"."person_id" IS NULL
100
+ AND p."workspace_id" = "leads"."workspace_id"
101
+ AND p."email" = lower(btrim("leads"."email", E' \t\n\r\f\x0B') COLLATE "C");
102
+
103
+ UPDATE "appointments"
104
+ SET "person_id" = p."id"
105
+ FROM "people" p
106
+ WHERE "appointments"."person_id" IS NULL
107
+ AND p."workspace_id" = "appointments"."workspace_id"
108
+ AND p."email" = lower(btrim("appointments"."attendee_email", E' \t\n\r\f\x0B') COLLATE "C");
109
+
110
+ -- 5. user_id, verified only: the oldest promoted lead (by promoted_at, then
111
+ -- created_at, then id) whose user is email-verified and whose verified
112
+ -- address normalizes to the Person's. An unverified or differing user is
113
+ -- never copied — the rule stampPersonUser applies to new rows.
114
+ UPDATE "people" p
115
+ SET "user_id" = c."user_id",
116
+ "updated_at" = now()
117
+ FROM (
118
+ SELECT DISTINCT ON (l."workspace_id", lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"))
119
+ l."workspace_id",
120
+ lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C") AS "email",
121
+ l."promoted_user_id" AS "user_id"
122
+ FROM "leads" l
123
+ JOIN "users" u ON u."id" = l."promoted_user_id"
124
+ WHERE l."promoted_user_id" IS NOT NULL
125
+ AND u."email_verified" = true
126
+ AND lower(btrim(u."email", E' \t\n\r\f\x0B') COLLATE "C") = lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C")
127
+ ORDER BY l."workspace_id", lower(btrim(l."email", E' \t\n\r\f\x0B') COLLATE "C"),
128
+ l."promoted_at" ASC NULLS LAST, l."created_at" ASC, l."id" ASC
129
+ ) c
130
+ WHERE p."workspace_id" = c."workspace_id"
131
+ AND p."email" = c."email"
132
+ AND p."user_id" IS NULL;
@@ -128,3 +128,56 @@ export async function resolveSentinelWorkspaceRow(
128
128
  }
129
129
  return { id: DEFAULT_WORKSPACE_ID, organizationId: workspace.organizationId };
130
130
  }
131
+
132
+ // ---------------------------------------------------------------------------
133
+ // #852 D7 — the Person timeline's pre-migration email fallback.
134
+ //
135
+ // A FlowSession or ProjectListing written before the Person backfill and
136
+ // never tied to a lead (`lead_id IS NULL`) reaches its Person only by email.
137
+ // These three SQL texts are the ONLY way that match is made: run by
138
+ // `apps/api/src/lib/tenant-db.ts`'s `people.timeline` through
139
+ // `$queryRawUnsafe(SQL, email, workspaceId, cutoff)`, and executed verbatim
140
+ // against live Postgres by `database/__tests__/person.db.test.ts` — one
141
+ // string, proven where it runs. `$n` placeholders only, never interpolation.
142
+ //
143
+ // The match is EXACT equality of the normalized column against the Person's
144
+ // stored (already-normalized) email — never Prisma's `mode: "insensitive"`,
145
+ // which compiles to ILIKE: `_`/`%` would act as wildcards and non-ASCII case
146
+ // would fold, joining another client's rows (SEC-852-B). The normalization is
147
+ // the backfill's N(x) (database/migrations/20261010121000_person_backfill).
148
+ //
149
+ // `$3` is the cutoff: `finished_at` of the backfill migration's
150
+ // `_prisma_migrations` row (`PERSON_CUTOFF_SQL`). That column is timestamptz;
151
+ // the inbox `created_at` columns are timestamp(3) holding UTC (Prisma's
152
+ // convention), so the comparison converts the cutoff to UTC wall time. Only
153
+ // rows strictly older than the cutoff qualify. Each returns ids only, at most
154
+ // 50, newest first; the caller re-reads them through its scoped findMany.
155
+ // ---------------------------------------------------------------------------
156
+
157
+ /** The `_prisma_migrations` key whose `finished_at` is the fallback cutoff. */
158
+ export const PERSON_BACKFILL_MIGRATION = "20261010121000_person_backfill";
159
+
160
+ /** `$1` = the Person's email, `$2` = workspace id, `$3` = the cutoff. */
161
+ export const PERSON_FALLBACK_FLOW_SESSIONS_SQL = String.raw`SELECT "id" FROM "flow_sessions"
162
+ WHERE "workspace_id" = $2::text
163
+ AND "lead_id" IS NULL
164
+ AND "created_at" < ($3::timestamptz AT TIME ZONE 'UTC')
165
+ AND lower(btrim("email", E' \t\n\r\f\x0B') COLLATE "C") = $1::text
166
+ ORDER BY "created_at" DESC, "id" DESC
167
+ LIMIT 50`;
168
+
169
+ /** `$1` = the Person's email, `$2` = workspace id, `$3` = the cutoff. */
170
+ export const PERSON_FALLBACK_PROJECT_LISTINGS_SQL = String.raw`SELECT "id" FROM "project_listings"
171
+ WHERE "workspace_id" = $2::text
172
+ AND "lead_id" IS NULL
173
+ AND "created_at" < ($3::timestamptz AT TIME ZONE 'UTC')
174
+ AND lower(btrim("founder_email", E' \t\n\r\f\x0B') COLLATE "C") = $1::text
175
+ ORDER BY "created_at" DESC, "id" DESC
176
+ LIMIT 50`;
177
+
178
+ /** The cutoff read: the backfill's `finished_at`, or no row when it has not run. */
179
+ export const PERSON_CUTOFF_SQL = `SELECT "finished_at" FROM "_prisma_migrations"
180
+ WHERE "migration_name" = '20261010121000_person_backfill'
181
+ AND "finished_at" IS NOT NULL
182
+ AND "rolled_back_at" IS NULL
183
+ LIMIT 1`;
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env tsx
2
+ /**
3
+ * Declared-env check — fails when this site's code reads an environment
4
+ * variable that `project.yaml` does not declare.
5
+ *
6
+ * Every literal `process.env` read in the site's source (tests, stories and
7
+ * this `tools/` directory excepted) needs a row in `project.yaml`'s
8
+ * `env_contract` block: a `name`, a one-line `description`, and
9
+ * `secret: true` or `false`. Platform names (`NODE_ENV`, `CI`, `VERCEL_*`, …)
10
+ * need none. On a spoke (`.ailk-site-manifest.json` records
11
+ * `"topology": "spoke"`), `NEXT_PUBLIC_AILK_API_URL` is refused outright:
12
+ * a spoke's hub origin is server-only, so read `AILK_API_URL` instead.
13
+ *
14
+ * The scanner is `tools/declared-env.ts`, a copy of create-ailk's own, which
15
+ * writes this site's rows when it adds a module or a route. Add a row by hand
16
+ * for a variable you add; create-ailk never edits or removes one.
17
+ *
18
+ * Usage:
19
+ * pnpm env:declared # or: tsx tools/check-declared-env.ts
20
+ *
21
+ * Exit codes:
22
+ * 0 — every read is declared
23
+ * 1 — an undeclared read, a malformed row, a refused name, or a missing file
24
+ */
25
+
26
+ import { dirname, resolve } from "node:path";
27
+
28
+ import { checkDeclaredEnv } from "./declared-env";
29
+
30
+ const ROOT = resolve(dirname(process.argv[1] ?? "."), "..");
31
+
32
+ const { findings, summary } = checkDeclaredEnv(ROOT);
33
+ if (findings.length > 0) {
34
+ for (const finding of findings) console.error(finding);
35
+ process.exit(1);
36
+ }
37
+ console.log(summary);