@lupinum/ginko-server 0.0.0-stage → 0.18.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 (95) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/convex/_generated/api.d.ts +185 -0
  5. package/convex/_generated/api.js +23 -0
  6. package/convex/_generated/dataModel.d.ts +60 -0
  7. package/convex/_generated/server.d.ts +162 -0
  8. package/convex/_generated/server.js +101 -0
  9. package/convex/account.ts +110 -0
  10. package/convex/agent.ts +814 -0
  11. package/convex/auth.config.ts +4 -0
  12. package/convex/auth.ts +62 -0
  13. package/convex/backup.ts +94 -0
  14. package/convex/betterAuth/_generated/api.ts +56 -0
  15. package/convex/betterAuth/_generated/component.ts +431 -0
  16. package/convex/betterAuth/_generated/dataModel.ts +60 -0
  17. package/convex/betterAuth/_generated/server.ts +169 -0
  18. package/convex/betterAuth/adapter.ts +7 -0
  19. package/convex/betterAuth/convex.config.ts +3 -0
  20. package/convex/betterAuth/schema.ts +102 -0
  21. package/convex/betterAuth/schemaMetadata.ts +697 -0
  22. package/convex/betterAuth/schemaOptions.ts +13 -0
  23. package/convex/betterAuth/schemaPlugins.ts +13 -0
  24. package/convex/bundle.ts +183 -0
  25. package/convex/changes.ts +136 -0
  26. package/convex/cleanup.ts +44 -0
  27. package/convex/connect.ts +143 -0
  28. package/convex/convex.config.ts +7 -0
  29. package/convex/crons.ts +14 -0
  30. package/convex/demo.ts +72 -0
  31. package/convex/entries.ts +1770 -0
  32. package/convex/facts.ts +129 -0
  33. package/convex/files.ts +631 -0
  34. package/convex/http.ts +21 -0
  35. package/convex/image.ts +45 -0
  36. package/convex/images.ts +54 -0
  37. package/convex/invites.ts +227 -0
  38. package/convex/lib/access.ts +180 -0
  39. package/convex/lib/agentTools.ts +331 -0
  40. package/convex/lib/content.ts +317 -0
  41. package/convex/lib/corpus.ts +83 -0
  42. package/convex/lib/diff.ts +50 -0
  43. package/convex/lib/fail.ts +27 -0
  44. package/convex/lib/files.ts +70 -0
  45. package/convex/lib/history.ts +103 -0
  46. package/convex/lib/i18n.ts +52 -0
  47. package/convex/lib/input.ts +57 -0
  48. package/convex/lib/library.ts +28 -0
  49. package/convex/lib/lifecycle.ts +100 -0
  50. package/convex/lib/list.ts +112 -0
  51. package/convex/lib/migrations.ts +126 -0
  52. package/convex/lib/names.ts +56 -0
  53. package/convex/lib/pending.ts +84 -0
  54. package/convex/lib/policy.ts +155 -0
  55. package/convex/lib/publicness.ts +87 -0
  56. package/convex/lib/reminders.ts +27 -0
  57. package/convex/lib/search.ts +132 -0
  58. package/convex/lib/siteUrl.ts +95 -0
  59. package/convex/lib/status.ts +109 -0
  60. package/convex/lib/translation.ts +56 -0
  61. package/convex/lib/trees.ts +43 -0
  62. package/convex/lib/write.ts +296 -0
  63. package/convex/mail.ts +136 -0
  64. package/convex/members.ts +129 -0
  65. package/convex/migrations.ts +105 -0
  66. package/convex/navigation.ts +276 -0
  67. package/convex/ops.ts +50 -0
  68. package/convex/proposals.ts +753 -0
  69. package/convex/refresh.ts +163 -0
  70. package/convex/release.ts +435 -0
  71. package/convex/reminders.ts +116 -0
  72. package/convex/retention.ts +121 -0
  73. package/convex/routes/bundle.ts +62 -0
  74. package/convex/routes/connect.ts +80 -0
  75. package/convex/routes/export.ts +23 -0
  76. package/convex/routes/file.ts +34 -0
  77. package/convex/routes/key.ts +53 -0
  78. package/convex/routes/mcp.ts +300 -0
  79. package/convex/routes/release.ts +66 -0
  80. package/convex/routes/upload.ts +94 -0
  81. package/convex/schema.ts +443 -0
  82. package/convex/search.ts +58 -0
  83. package/convex/seed.ts +624 -0
  84. package/convex/siteDeletion.ts +78 -0
  85. package/convex/sites.ts +393 -0
  86. package/convex/tasks.ts +51 -0
  87. package/convex/tsconfig.json +27 -0
  88. package/convex/uploads.ts +429 -0
  89. package/convex/uploadsNode.ts +86 -0
  90. package/convex/views.ts +111 -0
  91. package/i18n/de.json +364 -0
  92. package/i18n/en.json +364 -0
  93. package/i18n/es.json +364 -0
  94. package/i18n/fr.json +364 -0
  95. package/package.json +45 -3
