@hogsend/engine 0.46.1 → 0.51.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 (88) hide show
  1. package/README.md +6 -0
  2. package/package.json +13 -10
  3. package/src/campaigns/cohort-sql.ts +8 -9
  4. package/src/connectors/presets/index.ts +8 -2
  5. package/src/container.ts +150 -8
  6. package/src/destinations/define-destination.ts +2 -2
  7. package/src/destinations/presets/posthog.ts +7 -0
  8. package/src/destinations/presets/segment.ts +5 -0
  9. package/src/env.ts +38 -0
  10. package/src/flags/reconcile.ts +200 -0
  11. package/src/index.ts +79 -0
  12. package/src/journeys/authoring.ts +32 -0
  13. package/src/journeys/define-journey.ts +45 -40
  14. package/src/journeys/execute-journey-run.ts +73 -32
  15. package/src/journeys/journey-boundary.ts +76 -0
  16. package/src/journeys/journey-context.ts +128 -70
  17. package/src/journeys/journey-task-factory.ts +31 -0
  18. package/src/journeys/journey-task-runtime.ts +31 -0
  19. package/src/journeys/journey-version.test.ts +236 -0
  20. package/src/journeys/journey-version.ts +158 -0
  21. package/src/journeys/record-once.ts +28 -2
  22. package/src/lib/campaign-send-key.ts +9 -18
  23. package/src/lib/connector-actions.test.ts +36 -0
  24. package/src/lib/connector-actions.ts +42 -4
  25. package/src/lib/contacts.ts +49 -0
  26. package/src/lib/conversions.test.ts +33 -0
  27. package/src/lib/conversions.ts +9 -1
  28. package/src/lib/crm-deals.ts +1 -1
  29. package/src/lib/crm-ingest.ts +1 -1
  30. package/src/lib/email.ts +23 -2
  31. package/src/lib/enrollment-policy.ts +51 -0
  32. package/src/lib/event-names.ts +7 -1
  33. package/src/lib/feed.ts +55 -3
  34. package/src/lib/flags-registry.ts +48 -0
  35. package/src/lib/flags.ts +498 -0
  36. package/src/lib/frequency-cap.ts +4 -2
  37. package/src/lib/funnel-progress.ts +1 -1
  38. package/src/lib/fx.ts +374 -0
  39. package/src/lib/global-control-readout.ts +166 -0
  40. package/src/lib/groups.ts +362 -0
  41. package/src/lib/holdout.ts +1 -1
  42. package/src/lib/ingestion.ts +38 -0
  43. package/src/lib/journey-lift.ts +142 -0
  44. package/src/lib/journey-suppress.ts +4 -2
  45. package/src/lib/lift-stats.ts +2 -2
  46. package/src/lib/operator-settings.ts +71 -0
  47. package/src/lib/outbound.ts +147 -0
  48. package/src/lib/preferences.ts +6 -80
  49. package/src/lib/recipient-preferences.ts +53 -0
  50. package/src/lib/sms.ts +21 -2
  51. package/src/lib/stable-stringify.test.ts +42 -0
  52. package/src/lib/stable-stringify.ts +23 -0
  53. package/src/lib/tracked.ts +9 -2
  54. package/src/lib/variant.ts +99 -0
  55. package/src/lib/webhook-signing.ts +16 -1
  56. package/src/lists/registry.ts +6 -2
  57. package/src/lists/subscription.ts +13 -0
  58. package/src/routes/admin/attribution.ts +1 -2
  59. package/src/routes/admin/campaigns.ts +84 -45
  60. package/src/routes/admin/contacts.ts +53 -4
  61. package/src/routes/admin/conversions.ts +138 -1
  62. package/src/routes/admin/deals.ts +43 -34
  63. package/src/routes/admin/emails.ts +4 -6
  64. package/src/routes/admin/events.ts +128 -1
  65. package/src/routes/admin/flags.ts +369 -0
  66. package/src/routes/admin/groups.ts +900 -0
  67. package/src/routes/admin/impact-schemas.ts +44 -0
  68. package/src/routes/admin/impact-wire.test.ts +181 -0
  69. package/src/routes/admin/impact.ts +486 -0
  70. package/src/routes/admin/index.ts +12 -0
  71. package/src/routes/admin/journey-impact.ts +446 -0
  72. package/src/routes/admin/journeys.ts +70 -100
  73. package/src/routes/admin/settings.ts +145 -0
  74. package/src/routes/admin/targeting.ts +259 -0
  75. package/src/routes/events/index.ts +11 -0
  76. package/src/routes/flags/index.ts +120 -0
  77. package/src/routes/groups/index.ts +417 -0
  78. package/src/routes/index.ts +23 -1
  79. package/src/testing.ts +25 -0
  80. package/src/webhook-sources/presets/index.ts +5 -1
  81. package/src/webhook-sources/presets/intercom.ts +230 -0
  82. package/src/webhook-sources/presets/segment.ts +56 -4
  83. package/src/worker.ts +3 -0
  84. package/src/workflows/bucket-backfill.ts +1 -14
  85. package/src/workflows/crm-reconcile.ts +1 -1
  86. package/src/workflows/impact-digest.ts +761 -0
  87. package/src/workflows/journey-blueprint-interpreter.ts +18 -1
  88. package/src/middleware/auth.ts +0 -24
@@ -1,6 +1,19 @@
1
1
  import { contacts, userEvents } from "@hogsend/db";
2
2
  import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
3
- import { and, count, desc, eq, gte, isNull, lte, or, sql } from "drizzle-orm";
3
+ import {
4
+ and,
5
+ count,
6
+ desc,
7
+ eq,
8
+ gte,
9
+ isNotNull,
10
+ isNull,
11
+ lte,
12
+ max,
13
+ min,
14
+ or,
15
+ sql,
16
+ } from "drizzle-orm";
4
17
  import type { AppEnv } from "../../app.js";
5
18
  import type { HogsendClient } from "../../container.js";
6
19
  import {
@@ -169,6 +182,59 @@ const namesRoute = createRoute({
169
182
  },
170
183
  });
171
184
 
185
+ /**
186
+ * One-line explanations for the engine-stamped ingest origins, so the Studio
187
+ * source picker can say what a source IS rather than just echo its slug.
188
+ * Anything not listed here and not a registered connector is "observed" —
189
+ * sources are an open vocabulary exactly like event names.
190
+ */
191
+ const BUILTIN_SOURCES: Record<string, string> = {
192
+ api: "Server-side ingest — the secret-key /v1/events endpoint and SDKs.",
193
+ inapp: "Browser SDK ingest (publishable key).",
194
+ studio: "Fired from the Studio (debug drawer, admin tools).",
195
+ journey: "Emitted by a journey via ctx.trigger().",
196
+ connector: "Inbound connector engagement (Discord, Telegram, …).",
197
+ tracking: "First-party email tracking — opens, clicks, semantic actions.",
198
+ bucket: "Bucket entry/exit transitions.",
199
+ import: "Contact import jobs.",
200
+ sms: "SMS pipeline — delivery status, link clicks, inbound messages.",
201
+ };
202
+
203
+ const sourceEntrySchema = z.object({
204
+ name: z.string(),
205
+ occurrences: z.number(),
206
+ firstSeenAt: z.string().nullable(),
207
+ lastSeenAt: z.string().nullable(),
208
+ // "connector" = a registered inbound connector (label = its display name),
209
+ // "builtin" = an engine-stamped origin (label = what it means),
210
+ // "observed" = seen in the event store but not otherwise known.
211
+ kind: z.enum(["connector", "builtin", "observed"]),
212
+ label: z.string().nullable(),
213
+ });
214
+
215
+ const sourcesRoute = createRoute({
216
+ method: "get",
217
+ path: "/sources",
218
+ tags: ["Admin — Events"],
219
+ summary: "List event sources (observed + registered)",
220
+ description:
221
+ "Best-effort source vocabulary for the events filter. Merges sources " +
222
+ "actually observed on stored events (with occurrence counts and " +
223
+ "first/last seen) with registered inbound connectors that haven't " +
224
+ "fired yet (zero-backfilled). Sources are an open vocabulary — any " +
225
+ "other value is also valid.",
226
+ responses: {
227
+ 200: {
228
+ content: {
229
+ "application/json": {
230
+ schema: z.object({ sources: z.array(sourceEntrySchema) }),
231
+ },
232
+ },
233
+ description: "Merged observed + registered source vocabulary",
234
+ },
235
+ },
236
+ });
237
+
172
238
  const exitSchema = z.object({
173
239
  journeyId: z.string(),
174
240
  stateId: z.string(),
@@ -292,6 +358,67 @@ export const eventsRouter = new OpenAPIHono<AppEnv>()
292
358
  });