@@ -0,0 +1,443 @@
1
+ // Tables of the platform, SPEC part 3. Content shapes (`schema`, `data`, `before`/`after`)
2
+ // are v.any() on purpose: every write checks them with the one validator in
3
+ // @lupinum/ginko/core, so nothing unchecked gets in.
4
+ import { defineSchema, defineTable } from 'convex/server'
5
+ import { v } from 'convex/values'
6
+
7
+ const role = v.union(v.literal('owner'), v.literal('staff'))
8
+ /**
9
+ * A history line as catalog key plus params (`HistoryMsg`, lib/history.ts), read in the reader's language.
10
+ * Param values are text, numbers (dates in ms), labels per locale or nested messages: v.any() because
11
+ * the type is recursive; every write builds them with `msg()`.
12
+ */
13
+ const historyMsg = v.object({ key: v.string(), params: v.optional(v.record(v.string(), v.any())) })
14
+ const scope = v.union(v.literal('release'), v.literal('pull'), v.literal('check'), v.literal('export'))
15
+
16
+ export default defineSchema({
17
+ sites: defineTable({
18
+ slug: v.string(),
19
+ name: v.string(),
20
+ url: v.string(),
21
+ previewOrigins: v.array(v.string()),
22
+ schema: v.any(),
23
+ schemaRev: v.number(),
24
+ contentRev: v.number(),
25
+ /** Unused since entries.move (one order value per move); `sites:dropOrderRevs` unsets it (internals/migrations.md). */
26
+ orderRevs: v.optional(v.record(v.string(), v.number())),
27
+ entryCount: v.number(),
28
+ /** Budget bytes (core `entryBytes`) of the live entries, drafts included (SPEC 3). */
29
+ bytes: v.number(),
30
+ /**
31
+ * Budget bytes of the removed entries in the trash; capped (SITE_BUDGET.trashBytes). Optional and
32
+ * `treeBytes` too until `entries:migrateStorage` ran everywhere (internals/migrations.md).
33
+ */
34
+ trashBytes: v.optional(v.number()),
35
+ /** Bytes of the live entries' Markdown trees (`entryTrees`); bounded by SITE_BUDGET.treeBytes so the bundle read stays in Convex's limits. */
36
+ treeBytes: v.optional(v.number()),
37
+ release: v.union(v.null(), v.object({ commit: v.string(), schemaRev: v.number(), contentRev: v.number(), at: v.number() })),
38
+ /** Vercel bypass token of the site; never returned by a query. */
39
+ refreshToken: v.optional(v.string()),
40
+ /** Site setting for the agent door (SPEC 17): `true` makes agent writes proposals. Between the key's `review` and `agents.review` of the config. */
41
+ agentReview: v.optional(v.boolean()),
42
+ /** When the pending digest mail of open proposals goes out (ms); absent when none is scheduled. */
43
+ digestAt: v.optional(v.number()),
44
+ /** When the live site last proved it shows the current revision after a publish or an urgent refresh (ms). */
45
+ lastRefreshAt: v.optional(v.number()),
46
+ /**
47
+ * Set when an owner or admin started the deletion: nobody opens the site except to cancel, the bundle answers as for an
48
+ * unknown site and keys stop working. `at` is when `siteDeletion.purge` (the scheduled `job`) removes everything.
49
+ */
50
+ deleting: v.optional(v.object({ at: v.number(), job: v.id('_scheduled_functions') })),
51
+ /** Set by `seed:importOpen` on an empty site while an operator loads an export folder into the hosted platform; `seed:importDone` clears it. */
52
+ importOpen: v.optional(v.boolean()),
53
+ }).index('by_slug', ['slug']),
54
+
55
+ memberships: defineTable({
56
+ site: v.id('sites'),
57
+ user: v.string(),
58
+ /** Normalized email of the accepted invite; shown in member lists. */
59
+ email: v.optional(v.string()),
60
+ role,
61
+ grants: v.array(v.string()),
62
+ }).index('by_user_site', ['user', 'site']).index('by_site', ['site']),
63
+
64
+ invites: defineTable({
65
+ site: v.id('sites'),
66
+ email: v.string(),
67
+ role,
68
+ grants: v.array(v.string()),
69
+ tokenHash: v.string(),
70
+ invitedBy: v.string(),
71
+ expiresAt: v.number(),
72
+ acceptedAt: v.optional(v.number()),
73
+ /** The inviter's language: the invitee's mails until they have their own setting. */
74
+ locale: v.optional(v.string()),
75
+ }).index('by_tokenHash', ['tokenHash']).index('by_site', ['site']).index('by_email', ['email']).index('by_expires', ['expiresAt']),
76
+
77
+ admins: defineTable({ user: v.string() }).index('by_user', ['user']),
78
+
79
+ entries: defineTable({
80
+ site: v.id('sites'),
81
+ brick: v.string(),
82
+ kind: v.union(v.literal('single'), v.literal('item')),
83
+ order: v.number(),
84
+ data: v.any(),
85
+ rev: v.number(),
86
+ fieldRevs: v.record(v.string(), v.number()),
87
+ lifeRev: v.number(),
88
+ /** Leaf path → locale → print of the main-language value at translation time. */
89
+ prints: v.record(v.string(), v.record(v.string(), v.string())),
90
+ /**
91
+ * Legacy: the Markdown trees on the row itself. They live in `entryTrees` now; `entries:migrateStorage` moves
92
+ * them, and the bundle still reads this until then (internals/migrations.md).
93
+ */
94
+ trees: v.optional(v.string()),
95
+ /** Budget bytes: core `entryBytes(data, prints)`, the text without its trees. */
96
+ bytes: v.number(),
97
+ /** UTF-8 bytes of this entry's rows in `entryTrees`; 0 in the trash, which keeps no trees. */
98
+ treeBytes: v.optional(v.number()),
99
+ /**
100
+ * When the entry last changed for the public (ms): a save of a live entry, its creation, going live, a restore.
101
+ * The bundle's `updatedAt`. A draft's saves leave it alone; release migrations do too.
102
+ */
103
+ contentAt: v.optional(v.number()),
104
+ deletedAt: v.optional(v.number()),
105
+ /** Drafts (SPEC 15): absent means live. A draft is stored and counted but never in the public bundle. */
106
+ state: v.optional(v.union(v.literal('draft'), v.literal('live'))),
107
+ /** When a scheduled draft goes online (ms); only on a draft. */
108
+ publishAt: v.optional(v.number()),
109
+ /** The scheduled `entries.publishDue` run that belongs to `publishAt`. */
110
+ publishJob: v.optional(v.id('_scheduled_functions')),
111
+ /**
112
+ * The staff member (user id) who created the entry through a create task: they may change it later with that
113
+ * task (lib/access.ts `authorize`). Absent for entries of owners and admins, and for entries made before it existed.
114
+ */
115
+ createdBy: v.optional(v.string()),
116
+ })
117
+ .index('by_site_brick_order', ['site', 'brick', 'order'])
118
+ .index('by_site_brick_deleted', ['site', 'brick', 'deletedAt'])
119
+ .index('by_site_deleted', ['site', 'deletedAt']),
120
+
121
+ /**
122
+ * The trees of an entry's Markdown texts (core `markdownTrees`) as JSON text, split into parts below Convex's 1 MiB
123
+ * document limit. Derived from `entries.data` and written with it (lib/trees.ts, the only code that touches this table),
124
+ * so the bundle parses nothing. JSON text, because a tree may hold keys that a Convex value does not allow. An entry
125
+ * without rows is parsed per request. After a parser change: `entries:migrateStorage`.
126
+ */
127
+ entryTrees: defineTable({ site: v.id('sites'), entry: v.id('entries'), part: v.number(), json: v.string() })
128
+ .index('by_entry', ['entry', 'part'])
129
+ .index('by_site', ['site']),
130
+
131
+ /**
132
+ * Unpublished changes of a live entry in a drafts collection (lib/pending.ts): Speichern keeps them here, Veröffentlichen
133
+ * writes them into the entry through `commitEntry`, Verwerfen deletes the row. One row per entry. Never read by the
134
+ * bundle, so the website shows only `entries.data`.
135
+ */
136
+ pendingChanges: defineTable({
137
+ site: v.id('sites'),
138
+ entry: v.id('entries'),
139
+ brick: v.string(),
140
+ /** Root field → its unpublished value; null: the field is removed. */
141
+ fields: v.record(v.string(), v.any()),
142
+ /** The prints of the leaves under those roots (they replace the entry's prints there). */
143
+ prints: v.record(v.string(), v.record(v.string(), v.string())),
144
+ /** Root field → the entry rev its unpublished value was saved at; a live write after it is a conflict at publish. */
145
+ revs: v.record(v.string(), v.number()),
146
+ /** Who saved last, when the first and the last save happened (ms). */
147
+ by: v.string(),
148
+ since: v.number(),
149
+ at: v.number(),
150
+ /** When the changes go online (ms), and the scheduled `entries.publishDue` run. */
151
+ publishAt: v.optional(v.number()),
152
+ publishJob: v.optional(v.id('_scheduled_functions')),
153
+ }).index('by_entry', ['entry']).index('by_site', ['site']),
154
+
155
+ slugs: defineTable({
156
+ site: v.id('sites'),
157
+ brick: v.string(),
158
+ locale: v.string(),
159
+ slug: v.string(),
160
+ entry: v.id('entries'),
161
+ /** An address the entry had before `entries.changeSlug`: still reserved, the site forwards it with a 301 (bundle `oldUrls`). */
162
+ old: v.optional(v.boolean()),
163
+ }).index('by_key', ['site', 'brick', 'locale', 'slug']).index('by_entry', ['entry']).index('by_site_old', ['site', 'old']),
164
+
165
+ ops: defineTable({
166
+ site: v.id('sites'),
167
+ actor: v.string(),
168
+ opId: v.string(),
169
+ hash: v.string(),
170
+ result: v.any(),
171
+ at: v.number(),
172
+ }).index('by_site_actor_op', ['site', 'actor', 'opId']).index('by_at', ['at']),
173
+
174
+ changes: defineTable({
175
+ site: v.id('sites'),
176
+ entry: v.optional(v.id('entries')),
177
+ brick: v.string(),
178
+ actor: v.string(),
179
+ /** Set when the person acted through the agent door (SPEC 16), with the key they used. */
180
+ via: v.optional(v.literal('agent')),
181
+ agentKey: v.optional(v.id('agentKeys')),
182
+ /** The owner or admin who approved the proposal this change applies (SPEC 17); `actor` is the author. */
183
+ approvedBy: v.optional(v.string()),
184
+ opId: v.string(),
185
+ kind: v.string(),
186
+ /** German rendering of `msg`: the fallback for rows from before `msg` (they have no `msg`). Readers render `msg` in their own language. */
187
+ sentence: v.string(),
188
+ msg: v.optional(historyMsg),
189
+ fields: v.optional(v.array(v.string())),
190
+ before: v.optional(v.any()),
191
+ after: v.optional(v.any()),
192
+ printsBefore: v.optional(v.any()),
193
+ printsAfter: v.optional(v.any()),
194
+ entryRev: v.optional(v.number()),
195
+ contentRev: v.number(),
196
+ at: v.number(),
197
+ undoneBy: v.optional(v.id('changes')),
198
+ })
199
+ .index('by_entry', ['entry']).index('by_site_at', ['site', 'at']).index('by_site_brick_at', ['site', 'brick', 'at']).index('by_at', ['at'])
200
+ // "By me" / "By AI" filters (`changes.list`): `ai` is true for a change through the agent door; absent rows count as false.
201
+ .index('by_site_actor_at', ['site', 'actor', 'at']).index('by_site_via_at', ['site', 'via', 'at']),
202
+
203
+ /**
204
+ * A key for the agent door (SPEC 16). It acts as its person with their role and grants at call
205
+ * time; only the SHA-256 of the key is stored. `minute`/`calls` count calls for the rate limit.
206
+ */
207
+ agentKeys: defineTable({
208
+ site: v.id('sites'),
209
+ user: v.string(),
210
+ hash: v.string(),
211
+ label: v.string(),
212
+ createdAt: v.number(),
213
+ lastUsedAt: v.optional(v.number()),
214
+ revokedAt: v.optional(v.number()),
215
+ minute: v.optional(v.number()),
216
+ calls: v.optional(v.number()),
217
+ /** Whether this key's writes are proposals (SPEC 17). Absent: the site's setting decides. */
218
+ review: v.optional(v.boolean()),
219
+ }).index('by_hash', ['hash']).index('by_site_user', ['site', 'user']).index('by_user', ['user']),
220
+
221
+ /**
222
+ * A change that needs a yes (SPEC 17). `args` are the arguments of the normal operation (with the
223
+ * author's `opId`); approving runs that operation again as the author. `base` holds the revisions
224
+ * the author saw, `before`/`after` the changed fields for the diff.
225
+ */
226
+ proposals: defineTable({
227
+ site: v.id('sites'),
228
+ op: v.union(v.literal('save'), v.literal('create'), v.literal('remove'), v.literal('publish'), v.literal('unpublish')),
229
+ brick: v.string(),
230
+ entry: v.optional(v.id('entries')),
231
+ args: v.any(),
232
+ base: v.any(),
233
+ before: v.optional(v.any()),
234
+ after: v.optional(v.any()),
235
+ /** German rendering of `msg`: the fallback for rows from before `msg` (they have no `msg`). Readers render `msg` in their own language. */
236
+ sentence: v.string(),
237
+ msg: v.optional(historyMsg),
238
+ author: v.string(),
239
+ via: v.union(v.literal('ui'), v.literal('agent')),
240
+ agentKey: v.optional(v.id('agentKeys')),
241
+ status: v.union(v.literal('open'), v.literal('approved'), v.literal('scheduled'), v.literal('applied'), v.literal('rejected'), v.literal('stale'), v.literal('withdrawn')),
242
+ createdAt: v.number(),
243
+ /** When a scheduled approval applies (ms), and its scheduled run. */
244
+ at: v.optional(v.number()),
245
+ job: v.optional(v.id('_scheduled_functions')),
246
+ release: v.optional(v.id('releases')),
247
+ decidedBy: v.optional(v.string()),
248
+ decidedAt: v.optional(v.number()),
249
+ /** The reason of a rejection, or why a proposal went stale (German). */
250
+ reason: v.optional(v.string()),
251
+ /** The catalog message of a stale reason (the `reason` text is its German rendering); absent on rejections (free text) and on rows from before. */
252
+ reasonMsg: v.optional(historyMsg),
253
+ /** The change row the applied proposal wrote, if it changed anything. */
254
+ change: v.optional(v.id('changes')),
255
+ /** Set once the digest mail has listed this proposal. */
256
+ mailedAt: v.optional(v.number()),
257
+ })
258
+ .index('by_site', ['site']).index('by_site_status', ['site', 'status']).index('by_site_author', ['site', 'author'])
259
+ // decidedAt last, so History reads "decided in the last two weeks" as a range; open rows have none and keep creation order.
260
+ .index('by_site_status_decided', ['site', 'status', 'decidedAt']).index('by_site_author_status_decided', ['site', 'author', 'status', 'decidedAt'])
261
+ .index('by_release', ['release']).index('by_decided', ['decidedAt']),
262
+
263
+ /** A group of proposals approved together, all or none (SPEC 17). */
264
+ releases: defineTable({
265
+ site: v.id('sites'),
266
+ name: v.string(),
267
+ /** When it goes live: planned at creation, or set when it is approved. */
268
+ at: v.optional(v.number()),
269
+ job: v.optional(v.id('_scheduled_functions')),
270
+ status: v.union(v.literal('open'), v.literal('scheduled'), v.literal('applied'), v.literal('stale')),
271
+ createdBy: v.string(),
272
+ createdAt: v.number(),
273
+ decidedBy: v.optional(v.string()),
274
+ decidedAt: v.optional(v.number()),
275
+ }).index('by_site_status', ['site', 'status']).index('by_decided', ['decidedAt']),
276
+
277
+ /** Content migrations that a site's own config sent with a release (SPEC 5.1), per site. Not the server's own data migrations: those are `serverMigrations`. */
278
+ migrationsApplied: defineTable({
279
+ site: v.id('sites'),
280
+ id: v.string(),
281
+ brick: v.string(),
282
+ fills: v.string(),
283
+ fingerprint: v.string(),
284
+ schemaRev: v.number(),
285
+ }).index('by_site_id', ['site', 'id']),
286
+
287
+ /**
288
+ * One row per run of a one-time data migration of the platform (lib/migrations.ts, started after each deploy by
289
+ * `migrations:runPending`). A stopped run (failed or canceled) is not a state here: it is the state of `job`.
290
+ */
291
+ serverMigrations: defineTable({
292
+ /** The migration's name in the list (`MIGRATIONS`), never reused. */
293
+ name: v.string(),
294
+ state: v.union(v.literal('running'), v.literal('done')),
295
+ /** Where the next page starts; null: from the beginning. */
296
+ cursor: v.union(v.string(), v.null()),
297
+ /** The scheduled next page while running. */
298
+ job: v.optional(v.id('_scheduled_functions')),
299
+ pages: v.number(),
300
+ /** The first start plus every restart after a stop. */
301
+ attempts: v.number(),
302
+ startedAt: v.number(),
303
+ finishedAt: v.optional(v.number()),
304
+ /** Recorded as done on a fresh deployment: there was nothing to migrate, nothing ran. */
305
+ baseline: v.optional(v.boolean()),
306
+ }),
307
+
308
+ /** A one-time upload ticket (SPEC 4.3): who may store one file for which site, until when. Only its hash is kept. */
309
+ uploadTickets: defineTable({
310
+ tokenHash: v.string(),
311
+ site: v.id('sites'),
312
+ user: v.string(),
313
+ expiresAt: v.number(),
314
+ /** Library upload (SPEC 4.3): the file is kept and may go straight into a folder. */
315
+ folder: v.optional(v.id('folders')),
316
+ library: v.optional(v.boolean()),
317
+ }).index('by_tokenHash', ['tokenHash']).index('by_expires', ['expiresAt']).index('by_site', ['site']),
318
+
319
+ /** Folders of the asset library (SPEC 3). A file is in at most one; absent `parent` means the top level. */
320
+ folders: defineTable({
321
+ site: v.id('sites'),
322
+ name: v.string(),
323
+ parent: v.optional(v.id('folders')),
324
+ }).index('by_site_parent', ['site', 'parent']),
325
+
326
+ uploads: defineTable({
327
+ site: v.id('sites'),
328
+ uploader: v.string(),
329
+ storageId: v.id('_storage'),
330
+ processedId: v.optional(v.id('_storage')),
331
+ /** Smaller WebP copies of an image for srcset (ascending width). Empty array: none needed; missing: not made yet (see images.backfillVariants). */
332
+ variants: v.optional(v.array(v.object({ width: v.number(), storageId: v.id('_storage') }))),
333
+ name: v.string(),
334
+ size: v.number(),
335
+ mime: v.string(),
336
+ width: v.optional(v.number()),
337
+ height: v.optional(v.number()),
338
+ status: v.union(v.literal('processing'), v.literal('ready'), v.literal('failed')),
339
+ attempts: v.number(),
340
+ /** Catalog key (`errors.upload…`) of the reason of the last failed processing attempt, shown to the uploader in their language. */
341
+ error: v.optional(v.string()),
342
+ /** While `processing`: when the next processing run is due (ms). A row long past it lost its run (uploads.requeueStale). Missing: the creation time. */
343
+ runAt: v.optional(v.number()),
344
+ folder: v.optional(v.id('folders')),
345
+ /** Uploaded through the library, put in a folder or kept on purpose: the 7-day sweep leaves it alone. Missing means false. */
346
+ kept: v.optional(v.boolean()),
347
+ /** SHA-256 (hex) of the original bytes; equal values make the "Doppelt" view. */
348
+ sha256: v.optional(v.string()),
349
+ /** Focus point of an image, 0..1 from the top left. */
350
+ focus: v.optional(v.object({ x: v.number(), y: v.number() })),
351
+ /** Description (alt text) per language, written in the Files library: the default for every use of the photo without its own text. */
352
+ alt: v.optional(v.record(v.string(), v.string())),
353
+ /** In the trash since (ms). Purged after 30 days when nothing refers to it any more. */
354
+ trashedAt: v.optional(v.number()),
355
+ /** Files before a replace; their storage is deleted 30 days after `replacedAt`. */
356
+ previous: v.optional(v.array(v.object({ storageId: v.id('_storage'), processedId: v.optional(v.id('_storage')), variants: v.optional(v.array(v.object({ width: v.number(), storageId: v.id('_storage') }))), replacedAt: v.number() }))),
357
+ /** True while `previous` is not empty; lets the sweep and retention find these rows without a scan. */
358
+ hasPrevious: v.optional(v.boolean()),
359
+ })
360
+ .index('by_site', ['site']).index('by_storage', ['storageId']).index('by_processed', ['processedId']).index('by_status', ['status'])
361
+ .index('by_site_folder', ['site', 'folder']).index('by_site_sha256', ['site', 'sha256']).index('by_site_trashed', ['site', 'trashedAt'])
362
+ .index('by_previous', ['hasPrevious']),
363
+
364
+ fileRefs: defineTable({
365
+ site: v.id('sites'),
366
+ file: v.id('uploads'),
367
+ holder: v.union(v.literal('entry'), v.literal('change'), v.literal('pending')),
368
+ holderId: v.string(),
369
+ /** Entry holders only: where in the entry the file sits, and whether that image lacks a description in a language of the site. */
370
+ uses: v.optional(v.array(v.object({ path: v.string(), missingAlt: v.boolean() }))),
371
+ missingAlt: v.optional(v.boolean()),
372
+ })
373
+ .index('by_file', ['file']).index('by_holder', ['holder', 'holderId'])
374
+ .index('by_site_holder', ['site', 'holder']).index('by_site_missingAlt', ['site', 'missingAlt']),
375
+
376
+ /** One row per finished upload that an entry uses; `uploads.applyRevBumps` turns all rows of a site into one contentRev raise. */
377
+ revBumps: defineTable({ site: v.id('sites') }).index('by_site', ['site']),
378
+
379
+ pushKeys: defineTable({
380
+ site: v.id('sites'),
381
+ hash: v.string(),
382
+ label: v.string(),
383
+ scopes: v.array(scope),
384
+ createdBy: v.string(),
385
+ revokedAt: v.optional(v.number()),
386
+ /** When a CLI route last accepted the key, stamped at most once an hour (routes/key.ts). */
387
+ lastUsedAt: v.optional(v.number()),
388
+ }).index('by_hash', ['hash']).index('by_site', ['site']),
389
+
390
+ /**
391
+ * `ginko connect` (connect.ts): a computer asks for a publishing key, a person confirms its code in the Studio, the
392
+ * computer's next poll gets the key. Only the SHA-256 of the device code is stored; the key does not exist before
393
+ * that poll. `site`, `approvedBy`, `approvedAt` are set by the approval. Rows are deleted after `expiresAt`.
394
+ */
395
+ connectRequests: defineTable({
396
+ deviceHash: v.string(),
397
+ /** 8 characters without look-alikes, stored without the hyphen. Not a secret: it only names the request. */
398
+ userCode: v.string(),
399
+ label: v.string(),
400
+ expiresAt: v.number(),
401
+ state: v.union(v.literal('pending'), v.literal('approved'), v.literal('declined'), v.literal('used')),
402
+ site: v.optional(v.id('sites')),
403
+ approvedBy: v.optional(v.string()),
404
+ approvedAt: v.optional(v.number()),
405
+ }).index('by_device', ['deviceHash']).index('by_code', ['userCode']).index('by_site', ['site']).index('by_state_expires', ['state', 'expiresAt']).index('by_expires', ['expiresAt']),
406
+
407
+ /** Wrong connect codes per signed-in person in a fixed 10-minute window (connect.ts); `window` = its start in ms. */
408
+ connectTries: defineTable({ user: v.string(), window: v.number(), count: v.number() })
409
+ .index('by_user_window', ['user', 'window']).index('by_window', ['window']),
410
+
411
+ /** A saved list view of one person (SPEC 4.2 views): a filter and sort of a brick's entry list. Never shared. */
412
+ views: defineTable({
413
+ site: v.id('sites'),
414
+ user: v.string(),
415
+ brick: v.string(),
416
+ name: v.string(),
417
+ /** `{ text?, filters?, sort? }`; the shape is checked by `views.save`. */
418
+ query: v.any(),
419
+ }).index('by_site_user_brick', ['site', 'user', 'brick']).index('by_user', ['user']),
420
+
421
+ /**
422
+ * Fixed-window counters per site; `window` = minute since epoch. No `kind`: bundle requests (600 per minute).
423
+ * `invite`: invite mails (invites.create), one row per hour, its window the hour's first minute.
424
+ * `upload`: upload tickets (uploads.prepare), one row per person (`user`) and hour.
425
+ */
426
+ rateWindows: defineTable({ site: v.id('sites'), kind: v.optional(v.union(v.literal('invite'), v.literal('upload'))), user: v.optional(v.string()), window: v.number(), count: v.number() })
427
+ .index('by_site_kind_window', ['site', 'kind', 'window', 'user']).index('by_window', ['window']),
428
+
429
+ /** A person's own settings, one row each. No row means the defaults: reminders on, German (SPEC 10). `locale` is the language of messages and mail to this person. */
430
+ /**
431
+ * `locale`: the Studio language the person chose; it wins over the browser. `seenLocale`: the browser's language at the
432
+ * last visit without a choice, only for mails (sign-in code, reminders), so they come in a language the person reads.
433
+ * `name`: how the person's teams see them in history, conflicts, files and keys (`lib/names.ts`); without it, their email.
434
+ */
435
+ userSettings: defineTable({ user: v.string(), remindByMail: v.boolean(), locale: v.optional(v.string()), seenLocale: v.optional(v.string()), name: v.optional(v.string()) }).index('by_user', ['user']),
436
+
437
+ /** One sent reminder mail (SPEC 10): the work week it was for, so a sweep that runs again sends nothing twice. */
438
+ reminders: defineTable({ site: v.id('sites'), brick: v.string(), week: v.string(), user: v.string(), at: v.number() })
439
+ .index('by_site_brick_week_user', ['site', 'brick', 'week', 'user']),
440
+
441
+ /** Local and test mail sink (GINKO_MAIL=outbox). */
442
+ outbox: defineTable({ to: v.string(), subject: v.string(), text: v.string(), at: v.number() }).index('by_to', ['to']).index('by_at', ['at']),
443
+ })
@@ -0,0 +1,58 @@
1
+ // Studio search (⌘K, SPEC 4.2): entries, bricks and tasks that match the words. The entry search is
2
+ // the one of the agent door (lib/search.ts); bricks match by their label or a field's, tasks by label.
3
+ import type { Label } from '@lupinum/ginko'
4
+ import { labelOf, ordered, type Schema } from '@lupinum/ginko/internal'
5
+
6
+ import { v } from 'convex/values'
7
+ import { query } from './_generated/server'
8
+ import { actorFor } from './lib/access'
9
+ import { taskTools } from './lib/agentTools'
10
+ import { labelMatches, searchEntries } from './lib/search'
11
+
12
+ /** A label in every language it has, so "menu" finds the area whose German label is "Speisekarte". */
13
+ const allLanguages = (label: Label) => (typeof label === 'string' ? label : Object.values(label).join(' '))
14
+
15
+ export const LIMIT_DEFAULT = 20
16
+ export const LIMIT_MAX = 50
17
+
18
+ /**
19
+ * Any member. Entries: best first, deleted ones never. Bricks: in schema order, those named by the words first, then
20
+ * those found by a field (with `field`, its key). Tasks: in schema order. Staff find only what they can open: the tasks
21
+ * they may run, and entries and bricks of the areas they hold a task in. That is the Studio's own rule for the areas it
22
+ * opens (useAll.ts `editable`). Reading stays site-wide (SPEC 2.7): the agent door's search is not filtered.
23
+ */
24
+ export const studio = query({
25
+ args: { site: v.string(), query: v.string(), limit: v.optional(v.number()) },
26
+ handler: async (ctx, args) => {
27
+ const actor = await actorFor(ctx, args.site)
28
+ const schema = actor.site.schema as Schema
29
+ const main = schema.locales[0]!
30
+ const asked = args.limit !== undefined && Number.isFinite(args.limit) ? Math.floor(args.limit) : LIMIT_DEFAULT
31
+ const limit = Math.min(Math.max(asked, 1), LIMIT_MAX)
32
+ const text = args.query.trim().slice(0, 200)
33
+ if (!text) return { entries: [], bricks: [], tasks: [] }
34
+
35
+ const tools = taskTools(actor)
36
+ const open = actor.role === 'staff' ? new Set(tools.map((tool) => tool.brick)) : undefined
37
+ const entries = (await searchEntries(ctx, actor, { query: text, limit, within: open })).map((hit) => ({
38
+ entry: hit.entry, brick: hit.brick, brickLabel: labelOf(schema.bricks[hit.brick]!.label, main, main), label: hit.label, snippet: hit.snippet, state: hit.state,
39
+ }))
40
+ const live = Object.entries(schema.bricks).filter(([brick, def]) => !def.retired && (!open || open.has(brick)))
41
+ const byName = live.filter(([, def]) => labelMatches(allLanguages(def.label), text))
42
+ // An area is also found by one of its fields ("Telefon" finds "Adresse und Kontakt"), after those named so.
43
+ // The slug is left out: the Studio calls it "Webadresse", whatever the schema says.
44
+ const byField = live.flatMap(([brick, def]) => {
45
+ if (byName.some(([named]) => named === brick)) return []
46
+ const hit = ordered(def.fields).find(([, f]) => !f.retired && f.type !== 'slug' && labelMatches(allLanguages(f.label), text))
47
+ return hit ? [[brick, def, hit[0]] as const] : []
48
+ })
49
+ const bricks = [...byName.map(([brick, def]) => [brick, def, undefined] as const), ...byField]
50
+ .slice(0, limit)
51
+ .map(([brick, def, field]) => ({ brick, label: labelOf(def.label, main, main), kind: def.kind, ...(field ? { field } : {}) }))
52
+ const tasks = tools
53
+ .filter((tool) => labelMatches(allLanguages(tool.task.label), text))
54
+ .slice(0, limit)
55
+ .map((tool) => ({ id: tool.ref, label: labelOf(tool.task.label, main, main), brick: tool.brick, brickLabel: labelOf(schema.bricks[tool.brick]!.label, main, main) }))
56
+ return { entries, bricks, tasks }
57
+ },
58
+ })