293
359
  return c.json({ note, events }, 200);
294
360
  })
361
+ // Registered before getRoute so the literal "sources" is never captured as
362
+ // an {id}. One grouped scan over the indexed source column (sources number
363
+ // in the dozens at most), then registered-connector + builtin labeling.
364
+ .openapi(sourcesRoute, async (c) => {
365
+ const container = c.get("container");
366
+ const { db } = container;
367
+
368
+ const observed = await db
369
+ .select({
370
+ name: userEvents.source,
371
+ occurrences: count(),
372
+ firstSeenAt: min(userEvents.occurredAt),
373
+ lastSeenAt: max(userEvents.occurredAt),
374
+ })
375
+ .from(userEvents)
376
+ .where(isNotNull(userEvents.source))
377
+ .groupBy(userEvents.source)
378
+ .orderBy(desc(count()));
379
+
380
+ const connectors = new Map(
381
+ container.connectorRegistry
382
+ .getAll()
383
+ .map((conn) => [conn.meta.id, conn.meta.name ?? conn.meta.id]),
384
+ );
385
+
386
+ const entries = observed
387
+ .filter((row) => row.name !== null)
388
+ .map((row) => {
389
+ const name = row.name as string;
390
+ const connectorLabel = connectors.get(name);
391
+ return {
392
+ name,
393
+ occurrences: row.occurrences,
394
+ firstSeenAt: row.firstSeenAt?.toISOString() ?? null,
395
+ lastSeenAt: row.lastSeenAt?.toISOString() ?? null,
396
+ kind: connectorLabel
397
+ ? ("connector" as const)
398
+ : BUILTIN_SOURCES[name]
399
+ ? ("builtin" as const)
400
+ : ("observed" as const),
401
+ label: connectorLabel ?? BUILTIN_SOURCES[name] ?? null,
402
+ };
403
+ });
404
+
405
+ // Zero-backfill registered connectors that haven't fired yet, so a
406
+ // freshly-wired source is pickable before its first event arrives.
407
+ const seen = new Set(entries.map((e) => e.name));
408
+ for (const [id, label] of connectors) {
409
+ if (seen.has(id)) continue;
410
+ entries.push({
411
+ name: id,
412
+ occurrences: 0,
413
+ firstSeenAt: null,
414
+ lastSeenAt: null,
415
+ kind: "connector" as const,
416
+ label,
417
+ });
418
+ }
419
+
420
+ return c.json({ sources: entries }, 200);
421
+ })
295
422
  .openapi(getRoute, async (c) => {
296
423
  const { db } = c.get("container");
297
424
  const { id } = c.req.valid("param");
@@ -0,0 +1,369 @@
1
+ import {
2
+ type ConditionSet,
3
+ type FlagCreateInput,
4
+ type FlagTargeting,
5
+ type FlagUpdateInput,
6
+ type FlagVariant,
7
+ flagConditionSetSchema,
8
+ flagCreateSchema,
9
+ flagTargetingSchema,
10
+ flagUpdateSchema,
11
+ } from "@hogsend/core";
12
+ import { flags } from "@hogsend/db";
13
+ import { createRoute, OpenAPIHono, z } from "@hono/zod-openapi";
14
+ import { and, desc, eq, isNull } from "drizzle-orm";
15
+ import type { AppEnv } from "../../app.js";
16
+ import { errorSchema } from "../../lib/schemas.js";
17
+
18
+ /**
19
+ * Admin CRUD over the sovereign `flags` table (the Studio authoring surface).
20
+ * Inherits the admin router's `requireAdmin` guard, so it never re-auths here.
21
+ * Archive is a soft-delete (`archivedAt`) that frees the flag's key for reuse
22
+ * via the partial-unique live-row index.
23
+ */
24
+
25
+ const flagVariantSchema = z.object({
26
+ key: z.string(),
27
+ value: z.unknown(),
28
+ weight: z.number(),
29
+ });
30
+
31
+ const flagSchema = z.object({
32
+ id: z.string(),
33
+ key: z.string(),
34
+ name: z.string(),
35
+ description: z.string().nullable(),
36
+ enabled: z.boolean(),
37
+ type: z.string(),
38
+ variants: z.array(flagVariantSchema),
39
+ defaultValue: z.unknown(),
40
+ targeting: flagTargetingSchema,
41
+ rollout: z.number(),
42
+ conditionSets: z.array(flagConditionSetSchema),
43
+ origin: z.string(),
44
+ archivedAt: z.string().nullable(),
45
+ createdAt: z.string(),
46
+ updatedAt: z.string(),
47
+ });
48
+
49
+ /**
50
+ * Normalize a write body's targeting to the coherent pair the columns store:
51
+ * the ordered `conditionSets` (authoritative) AND the legacy `targeting`+
52
+ * `rollout` (synthesized from `conditionSets[0]` for readers that still read
53
+ * them). `conditionSets` wins when present; otherwise a single set is built
54
+ * from the legacy fields (an omitted `rollout` defaults to 100).
55
+ */
56
+ function normalizeWrite(body: FlagCreateInput | FlagUpdateInput): {
57
+ conditionSets: ConditionSet[];
58
+ targeting: FlagTargeting;
59
+ rollout: number;
60
+ } {
61
+ const first = body.conditionSets?.[0];
62
+ if (body.conditionSets && first) {
63
+ return {
64
+ conditionSets: body.conditionSets,
65
+ targeting: first.targeting as FlagTargeting,
66
+ rollout: first.rollout,
67
+ };
68
+ }
69
+ const targeting = (body.targeting ?? []) as FlagTargeting;
70
+ const rollout = body.rollout ?? 100;
71
+ return { conditionSets: [{ targeting, rollout }], targeting, rollout };
72
+ }
73
+
74
+ function serializeFlag(row: typeof flags.$inferSelect) {
75
+ // Back-compat synthesis: a flag that predates condition sets (NULL column)
76
+ // reads as a single set built from the legacy targeting+rollout columns.
77
+ const conditionSets: ConditionSet[] = (row.conditionSets as
78
+ | ConditionSet[]
79
+ | null) ?? [
80
+ { targeting: row.targeting as FlagTargeting, rollout: row.rollout },
81
+ ];
82
+ return {
83
+ id: row.id,
84
+ key: row.key,
85
+ name: row.name,
86
+ description: row.description ?? null,
87
+ enabled: row.enabled,
88
+ type: row.type,
89
+ variants: row.variants as FlagVariant[],
90
+ defaultValue: row.defaultValue,
91
+ targeting: row.targeting as FlagTargeting,
92
+ rollout: row.rollout,
93
+ conditionSets,
94
+ origin: row.origin,
95
+ archivedAt: row.archivedAt?.toISOString() ?? null,
96
+ createdAt: row.createdAt.toISOString(),
97
+ updatedAt: row.updatedAt.toISOString(),
98
+ };
99
+ }
100
+
101
+ const listRoute = createRoute({
102
+ method: "get",
103
+ path: "/",
104
+ tags: ["Admin — Flags"],
105
+ summary: "List flags",
106
+ request: {
107
+ query: z.object({
108
+ includeArchived: z.coerce.boolean().optional(),
109
+ }),
110
+ },
111
+ responses: {
112
+ 200: {
113
+ content: {
114
+ "application/json": {
115
+ schema: z.object({ flags: z.array(flagSchema) }),
116
+ },
117
+ },
118
+ description: "Flags",
119
+ },
120
+ },
121
+ });
122
+
123
+ const createFlagRoute = createRoute({
124
+ method: "post",
125
+ path: "/",
126
+ tags: ["Admin — Flags"],
127
+ summary: "Create a flag",
128
+ request: {
129
+ body: { content: { "application/json": { schema: flagCreateSchema } } },
130
+ },
131
+ responses: {
132
+ 201: {
133
+ content: {
134
+ "application/json": { schema: z.object({ flag: flagSchema }) },
135
+ },
136
+ description: "Flag created",
137
+ },
138
+ 409: {
139
+ content: { "application/json": { schema: errorSchema } },
140
+ description: "A live flag with that key already exists",
141
+ },
142
+ },
143
+ });
144
+
145
+ const updateFlagRoute = createRoute({
146
+ method: "patch",
147
+ path: "/{id}",
148
+ tags: ["Admin — Flags"],
149
+ summary: "Update a flag (toggle enabled, edit targeting/rollout/variants)",
150
+ request: {
151
+ params: z.object({ id: z.string().uuid() }),
152
+ body: { content: { "application/json": { schema: flagUpdateSchema } } },
153
+ },
154
+ responses: {
155
+ 200: {
156
+ content: {
157
+ "application/json": { schema: z.object({ flag: flagSchema }) },
158
+ },
159
+ description: "Flag updated",
160
+ },
161
+ 404: {
162
+ content: { "application/json": { schema: errorSchema } },
163
+ description: "Flag not found",
164
+ },
165
+ 409: {
166
+ content: { "application/json": { schema: errorSchema } },
167
+ description: "A live flag with that key already exists",
168
+ },
169
+ },
170
+ });
171
+
172
+ const archiveFlagRoute = createRoute({
173
+ method: "delete",
174
+ path: "/{id}",
175
+ tags: ["Admin — Flags"],
176
+ summary: "Archive a flag (soft-delete; frees the key)",
177
+ request: {
178
+ params: z.object({ id: z.string().uuid() }),
179
+ },
180
+ responses: {
181
+ 200: {
182
+ content: {
183
+ "application/json": {
184
+ schema: z.object({ archived: z.boolean() }),
185
+ },
186
+ },
187
+ description: "Flag archived",
188
+ },
189
+ 404: {
190
+ content: { "application/json": { schema: errorSchema } },
191
+ description: "Flag not found",
192
+ },
193
+ },
194
+ });
195
+
196
+ export const adminFlagsRouter = new OpenAPIHono<AppEnv>()
197
+ .openapi(listRoute, async (c) => {
198
+ const { db } = c.get("container");
199
+ const { includeArchived } = c.req.valid("query");
200
+ const rows = await db
201
+ .select()
202
+ .from(flags)
203
+ .where(includeArchived ? undefined : isNull(flags.archivedAt))
204
+ .orderBy(desc(flags.createdAt));
205
+ return c.json({ flags: rows.map(serializeFlag) }, 200);
206
+ })
207
+ .openapi(createFlagRoute, async (c) => {
208
+ const { db } = c.get("container");
209
+ const body = c.req.valid("json");
210
+
211
+ // Enforce the live-key uniqueness explicitly for a friendly 409 (the
212
+ // partial-unique index is the ultimate backstop).
213
+ const existing = await db
214
+ .select({ id: flags.id })
215
+ .from(flags)
216
+ .where(and(eq(flags.key, body.key), isNull(flags.archivedAt)))
217
+ .limit(1);
218
+ if (existing[0]) {
219
+ return c.json({ error: "A live flag with that key already exists" }, 409);
220
+ }
221
+
222
+ // A boolean flag's default is `false` when unspecified (the spec's served
223
+ // value when disabled / targeting fails / outside the rollout).
224
+ const defaultValue =
225
+ body.defaultValue !== undefined
226
+ ? body.defaultValue
227
+ : body.type === "boolean"
228
+ ? false
229
+ : null;
230
+
231
+ const write = normalizeWrite(body);
232
+ const [created] = await db
233
+ .insert(flags)
234
+ .values({
235
+ key: body.key,
236
+ name: body.name,
237
+ description: body.description,
238
+ enabled: body.enabled,
239
+ type: body.type,
240
+ variants: body.variants ?? [],
241
+ defaultValue,
242
+ targeting: write.targeting,
243
+ rollout: write.rollout,
244
+ conditionSets: write.conditionSets,
245
+ })
246
+ .returning();
247
+ if (!created) throw new Error("Failed to create flag");
248
+ return c.json({ flag: serializeFlag(created) }, 201);
249
+ })
250
+ .openapi(updateFlagRoute, async (c) => {
251
+ const { db } = c.get("container");
252
+ const { id } = c.req.valid("param");
253
+ const body = c.req.valid("json");
254
+
255
+ const rows = await db.select().from(flags).where(eq(flags.id, id)).limit(1);
256
+ if (!rows[0]) return c.json({ error: "Flag not found" }, 404);
257
+
258
+ // A key rename must stay unique among LIVE flags (the partial-unique index
259
+ // is the backstop; this is the friendly 409). Skip when the key is
260
+ // unchanged so re-saving the same flag never self-collides.
261
+ if (body.key !== undefined && body.key !== rows[0].key) {
262
+ const clash = await db
263
+ .select({ id: flags.id })
264
+ .from(flags)
265
+ .where(and(eq(flags.key, body.key), isNull(flags.archivedAt)))
266
+ .limit(1);
267
+ if (clash[0]) {
268
+ return c.json(
269
+ { error: "A live flag with that key already exists" },
270
+ 409,
271
+ );
272
+ }
273
+ }
274
+
275
+ // Targeting write: recompute the coherent (conditionSets + legacy) triple
276
+ // when the caller touches ANY of conditionSets/targeting/rollout. An
277
+ // explicit `conditionSets` is authoritative. A legacy-field-only edit (bare
278
+ // targeting/rollout) merges into the EXISTING first set and PRESERVES
279
+ // sets[1..], so a rollout bump on a multi-set flag never silently destroys
280
+ // its other sets. The legacy `targeting`/`rollout` columns mirror set[0].
281
+ const touchesTargeting =
282
+ body.conditionSets !== undefined ||
283
+ body.targeting !== undefined ||
284
+ body.rollout !== undefined;
285
+ let targetingWrite:
286
+ | {
287
+ conditionSets: ConditionSet[];
288
+ targeting: FlagTargeting;
289
+ rollout: number;
290
+ }
291
+ | undefined;
292
+ if (touchesTargeting) {
293
+ const first = body.conditionSets?.[0];
294
+ if (body.conditionSets && first) {
295
+ targetingWrite = {
296
+ conditionSets: body.conditionSets,
297
+ targeting: first.targeting as FlagTargeting,
298
+ rollout: first.rollout,
299
+ };
300
+ } else {
301
+ // Existing sets to merge into (back-compat: a NULL column synthesizes a
302
+ // single set from the legacy targeting+rollout columns).
303
+ const existing = rows[0].conditionSets as ConditionSet[] | null;
304
+ const base =
305
+ existing && existing.length > 0
306
+ ? existing
307
+ : [
308
+ {
309
+ targeting: rows[0].targeting as FlagTargeting,
310
+ rollout: rows[0].rollout,
311
+ },
312
+ ];
313
+ const targeting = (body.targeting ??
314
+ base[0]?.targeting ??
315
+ rows[0].targeting) as FlagTargeting;
316
+ const rollout = body.rollout ?? base[0]?.rollout ?? rows[0].rollout;
317
+ targetingWrite = {
318
+ conditionSets: [{ targeting, rollout }, ...base.slice(1)],
319
+ targeting,
320
+ rollout,
321
+ };
322
+ }
323
+ }
324
+
325
+ const [updated] = await db
326
+ .update(flags)
327
+ .set({
328
+ ...(body.key !== undefined ? { key: body.key } : {}),
329
+ ...(body.name !== undefined ? { name: body.name } : {}),
330
+ ...(body.description !== undefined
331
+ ? { description: body.description }
332
+ : {}),
333
+ ...(body.enabled !== undefined ? { enabled: body.enabled } : {}),
334
+ ...(body.type !== undefined ? { type: body.type } : {}),
335
+ ...(body.variants !== undefined ? { variants: body.variants } : {}),
336
+ ...(body.defaultValue !== undefined
337
+ ? { defaultValue: body.defaultValue }
338
+ : {}),
339
+ ...(targetingWrite
340
+ ? {
341
+ targeting: targetingWrite.targeting,
342
+ rollout: targetingWrite.rollout,
343
+ conditionSets: targetingWrite.conditionSets,
344
+ }
345
+ : {}),
346
+ updatedAt: new Date(),
347
+ })
348
+ .where(eq(flags.id, id))
349
+ .returning();
350
+ if (!updated) throw new Error("Failed to update flag");
351
+ return c.json({ flag: serializeFlag(updated) }, 200);
352
+ })
353
+ .openapi(archiveFlagRoute, async (c) => {
354
+ const { db } = c.get("container");
355
+ const { id } = c.req.valid("param");
356
+
357
+ const rows = await db
358
+ .select()
359
+ .from(flags)
360
+ .where(and(eq(flags.id, id), isNull(flags.archivedAt)))
361
+ .limit(1);
362
+ if (!rows[0]) return c.json({ error: "Flag not found" }, 404);
363
+
364
+ await db
365
+ .update(flags)
366
+ .set({ archivedAt: new Date(), updatedAt: new Date() })
367
+ .where(eq(flags.id, id));
368
+ return c.json({ archived: true }, 200);
369
+ });