@sentry/junior 0.312.0 → 0.314.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 (115) hide show
  1. package/dist/{adapter-iIq7ihf7.js → adapter-JARQvoLw.js} +1 -2
  2. package/dist/{adapter-context-BRjEWRy1.js → adapter-context-B4BrJZuS.js} +2 -2
  3. package/dist/{admin-DhInw5K9.js → admin-BXGAySz0.js} +1 -1
  4. package/dist/{agent-runner-C9iDurwX.js → agent-runner-qZU5TR8i.js} +865 -138
  5. package/dist/agent-update-cS7Z9mnG.js +26 -0
  6. package/dist/agent-update-delivery-CZ5M8RDa.js +85 -0
  7. package/dist/api/schema.d.ts +2 -2
  8. package/dist/api/schema.js +6 -6
  9. package/dist/api.d.ts +1 -1
  10. package/dist/api.js +340 -106
  11. package/dist/{app-DRFrC8Mw.d.ts → app-D7tKnw9a.d.ts} +4 -21
  12. package/dist/app.d.ts +2 -2
  13. package/dist/app.js +80 -171
  14. package/dist/{background-compaction-queue-DrKi7w3d.js → background-compaction-queue-C_uIBUvS.js} +6 -17
  15. package/dist/{callback-mFlTUWWx.js → callback-C8SdXCwr.js} +4 -11
  16. package/dist/{catalog-runtime-D7xapBAX.js → catalog-runtime-BLKtnUL3.js} +1 -1
  17. package/dist/{channel-access-CJGfNTdn.js → channel-access-BOL29BG3.js} +6 -6
  18. package/dist/child-message--2G3Ft26.js +19 -0
  19. package/dist/cli/chat.js +18 -21
  20. package/dist/cli/check.js +4 -4
  21. package/dist/cli/main.js +2 -2
  22. package/dist/cli/plugins.js +5 -5
  23. package/dist/cli/snapshot-create.js +5 -5
  24. package/dist/cli/upgrade.d.ts +1 -1
  25. package/dist/cli/upgrade.js +23 -4
  26. package/dist/{config-kXB2Y5tl.js → config-BIfHKNXN.js} +40 -35
  27. package/dist/{continue-in-slack-O6pV5004.js → continue-in-slack-fnmD2Ifb.js} +5 -7
  28. package/dist/{conversation-feed-uNOv_x68.js → conversation-feed-DdFQuQDR.js} +13 -2
  29. package/dist/{logging-dQ9ZRGQ8.js → conversation-privacy-DtZhI91r.js} +188 -2
  30. package/dist/{conversation-turn-CeLbHqdw.js → conversation-turn-DScuDYmN.js} +465 -62
  31. package/dist/create-CrNt4Ewu.js +212 -0
  32. package/dist/{credential-sync-I8VBGk05.js → credential-sync-CtqsGjj1.js} +14 -18
  33. package/dist/{credentialed-Cb6E2phL.js → credentialed-dWRA3-oJ.js} +911 -429
  34. package/dist/{db-LAyyX8tk.js → db-BTmLKZrp.js} +2245 -50
  35. package/dist/{db-BbC5stfa.d.ts → db-DcmzbA55.d.ts} +2 -2
  36. package/dist/{history-CYstOMKX.js → history-CneKY7_V.js} +19 -1
  37. package/dist/{html-BCZ3Xtb_.js → html-B8rBt7F4.js} +5 -7
  38. package/dist/{install-DCFJFkC0.js → install-OtFboxOM.js} +2 -2
  39. package/dist/instrumentation.js +2 -2
  40. package/dist/{lineage-B_m-4TJw.js → lineage-EULJkGO1.js} +1 -2
  41. package/dist/{list-CN2QA2R9.js → list-C5400AlJ.js} +284 -113
  42. package/dist/{thread-state-DhPndWi1.js → mailbox-turn-DL3Lvsm0.js} +4830 -485
  43. package/dist/markers-DUP8aBOp.js +323 -0
  44. package/dist/{media-CYm1QD8T.js → media-FYM-Bl3H.js} +42 -14
  45. package/dist/{message-DSXGj1hM.js → message-DuDelZFr.js} +16 -15
  46. package/dist/{model-input--TrP9hYV.js → model-input-0osF3pBS.js} +3 -3
  47. package/dist/nitro.d.ts +2 -4
  48. package/dist/nitro.js +340 -13
  49. package/dist/{oauth-callback-server-DHCZC6B4.js → oauth-callback-server-DX2fQ7Nq.js} +2 -2
  50. package/dist/{oauth-relay-pPMGnDZt.js → oauth-relay-PwPMdZJv.js} +1 -1
  51. package/dist/{plugins-Bkk0XRo2.js → plugins-BXMdNdyA.js} +1 -1
  52. package/dist/{registry-CZOzddwu.js → registry-D6kS6xYH.js} +1402 -64
  53. package/dist/{statuses-_cRJHXK7.js → reporting-window-C4dbzDiR.js} +1 -27
  54. package/dist/{resolve-cKOQ14Dh.js → resolve-D8CPJcNK.js} +3 -3
  55. package/dist/result-D090hxr5.js +402 -0
  56. package/dist/{runner-DBfUW44l.js → runner-BU7fgrm-.js} +7 -8
  57. package/dist/{sandbox-egress-signals-BVF_xAm1.js → sandbox-egress-signals-BUmVrsoG.js} +1 -1
  58. package/dist/{schema-Bk9Nm2E8.js → schema-7gW9vBpJ.js} +91 -10
  59. package/dist/{schema-BEHKxr4I.d.ts → schema-BB6E0wyV.d.ts} +2105 -2753
  60. package/dist/{service-account-CVYsFjty.js → service-account-plA-uzIB.js} +6 -5
  61. package/dist/{skills-VTnhAJWm.js → skills-CIosT6bS.js} +3 -3
  62. package/dist/{slack-conversation-unfurl-fuLnF1jE.js → slack-conversation-unfurl-CBgZqth6.js} +8 -10
  63. package/dist/spawn-DRjdzh3R.js +46 -0
  64. package/dist/{start-conversation-CEn2KH1A.js → start-conversation-a4NXH4X9.js} +13 -202
  65. package/dist/{store-DFZaN-Ix.js → store-BuhF1QDm.js} +2 -4
  66. package/dist/{task-queue-Cx4Lmjyk.js → task-queue-CrRjFzOh.js} +5 -16
  67. package/dist/{task-runner-CbTwFA6k.js → task-runner-C-pXsgHM.js} +105 -51
  68. package/dist/{thread-context-BkAZDTX2.js → thread-context-CDX4dSZd.js} +8 -10
  69. package/dist/turn-session-routing-CZTRU8IY.js +116 -0
  70. package/dist/turn-wake-Bzq1Efrm.js +154 -0
  71. package/dist/user-customization-B27StpVQ.js +9 -0
  72. package/dist/{validation-nIzMtAVJ.js → validation-bTq88sya.js} +1 -1
  73. package/dist/{vercel-queue-hW90XzbG.js → vercel-queue-nL0Hq3hr.js} +32 -147
  74. package/dist/{version-Brbtz4Qf.js → version-DGUa1dZK.js} +1 -1
  75. package/dist/version.js +1 -1
  76. package/dist/{warmup-BDA5myRK.js → warmup-CCOuIwAS.js} +831 -3254
  77. package/dist/{worker-D63RcaVD.js → worker-AkZg7Dg1.js} +5 -6
  78. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  79. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  80. package/migrations/0160_money_micro_usd_repair.sql +99 -0
  81. package/migrations/0161_agent_config_backfill.sql +34 -0
  82. package/migrations/0162_inbox_item_deliveries.sql +15 -0
  83. package/migrations/0163_pg_trgm.sql +2 -0
  84. package/migrations/0164_search_indexes.sql +4 -0
  85. package/migrations/0165_drop_legacy_archive_columns.sql +4 -0
  86. package/migrations/0166_memory_prefix_index.sql +1 -0
  87. package/migrations/0167_todo_search_indexes.sql +2 -0
  88. package/migrations/0168_todo_inbox_items.sql +4 -0
  89. package/migrations/0169_drop_code_urls.sql +2 -0
  90. package/migrations/meta/0158_snapshot.json +6515 -0
  91. package/migrations/meta/0159_snapshot.json +6515 -0
  92. package/migrations/meta/0160_snapshot.json +6515 -0
  93. package/migrations/meta/0161_snapshot.json +6278 -0
  94. package/migrations/meta/0162_snapshot.json +6404 -0
  95. package/migrations/meta/0163_snapshot.json +6404 -0
  96. package/migrations/meta/0164_snapshot.json +6466 -0
  97. package/migrations/meta/0165_snapshot.json +6466 -0
  98. package/migrations/meta/0166_snapshot.json +6494 -0
  99. package/migrations/meta/0167_snapshot.json +6525 -0
  100. package/migrations/meta/0168_snapshot.json +6525 -0
  101. package/migrations/meta/0169_snapshot.json +6513 -0
  102. package/migrations/meta/_journal.json +84 -0
  103. package/package.json +9 -18
  104. package/skills/design-automation-skill/SKILL.md +2 -3
  105. package/dist/actor-BsBdxDXQ.js +0 -208
  106. package/dist/child-message-DcsritGf.js +0 -179
  107. package/dist/conversation-privacy-L4ja1_W6.js +0 -189
  108. package/dist/executor-SCub-fAq.js +0 -1860
  109. package/dist/fan-out-Cod-yEHG.js +0 -10
  110. package/dist/ingest-BDf3D50j.js +0 -3836
  111. package/dist/result-DcvEOe1r.js +0 -574
  112. package/dist/result-event-type-BdIJuZxg.js +0 -48
  113. package/dist/service-account-Ts4ulcrV.js +0 -931
  114. package/dist/spawn-vxAarlX5.js +0 -73
  115. package/dist/state-C1P3_Ywk.js +0 -161
@@ -1,17 +1,82 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { N as cacheKeyPrefix, P as createCache, r as getChatConfig } from "./config-kXB2Y5tl.js";
3
- import { a as isSlackUserId, d as parseSlackChannelReferenceId, f as parseSlackTeamId, s as parseActorUserId } from "./actor-BsBdxDXQ.js";
4
- import { A as juniorConversationMetrics, B as juniorAttachments, C as juniorConversationParticipants, H as juniorConversations, K as juniorUsers, M as juniorConversationEvents, P as juniorConversationAnnotations, S as juniorConversationReadPositions, T as juniorConversationBriefs, U as juniorIdentities, V as juniorMessageAttachments, _ as juniorAutomationRuns, f as juniorInboxItemAssignees, g as juniorAutomations, h as juniorInboxItems, j as isUserInstruction, k as CONVERSATION_METRICS, p as juniorInboxItemConversations, q as juniorDestinations, t as createJuniorSqlExecutor, w as juniorConversationBindings } from "./executor-SCub-fAq.js";
5
- import { c as newConversationEventSchema, h as usageSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema } from "./history-CYstOMKX.js";
6
- import { t as canExposeConversationPayload } from "./conversation-privacy-L4ja1_W6.js";
7
- import { t as mapBounded } from "./fan-out-Cod-yEHG.js";
8
- import { J as normalizeIdentityEmail, K as GOOGLE_IDENTITY_PROVIDER, h as logWarn } from "./logging-dQ9ZRGQ8.js";
9
- import { i as getStateAdapter } from "./adapter-iIq7ihf7.js";
2
+ import { N as cacheKeyPrefix, P as createCache, gt as mapBounded, r as getChatConfig } from "./config-BIfHKNXN.js";
3
+ import { b as usageSchema, c as newConversationEventSchema, l as encodeHistoryPayload, o as decodeStoredConversationEvent, r as conversationEventDataSchema, s as historyReplacementSchema, v as UPDATE_TODOS_TOOL_NAME } from "./history-CneKY7_V.js";
4
+ import { S as logException, rt as normalizeIdentityEmail, t as canExposeConversationPayload, tt as GOOGLE_IDENTITY_PROVIDER, w as logWarn } from "./conversation-privacy-DtZhI91r.js";
5
+ import { i as getStateAdapter } from "./adapter-JARQvoLw.js";
6
+ import { _ as withScope } from "./sentry-CPbZjomA.js";
10
7
  import * as z from "zod";
8
+ import { AsyncLocalStorage } from "node:async_hooks";
11
9
  import { createHash, randomUUID } from "node:crypto";
12
- import { PluginToolInputError, destinationSchema, identitySchema, locationSchema, sourceSchema, userSchema } from "@sentry/junior-plugin-api";
13
- import { and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, or, sql } from "drizzle-orm";
14
- import { alias } from "drizzle-orm/pg-core";
10
+ import { PluginToolInputError, actorSchema, destinationSchema, identitySchema, locationSchema, sourceSchema, userSchema } from "@sentry/junior-plugin-api";
11
+ import { SQL, and, asc, desc, eq, exists, gt, gte, inArray, isNotNull, isNull, lt, lte, ne, not, notLike, or, sql } from "drizzle-orm";
12
+ import { alias, bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
13
+ import { Pool as Pool$1, neon } from "@neondatabase/serverless";
14
+ import { drizzle } from "drizzle-orm/neon-serverless";
15
+ import { Agent } from "undici";
16
+ import { readMigrationFiles } from "drizzle-orm/migrator";
17
+ import pg from "pg";
18
+ import { drizzle as drizzle$1 } from "drizzle-orm/node-postgres";
19
+ // src/chat/slack/timestamp.ts
20
+ /** Native Slack message timestamp, safe to pass as Slack Web API `message_ts`. */
21
+ const slackMessageTsSchema = z.string().trim().regex(/^\d+(?:\.\d+)?$/).brand();
22
+ /** Parse a native Slack message timestamp from untrusted message metadata. */
23
+ function parseSlackMessageTs(value) {
24
+ const parsed = slackMessageTsSchema.safeParse(value);
25
+ return parsed.success ? parsed.data : void 0;
26
+ }
27
+ /**
28
+ * Write a time in milliseconds as a Slack timestamp, for input that has no
29
+ * Slack message of its own, such as a submitted form.
30
+ */
31
+ function slackMessageTsFromMs(ms) {
32
+ return slackMessageTsSchema.parse((ms / 1e3).toFixed(6));
33
+ }
34
+ // src/chat/slack/ids.ts
35
+ const slackChannelIdSchema = z.string().regex(/^[CDG][A-Z0-9]+$/).brand();
36
+ const slackTeamIdSchema = z.string().regex(/^T[A-Z0-9]+$/).brand();
37
+ const slackUserIdSchema = z.string().regex(/^[UW][A-Z0-9]+$/).brand();
38
+ const slackBotIdSchema = z.string().regex(/^B[A-Z0-9]+$/).brand();
39
+ const SLACK_CHANNEL_MENTION_RE = /^<#([CDG][A-Z0-9]+)(?:\|[^>]*)?>$/;
40
+ function slackChannelReferenceCandidate(value) {
41
+ const trimmed = value.trim();
42
+ if (!trimmed.startsWith("slack:")) return trimmed;
43
+ const parts = trimmed.split(":");
44
+ if (parts.length === 2) return parts[1]?.trim() ?? "";
45
+ if (parts.length === 3 && parseSlackMessageTs(parts[2])) return parts[1]?.trim() ?? "";
46
+ return "";
47
+ }
48
+ /** Parse an exact Slack channel/conversation ID from untrusted input. */
49
+ function parseSlackChannelId(value) {
50
+ if (typeof value !== "string") return void 0;
51
+ const parsed = slackChannelIdSchema.safeParse(value.trim());
52
+ return parsed.success ? parsed.data : void 0;
53
+ }
54
+ /**
55
+ * Parse a channel id from common tool/model reference forms.
56
+ *
57
+ * Accepts exact ids (`C123`), Slack mentions (`<#C123>` / `<#C123|name>`),
58
+ * and Junior slack references (`slack:C123`, `slack:C123:ts`). Plain channel
59
+ * names are not ids and are rejected here.
60
+ */
61
+ function parseSlackChannelReferenceId(value) {
62
+ if (typeof value !== "string") return void 0;
63
+ const trimmed = value.trim();
64
+ const mentionMatch = SLACK_CHANNEL_MENTION_RE.exec(trimmed);
65
+ if (mentionMatch?.[1]) return parseSlackChannelId(mentionMatch[1]);
66
+ return parseSlackChannelId(slackChannelReferenceCandidate(trimmed));
67
+ }
68
+ /** Parse a Slack workspace/team ID from untrusted metadata. */
69
+ function parseSlackTeamId(value) {
70
+ if (typeof value !== "string") return void 0;
71
+ const parsed = slackTeamIdSchema.safeParse(value.trim());
72
+ return parsed.success ? parsed.data : void 0;
73
+ }
74
+ /** Parse a Slack user ID from untrusted metadata. */
75
+ function parseSlackUserId(value) {
76
+ if (typeof value !== "string") return void 0;
77
+ const parsed = slackUserIdSchema.safeParse(value.trim());
78
+ return parsed.success ? parsed.data : void 0;
79
+ }
15
80
  // src/chat/destination.ts
16
81
  /** Build Junior's canonical destination from Slack workspace and channel ids. */
17
82
  function createSlackDestination(input) {
@@ -41,6 +106,1398 @@ function sameDestination(left, right) {
41
106
  if (left.platform === "slack" && right.platform === "slack") return left.teamId === right.teamId && left.channelId === right.channelId;
42
107
  return false;
43
108
  }
109
+ // src/db/schema/timestamps.ts
110
+ const timestamptz = (name) => timestamp(name, { withTimezone: true });
111
+ // src/db/schema/artifacts.ts
112
+ /** Durable metadata for conversation-owned artifacts. */
113
+ const juniorArtifacts = pgTable("junior_artifacts", {
114
+ /** Row identity. A public row serves at `/public/artifacts/<id>.<ext>`. */
115
+ id: text("id").primaryKey(),
116
+ conversationId: text("conversation_id").notNull(),
117
+ sha256: text("sha256").notNull(),
118
+ ext: text("ext").notNull(),
119
+ storageKey: text("storage_key").notNull(),
120
+ contentType: text("content_type").notNull(),
121
+ bytes: integer("bytes").notNull(),
122
+ /**
123
+ * Path under the Sandbox `artifacts/` directory for a live file. Null for
124
+ * a public frozen copy, such as a published image.
125
+ */
126
+ path: text("path"),
127
+ visibility: text("visibility").$type().notNull().default("conversation"),
128
+ createdAt: timestamptz("created_at").notNull(),
129
+ /** Set when the artifact is unpublished or its live file is deleted. */
130
+ deleteRequestedAt: timestamptz("delete_requested_at"),
131
+ /** When a public artifact stops serving. Null serves until unpublished. */
132
+ expiresAt: timestamptz("expires_at")
133
+ }, (table) => [
134
+ check("junior_artifacts_visibility_check", sql`${table.visibility} in ('conversation', 'internal', 'public')`),
135
+ check("junior_artifacts_path_visibility_check", sql`(${table.path} is null) = (${table.visibility} = 'public')`),
136
+ uniqueIndex("junior_artifacts_conversation_path_uidx").on(table.conversationId, table.path),
137
+ uniqueIndex("junior_artifacts_permanent_sha_uidx").on(table.conversationId, table.sha256).where(sql`${table.visibility} = 'public' and ${table.expiresAt} is null`),
138
+ index("junior_artifacts_gc_idx").on(table.deleteRequestedAt, table.createdAt),
139
+ index("junior_artifacts_conversation_idx").on(table.conversationId)
140
+ ]);
141
+ // src/db/embeddings.ts
142
+ /**
143
+ * Shared parts of the derived embedding indexes. Each owner keeps its own
144
+ * table, so a foreign key still deletes a vector with its source row. These
145
+ * helpers keep the column types, the distance SQL, the batch checks, and the
146
+ * backfill loop the same in every table.
147
+ */
148
+ function pgvectorColumn(dataType) {
149
+ return customType({
150
+ dataType() {
151
+ return dataType;
152
+ },
153
+ toDriver(value) {
154
+ return JSON.stringify(value);
155
+ },
156
+ fromDriver(value) {
157
+ return value.slice(1, -1).split(",").map(Number);
158
+ }
159
+ });
160
+ }
161
+ /**
162
+ * pgvector `vector` column without a fixed size, so a new embedding model
163
+ * needs no migration. Each table records the size of each row in its own
164
+ * column.
165
+ */
166
+ const embeddingVector = pgvectorColumn("vector");
167
+ /**
168
+ * Half-precision `embeddingVector`: 2 bytes per value instead of 4, for
169
+ * tables that hold many vectors.
170
+ */
171
+ const embeddingHalfvec = pgvectorColumn("halfvec");
172
+ const embeddingResultSchema = z.object({
173
+ costUsd: z.number().finite().nonnegative().optional(),
174
+ dimensions: z.number().int().positive(),
175
+ model: z.string().min(1),
176
+ provider: z.string().min(1),
177
+ vectors: z.array(z.array(z.number().finite()))
178
+ }).strict();
179
+ /**
180
+ * Validate an embedder result: one vector per text, all of the reported
181
+ * size. With `dimensions`, the size must be one that the table accepts. With
182
+ * `expected`, the result must come from that provider and model, because a
183
+ * backfill that finds rows by model would see a row of another model as
184
+ * missing on every run.
185
+ */
186
+ function parseEmbeddingBatch(raw, args) {
187
+ const result = embeddingResultSchema.parse(raw);
188
+ if (args.dimensions && !args.dimensions.includes(result.dimensions)) throw new Error("Unsupported embedding vector size.");
189
+ if (result.vectors.length !== args.textCount) throw new Error("Embedding provider returned an unexpected vector count.");
190
+ if (result.vectors.some((vector) => vector.length !== result.dimensions)) throw new Error("Embedding provider returned an unexpected vector size.");
191
+ if (args.expected && (result.provider !== args.expected.provider || result.model !== args.expected.model)) throw new Error(`Embedding provider used model ${result.provider}/${result.model}, not ${args.expected.provider}/${args.expected.model}.`);
192
+ return {
193
+ dimensions: result.dimensions,
194
+ model: result.model,
195
+ provider: result.provider,
196
+ vectors: result.vectors
197
+ };
198
+ }
199
+ /** Embed one text with the embedder's model and return its vector. */
200
+ async function embedText(embedder, input) {
201
+ const batch = parseEmbeddingBatch(await embedder.embedTexts({
202
+ inputType: input.inputType,
203
+ texts: [input.text]
204
+ }), {
205
+ expected: embedder,
206
+ textCount: 1
207
+ });
208
+ return {
209
+ model: batch.model,
210
+ provider: batch.provider,
211
+ vector: batch.vectors[0]
212
+ };
213
+ }
214
+ function vectorSize(query) {
215
+ if (query.length === 0) throw new Error("Embedding vector is empty.");
216
+ return sql.raw(String(query.length));
217
+ }
218
+ /**
219
+ * Cosine distance from a stored vector to a query vector. Both sides are cast
220
+ * to the query size, the form that an HNSW expression index on that size
221
+ * matches. The cast fails on a stored vector of another size, so filter on the
222
+ * size first, as the index predicate does, or use `guardedCosineDistance`.
223
+ * A caller with another copy of drizzle-orm embeds the result in its own
224
+ * `sql` template to get its own `SQL` type.
225
+ */
226
+ function cosineDistance(args) {
227
+ const size = vectorSize(args.query);
228
+ const type = sql.raw(args.type);
229
+ return sql`(${args.column}::${type}(${size})) <=> ${JSON.stringify(args.query)}::${type}(${size})`;
230
+ }
231
+ /**
232
+ * `cosineDistance`, or null for a stored vector of another size. Postgres
233
+ * does not promise to check a WHERE term before it computes an ORDER BY or
234
+ * SELECT expression, and pgvector fails on vectors of two sizes. CASE fixes
235
+ * the order.
236
+ */
237
+ function guardedCosineDistance(args) {
238
+ return sql`CASE WHEN ${args.dimensions} = ${vectorSize(args.query)} THEN ${cosineDistance(args)} END`;
239
+ }
240
+ /**
241
+ * Embed items that have no current vector, one batch at a time, and store
242
+ * each batch before the next starts. `listMissing` returns the next items in
243
+ * the caller's order, after the last item of the previous page, so each run
244
+ * ends even when a write leaves an item missing. Text that trims to nothing
245
+ * is skipped, because the embedder rejects it. A provider failure stops the
246
+ * run and keeps the batches stored before it, so a later run continues.
247
+ */
248
+ async function refreshEmbeddings(args) {
249
+ const now = args.now ?? Date.now;
250
+ let after;
251
+ let embedded = 0;
252
+ for (;;) {
253
+ const remaining = (args.maxItems ?? 1e400) - embedded;
254
+ if (remaining <= 0 || args.deadlineMs !== void 0 && now() >= args.deadlineMs) return {
255
+ done: false,
256
+ embedded
257
+ };
258
+ const page = await args.listMissing({
259
+ after,
260
+ limit: Math.min(args.batchSize, remaining)
261
+ });
262
+ after = page.at(-1);
263
+ if (!after) return {
264
+ done: true,
265
+ embedded
266
+ };
267
+ const items = page.filter((item) => item.text.trim() !== "");
268
+ if (items.length === 0) continue;
269
+ const batch = parseEmbeddingBatch(await args.embedder.embedTexts({
270
+ inputType: "document",
271
+ texts: items.map((item) => item.text)
272
+ }), {
273
+ ...args.dimensions ? { dimensions: args.dimensions } : void 0,
274
+ expected: args.embedder,
275
+ textCount: items.length
276
+ });
277
+ await args.write(items.map((item, index) => ({
278
+ item,
279
+ vector: batch.vectors[index]
280
+ })), batch);
281
+ embedded += items.length;
282
+ }
283
+ }
284
+ // src/db/schema/tsvector.ts
285
+ /** Postgres full-text lexemes. Queries read them only through SQL. */
286
+ const tsvector = customType({ dataType() {
287
+ return "tsvector";
288
+ } });
289
+ // src/chat/memory/types.ts
290
+ const MEMORY_KINDS = [
291
+ "preference",
292
+ "procedure",
293
+ "knowledge"
294
+ ];
295
+ const MEMORY_SCOPES = ["private", "public"];
296
+ const MEMORY_SUBJECT_TYPES = [
297
+ "user",
298
+ "conversation",
299
+ "general"
300
+ ];
301
+ const MEMORY_SOURCE_PLATFORMS = [
302
+ "slack",
303
+ "local",
304
+ "web"
305
+ ];
306
+ const MEMORY_EMBEDDING_METRICS = ["cosine"];
307
+ /** Things that can happen to a stored memory and feed future recall weights. */
308
+ /** `contradicted` and `superseded` record why a memory was retired. */
309
+ const MEMORY_SIGNALS = [
310
+ "duplicate",
311
+ "contradicted",
312
+ "superseded"
313
+ ];
314
+ /**
315
+ * Vector sizes the embeddings table can store, so one table can hold vectors
316
+ * from an old and a new model while a model change is in progress. Only 1024
317
+ * has an HNSW index.
318
+ */
319
+ const MEMORY_EMBEDDING_DIMENSIONS = [1024, 1536];
320
+ const nonEmptyStringSchema = z.string().min(1);
321
+ /** Host data used to set memory access, subject, and source. */
322
+ const memoryRuntimeContextSchema = z.object({
323
+ conversationId: nonEmptyStringSchema.optional(),
324
+ locationId: nonEmptyStringSchema.optional(),
325
+ actor: actorSchema.optional(),
326
+ source: sourceSchema,
327
+ /** User linked to the active Actor. */
328
+ userId: nonEmptyStringSchema.optional()
329
+ }).strict();
330
+ // src/db/schema/memory.ts
331
+ /**
332
+ * The words of a memory for typed search. The `simple` config keeps each
333
+ * word as typed, so a half-typed word is a prefix of it. The `english`
334
+ * search vector stems words, so a half-typed word is not a prefix of its
335
+ * stem.
336
+ */
337
+ function memoryPrefixDocument(table) {
338
+ return sql`to_tsvector('simple', ${table.content})`;
339
+ }
340
+ const juniorMemoryMemories = pgTable("junior_memory_memories", {
341
+ id: text("id").primaryKey(),
342
+ scope: text("scope", { enum: MEMORY_SCOPES }).notNull(),
343
+ scopeKey: text("scope_key").notNull(),
344
+ kind: text("type", { enum: MEMORY_KINDS }).notNull(),
345
+ subjectType: text("subject_type", { enum: MEMORY_SUBJECT_TYPES }).notNull(),
346
+ subjectKey: text("subject_key"),
347
+ content: text("content").notNull(),
348
+ searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', "content")`),
349
+ sourcePlatform: text("source_platform", { enum: MEMORY_SOURCE_PLATFORMS }).notNull(),
350
+ sourceKey: text("source_key").notNull(),
351
+ /** Location where Junior learned the memory, when known. */
352
+ locationId: text("location_id"),
353
+ /** Conversation where Junior learned the memory, when known. */
354
+ conversationId: text("conversation_id"),
355
+ idempotencyKey: text("idempotency_key"),
356
+ observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull(),
357
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
358
+ expiresAtMs: bigint("expires_at_ms", { mode: "number" }),
359
+ supersededAtMs: bigint("superseded_at_ms", { mode: "number" }),
360
+ supersededById: text("superseded_by_id"),
361
+ archivedAtMs: bigint("archived_at_ms", { mode: "number" }),
362
+ archiveReason: text("archive_reason")
363
+ }, (table) => [
364
+ index("junior_memory_memories_visible_idx").on(table.scope, table.scopeKey, table.createdAtMs.desc(), table.id).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
365
+ index("junior_memory_memories_expiration_idx").on(table.expiresAtMs).where(sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`),
366
+ index("junior_memory_memories_search_idx").using("gin", table.scope, table.scopeKey, table.searchVector).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
367
+ index("junior_memory_memories_prefix_idx").using("gin", table.scope, table.scopeKey, memoryPrefixDocument(table)).where(sql`${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
368
+ uniqueIndex("junior_memory_memories_idempotency_idx").on(table.scope, table.scopeKey, table.idempotencyKey).where(sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NULL AND ${table.supersededAtMs} IS NULL AND ${table.supersededById} IS NULL`),
369
+ index("junior_memory_memories_archived_idempotency_idx").on(table.scope, table.scopeKey, table.idempotencyKey).where(sql`${table.idempotencyKey} IS NOT NULL AND ${table.archivedAtMs} IS NOT NULL AND ${table.archiveReason} <> 'expired'`),
370
+ check("junior_memory_memories_scope_check", sql`${table.scope} IN ('private', 'public')`),
371
+ check("junior_memory_memories_kind_check", sql`${table.kind} IN (
372
+ 'preference',
373
+ 'procedure',
374
+ 'knowledge'
375
+ )`),
376
+ check("junior_memory_memories_subject_type_check", sql`${table.subjectType} IN ('user', 'conversation', 'general')`),
377
+ check("junior_memory_memories_subject_key_check", sql`(${table.subjectType} = 'general' AND ${table.subjectKey} IS NULL) OR (${table.subjectType} IN ('user', 'conversation') AND ${table.subjectKey} IS NOT NULL AND length(${table.subjectKey}) > 0)`),
378
+ check("junior_memory_memories_source_platform_check", sql`${table.sourcePlatform} IN ('slack', 'local', 'web')`)
379
+ ]);
380
+ const juniorMemoryEmbeddings = pgTable("junior_memory_embeddings", {
381
+ memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
382
+ provider: text("provider").notNull(),
383
+ model: text("model").notNull(),
384
+ dimensions: integer("dimensions").notNull(),
385
+ metric: text("metric", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),
386
+ contentHash: text("content_hash").notNull(),
387
+ embedding: embeddingVector("embedding").notNull(),
388
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull()
389
+ }, (table) => [
390
+ primaryKey({ columns: [
391
+ table.memoryId,
392
+ table.provider,
393
+ table.model
394
+ ] }),
395
+ index("junior_memory_embeddings_model_idx").on(table.provider, table.model, table.dimensions, table.metric),
396
+ index("junior_memory_embeddings_embedding_1024_hnsw_idx").using("hnsw", sql`(${table.embedding}::vector(1024)) vector_cosine_ops`).with({
397
+ m: 16,
398
+ ef_construction: 64
399
+ }).where(sql`${table.dimensions} = 1024`),
400
+ check("junior_memory_embeddings_metric_check", sql`${table.metric} IN ('cosine')`),
401
+ check("junior_memory_embeddings_dimensions_check", sql`${table.dimensions} IN (${sql.raw(MEMORY_EMBEDDING_DIMENSIONS.join(", "))}) AND vector_dims(${table.embedding}) = ${table.dimensions}`)
402
+ ]);
403
+ /**
404
+ * Thin log of signals about stored memories, such as a capture that resolved
405
+ * to an existing memory. Callers count recent rows to weigh memories.
406
+ */
407
+ const juniorMemorySignals = pgTable("junior_memory_signals", {
408
+ memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
409
+ signal: text("signal", { enum: MEMORY_SIGNALS }).notNull(),
410
+ idempotencyKey: text("idempotency_key").notNull(),
411
+ /** Conversation where Junior saw the signal, when known. */
412
+ conversationId: text("conversation_id"),
413
+ observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull()
414
+ }, (table) => [
415
+ primaryKey({ columns: [
416
+ table.memoryId,
417
+ table.signal,
418
+ table.idempotencyKey
419
+ ] }),
420
+ index("junior_memory_signals_observed_idx").on(table.memoryId, table.signal, table.observedAtMs),
421
+ check("junior_memory_signals_signal_check", sql`${table.signal} IN ('duplicate', 'contradicted', 'superseded')`)
422
+ ]);
423
+ // src/db/schema/destinations.ts
424
+ const juniorDestinations = pgTable("junior_destinations", {
425
+ id: text("id").primaryKey(),
426
+ provider: text("provider").notNull(),
427
+ providerTenantId: text("provider_tenant_id").notNull().default(""),
428
+ providerDestinationId: text("provider_destination_id").notNull(),
429
+ kind: text("kind").$type().notNull(),
430
+ parentDestinationId: text("parent_destination_id"),
431
+ displayName: text("display_name"),
432
+ visibility: text("visibility").$type().notNull().default("unknown"),
433
+ metadata: jsonb("metadata_json"),
434
+ createdAt: timestamptz("created_at").notNull(),
435
+ updatedAt: timestamptz("updated_at").notNull()
436
+ }, (table) => [uniqueIndex("junior_destinations_provider_destination_uidx").on(table.provider, table.providerTenantId, table.providerDestinationId), index("junior_destinations_provider_kind_idx").on(table.provider, table.kind)]);
437
+ const juniorUsers = pgTable("junior_users", {
438
+ id: text("id").primaryKey(),
439
+ primaryEmail: text("primary_email").notNull(),
440
+ primaryEmailNormalized: text("primary_email_normalized").notNull(),
441
+ displayName: text("display_name"),
442
+ timezone: text("timezone"),
443
+ /** Text the user saved to change how Junior replies to them. */
444
+ customization: text("customization"),
445
+ /** Push notification hours. Null means the default schedule. */
446
+ notificationSchedule: jsonb("notification_schedule").$type(),
447
+ /** Junior-wide admin role. Only the `junior admin` CLI changes it. */
448
+ isAdmin: boolean("is_admin").notNull().default(false),
449
+ /** Auto-archive this user's conversations when their work is done. */
450
+ autoArchiveDefault: boolean("auto_archive_default").notNull().default(false),
451
+ /** Hours done work and the conversation stay quiet before auto-archive. */
452
+ autoArchiveGraceHours: integer("auto_archive_grace_hours").notNull().default(24),
453
+ /**
454
+ * Small per-user choices, such as an experiment opt-in, that can come
455
+ * and go without a migration. `api/user-settings.ts` owns the keys.
456
+ */
457
+ preferences: jsonb("preferences").$type().notNull().default({}),
458
+ createdAt: timestamptz("created_at").notNull(),
459
+ updatedAt: timestamptz("updated_at").notNull()
460
+ }, (table) => [uniqueIndex("junior_users_primary_email_normalized_uidx").on(table.primaryEmailNormalized)]);
461
+ // src/db/schema/identities.ts
462
+ /** Words of a Slack person's name and handle, for prefix search. */
463
+ function slackPersonSearchDocument(table) {
464
+ return sql`to_tsvector('simple', coalesce(${table.displayName}, '') || ' ' || coalesce(${table.handle}, ''))`;
465
+ }
466
+ /**
467
+ * Slack people. Literal values, so a prepared query with this predicate
468
+ * can use the partial index.
469
+ */
470
+ function slackPersonPredicate(table) {
471
+ return sql`${table.provider} = 'slack' AND ${table.kind} = 'user'`;
472
+ }
473
+ const juniorIdentities = pgTable("junior_identities", {
474
+ id: text("id").primaryKey(),
475
+ kind: text("kind").$type().notNull(),
476
+ provider: text("provider").notNull(),
477
+ providerTenantId: text("provider_tenant_id").notNull().default(""),
478
+ providerSubjectId: text("provider_subject_id").notNull(),
479
+ displayName: text("display_name"),
480
+ handle: text("handle"),
481
+ email: text("email"),
482
+ avatarUrl: text("avatar_url"),
483
+ metadata: jsonb("metadata_json"),
484
+ createdAt: timestamptz("created_at").notNull(),
485
+ updatedAt: timestamptz("updated_at").notNull(),
486
+ userId: text("user_id").references(() => juniorUsers.id),
487
+ emailNormalized: text("email_normalized"),
488
+ emailVerified: boolean("email_verified").notNull().default(false),
489
+ signedInAt: timestamptz("signed_in_at")
490
+ }, (table) => [
491
+ uniqueIndex("junior_identities_provider_subject_uidx").on(table.provider, table.providerTenantId, table.providerSubjectId),
492
+ index("junior_identities_user_idx").on(table.userId),
493
+ index("junior_identities_verified_email_idx").on(table.emailNormalized).where(sql`${table.emailVerified} = true AND ${table.emailNormalized} IS NOT NULL`),
494
+ index("junior_identities_kind_provider_idx").on(table.kind, table.provider),
495
+ index("junior_identities_slack_person_search_idx").using("gin", slackPersonSearchDocument(table)).where(slackPersonPredicate(table))
496
+ ]);
497
+ // src/db/schema/conversations.ts
498
+ const juniorConversations = pgTable("junior_conversations", {
499
+ conversationId: text("conversation_id").primaryKey(),
500
+ schemaVersion: integer("schema_version").notNull().default(1),
501
+ source: text("source").$type(),
502
+ /** Structured session Source locator; set-once on the conversation root. */
503
+ sessionSource: jsonb("source_json").$type(),
504
+ /** Complete Location associated with this Conversation. */
505
+ location: jsonb("location_json").$type(),
506
+ destinationId: text("destination_id").references(() => juniorDestinations.id),
507
+ destination: jsonb("destination_json").$type(),
508
+ actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
509
+ creatorIdentityId: text("creator_identity_id").references(() => juniorIdentities.id),
510
+ credentialSubjectIdentityId: text("credential_subject_identity_id").references(() => juniorIdentities.id),
511
+ actor: jsonb("actor_json").$type(),
512
+ channelName: text("channel_name"),
513
+ title: text("title"),
514
+ summary: text("summary"),
515
+ metadataThroughSeq: integer("metadata_through_seq"),
516
+ createdAt: timestamptz("created_at").notNull(),
517
+ lastActivityAt: timestamptz("last_activity_at").notNull(),
518
+ /**
519
+ * The newest Message that a reader would notice (`refreshLastMessageAt`).
520
+ * Null until the Conversation has one.
521
+ */
522
+ lastMessageAt: timestamptz("last_message_at"),
523
+ updatedAt: timestamptz("updated_at").notNull(),
524
+ executionUpdatedAt: timestamptz("execution_updated_at"),
525
+ executionStatus: text("execution_status").$type().notNull(),
526
+ runId: text("run_id"),
527
+ lastCheckpointAt: timestamptz("last_checkpoint_at"),
528
+ lastEnqueuedAt: timestamptz("last_enqueued_at"),
529
+ parentConversationId: text("parent_conversation_id").references(() => juniorConversations.conversationId),
530
+ kind: text("kind").$type(),
531
+ agentConfig: jsonb("agent_config_json").$type(),
532
+ archivedAt: timestamptz("archived_at"),
533
+ forkedFromConversationId: text("forked_from_conversation_id").references(() => juniorConversations.conversationId, { onDelete: "set null" }),
534
+ quickQuestionAt: timestamptz("quick_question_at"),
535
+ rootConversationId: text("root_conversation_id").references(() => juniorConversations.conversationId),
536
+ transcriptPurgedAt: timestamptz("transcript_purged_at"),
537
+ /**
538
+ * Set while the Conversation is stopped. Its Watch Events are then saved
539
+ * as Messages that start no Turn. A person's later input, or new work
540
+ * from its parent, clears it.
541
+ */
542
+ stoppedAt: timestamptz("stopped_at"),
543
+ /**
544
+ * Set while a root's Event Turn replies stay out of its Location. Junior
545
+ * still stores them. A person's next mention in the Location clears it.
546
+ */
547
+ deliveryPausedAt: timestamptz("delivery_paused_at"),
548
+ durationMs: integer("duration_ms").notNull().default(0),
549
+ usage: jsonb("usage_json").$type(),
550
+ executionDurationMs: integer("execution_duration_ms").notNull().default(0),
551
+ executionUsage: jsonb("execution_usage_json").$type(),
552
+ metricRunId: text("metric_run_id"),
553
+ detailVersion: integer("detail_version").notNull().default(0)
554
+ }, (table) => [
555
+ check("junior_conversations_kind_check", sql`${table.kind} in ('root', 'automation', 'lead', 'thread', 'task')`),
556
+ check("junior_conversations_kind_parent_check", sql`${table.kind} is null or ((${table.kind} in ('root', 'automation', 'lead')) = (${table.parentConversationId} is null))`),
557
+ index("junior_conversations_last_activity_idx").on(table.lastActivityAt.desc(), table.conversationId),
558
+ index("junior_conversations_active_idx").using("btree", sql`coalesce(${table.executionUpdatedAt}, ${table.updatedAt})`, table.conversationId).where(sql`${table.executionStatus} <> 'idle'`),
559
+ index("junior_conversations_destination_activity_idx").on(table.destinationId, table.lastActivityAt.desc()),
560
+ index("junior_conversations_actor_activity_idx").on(table.actorIdentityId, table.lastActivityAt.desc()),
561
+ index("junior_conversations_parent_idx").on(table.parentConversationId),
562
+ index("junior_conversations_forked_from_idx").on(table.forkedFromConversationId),
563
+ index("junior_conversations_root_idx").on(table.rootConversationId),
564
+ uniqueIndex("junior_conversations_lead_actor_idx").on(table.actorIdentityId).where(sql`${table.kind} = 'lead'`),
565
+ index("junior_conversations_search_idx").using("gin", sql`to_tsvector('english', coalesce(${table.title}, '') || ' ' || coalesce(${table.summary}, ''))`)
566
+ ]);
567
+ // src/db/schema/attachments.ts
568
+ /**
569
+ * What a Message carries: a stored file (`file`) or a web link that its text
570
+ * names (`url`). Rows are owned by one Conversation, and a repeat of the same
571
+ * thing in that Conversation reuses its row.
572
+ */
573
+ const juniorAttachments = pgTable("junior_attachments", {
574
+ id: text("id").primaryKey(),
575
+ /** `file` or `url`. Only `file` rows have storage and file fields. */
576
+ kind: text("kind").notNull().default("file"),
577
+ conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
578
+ /** Service that stores the file bytes. */
579
+ storageProvider: text("storage_provider"),
580
+ /**
581
+ * Object key of the stored bytes. Null for a file that Junior records
582
+ * without storing, such as a large Slack file.
583
+ */
584
+ storageKey: text("storage_key"),
585
+ /** Provider that supplied the file. */
586
+ provider: text("provider"),
587
+ /** File id assigned by the source provider. */
588
+ providerId: text("provider_id"),
589
+ /**
590
+ * File name of a file. The column keeps its old name until no worker
591
+ * that reads `filename` runs.
592
+ */
593
+ title: text("filename"),
594
+ contentType: text("content_type"),
595
+ bytes: integer("bytes"),
596
+ /** Web link of a `url` row, as its message text wrote it. */
597
+ url: text("url"),
598
+ /** Digest of the stored bytes. Null when `storage_key` is null. */
599
+ sha256: text("sha256"),
600
+ visionSummary: text("vision_summary"),
601
+ createdAt: timestamptz("created_at").notNull(),
602
+ /** Set when conversation purge marks the attachment unavailable. */
603
+ deleteRequestedAt: timestamptz("delete_requested_at")
604
+ }, (table) => [
605
+ index("junior_attachments_conversation_idx").on(table.conversationId),
606
+ index("junior_attachments_provider_idx").on(table.conversationId, table.provider, table.providerId),
607
+ index("junior_attachments_gc_idx").on(table.storageProvider, table.deleteRequestedAt, table.createdAt),
608
+ uniqueIndex("junior_attachments_conversation_url_idx").on(table.conversationId, table.url).where(sql`${table.url} IS NOT NULL`)
609
+ ]);
610
+ /**
611
+ * Where each stored message event uses an Attachment. `seq` is the seq of the
612
+ * first save of its message, as in the transcript. `position` is the 1-based
613
+ * order of a link in the message text, and null for an Attachment that is not
614
+ * in the text. No foreign keys, so creating the table locks no existing
615
+ * table.
616
+ */
617
+ const juniorMessageAttachments = pgTable("junior_message_attachments", {
618
+ conversationId: text("conversation_id").notNull(),
619
+ seq: integer("seq").notNull(),
620
+ attachmentId: text("attachment_id").notNull(),
621
+ position: integer("position")
622
+ }, (table) => [primaryKey({
623
+ name: "junior_message_attachments_pk",
624
+ columns: [
625
+ table.conversationId,
626
+ table.seq,
627
+ table.attachmentId
628
+ ]
629
+ })]);
630
+ /**
631
+ * Browser uploads that wait for a web Message.
632
+ *
633
+ * A row binds one object key to the viewer, Conversation, and Message
634
+ * idempotency key that asked for it. A Message turns the upload into a
635
+ * `junior_attachments` row with the same id. Cleanup deletes the object of an
636
+ * upload that no Message used.
637
+ */
638
+ const juniorAttachmentUploads = pgTable("junior_attachment_uploads", {
639
+ id: text("id").primaryKey(),
640
+ /** No foreign key: a new Conversation has no row until its first send. */
641
+ conversationId: text("conversation_id").notNull(),
642
+ userId: text("user_id").notNull(),
643
+ idempotencyKey: text("idempotency_key").notNull(),
644
+ storageProvider: text("storage_provider").notNull(),
645
+ storageKey: text("storage_key").notNull(),
646
+ filename: text("filename").notNull(),
647
+ contentType: text("content_type").notNull(),
648
+ /** Size that the browser declared and the upload target allows. */
649
+ bytes: integer("bytes").notNull(),
650
+ createdAt: timestamptz("created_at").notNull()
651
+ }, (table) => [index("junior_attachment_uploads_gc_idx").on(table.storageProvider, table.createdAt)]);
652
+ // src/db/schema/code.ts
653
+ /**
654
+ * Words of a repository name, for prefix search. `owner/repo` is one token
655
+ * to the text parser, so the slash becomes a space.
656
+ */
657
+ function codeRepositorySearchDocument(table) {
658
+ return sql`to_tsvector('simple', translate(${table.name}, '/', ' '))`;
659
+ }
660
+ /** The number and the title words of a code change, for prefix search. */
661
+ function codeChangeSearchDocument(table) {
662
+ return sql`to_tsvector('simple', ${table.number}::text || ' ' || coalesce(${table.title}, ''))`;
663
+ }
664
+ /** Repository known to Junior through an installed code plugin. */
665
+ const juniorCodeRepositories = pgTable("junior_code_repositories", {
666
+ id: uuid("id").primaryKey(),
667
+ name: text("name").notNull(),
668
+ provider: text("provider").notNull(),
669
+ providerId: text("provider_id").notNull(),
670
+ updatedAt: timestamptz("updated_at").notNull()
671
+ }, (table) => [uniqueIndex("junior_code_repositories_provider_id_idx").on(table.provider, table.providerId), index("junior_code_repositories_search_idx").using("gin", codeRepositorySearchDocument(table))]);
672
+ /** Latest known state for one code change created by Junior. */
673
+ const juniorCodeChanges = pgTable("junior_code_changes", {
674
+ id: uuid("id").primaryKey(),
675
+ additions: integer("additions"),
676
+ changedFiles: integer("changed_files"),
677
+ closedAt: timestamptz("closed_at"),
678
+ conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
679
+ deletions: integer("deletions"),
680
+ draft: boolean("draft").notNull().default(false),
681
+ /** Latest push, review, or comment by a person, from the code plugin. */
682
+ lastActivityAt: timestamptz("last_activity_at"),
683
+ mergedAt: timestamptz("merged_at"),
684
+ number: integer("number").notNull(),
685
+ openedAt: timestamptz("opened_at").notNull(),
686
+ provider: text("provider").notNull(),
687
+ providerId: text("provider_id").notNull(),
688
+ repositoryId: uuid("repository_id").notNull().references(() => juniorCodeRepositories.id, { onDelete: "cascade" }),
689
+ state: text("state").$type().notNull(),
690
+ title: text("title"),
691
+ updatedAt: timestamptz("updated_at").notNull()
692
+ }, (table) => [
693
+ uniqueIndex("junior_code_changes_provider_id_idx").on(table.provider, table.providerId),
694
+ index("junior_code_changes_opened_at_idx").on(table.openedAt),
695
+ index("junior_code_changes_merged_at_idx").on(table.mergedAt),
696
+ index("junior_code_changes_closed_at_idx").on(table.closedAt),
697
+ index("junior_code_changes_repository_state_idx").on(table.repositoryId, table.state, table.updatedAt.desc()),
698
+ index("junior_code_changes_search_idx").using("gin", codeChangeSearchDocument(table)),
699
+ index("junior_code_changes_open_idx").on(table.id).where(sql`${table.state} = 'open'`)
700
+ ]);
701
+ // src/db/schema/conversation-annotations.ts
702
+ const juniorConversationAnnotations = pgTable("junior_conversation_annotations", {
703
+ conversationId: text("conversation_id").notNull(),
704
+ plugin: text("plugin").notNull(),
705
+ kind: text("kind").notNull(),
706
+ key: text("key").notNull(),
707
+ annotation: jsonb("annotation_json").$type().notNull(),
708
+ createdAt: timestamptz("created_at").notNull(),
709
+ updatedAt: timestamptz("updated_at").notNull()
710
+ }, (table) => [primaryKey({
711
+ name: "junior_conversation_annotations_pk",
712
+ columns: [
713
+ table.conversationId,
714
+ table.plugin,
715
+ table.kind,
716
+ table.key
717
+ ]
718
+ }), foreignKey({
719
+ name: "junior_conversation_annotations_conversation_id_fk",
720
+ columns: [table.conversationId],
721
+ foreignColumns: [juniorConversations.conversationId]
722
+ }).onDelete("cascade")]);
723
+ // src/db/schema/api-tokens.ts
724
+ const juniorApiTokens = pgTable("junior_api_tokens", {
725
+ id: text("id").primaryKey(),
726
+ ownerEmailNormalized: text("owner_email_normalized").notNull(),
727
+ name: text("name").notNull(),
728
+ tokenHash: text("token_hash").notNull(),
729
+ tokenSuffix: text("token_suffix").notNull(),
730
+ createdAt: timestamptz("created_at").notNull(),
731
+ expiresAt: timestamptz("expires_at").notNull(),
732
+ lastUsedAt: timestamptz("last_used_at"),
733
+ revokedAt: timestamptz("revoked_at")
734
+ }, (table) => [uniqueIndex("junior_api_tokens_token_hash_uidx").on(table.tokenHash), index("junior_api_tokens_owner_email_idx").on(table.ownerEmailNormalized)]);
735
+ // src/db/schema/conversation-events.ts
736
+ /**
737
+ * Match a user_message payload that a person sent as an instruction from a
738
+ * chat surface. `junior_conversation_events_user_message_time_idx` has this
739
+ * predicate, so a query with it can use the index and skip other events.
740
+ */
741
+ function isUserInstruction(payload) {
742
+ return sql`(${payload}->'provenance'->>'authority') = 'instruction' and (${payload}->'provenance'->'actor'->>'platform') in ('slack', 'local', 'web')`;
743
+ }
744
+ /**
745
+ * Append-only canonical conversation history. `history_version` partitions
746
+ * model-history replacements, while `(conversation_id, seq)` is the stable
747
+ * event identity and lease-fencing tripwire.
748
+ *
749
+ * `actor_identity_id` is the first-class author identity for human-authored
750
+ * events. Message payloads may still carry display author fields in `meta`.
751
+ */
752
+ const juniorConversationEvents = pgTable("junior_conversation_events", {
753
+ conversationId: text("conversation_id").notNull(),
754
+ seq: integer("seq").notNull(),
755
+ historyVersion: integer("history_version").notNull(),
756
+ schemaVersion: integer("schema_version").default(1).notNull(),
757
+ idempotencyKey: text("idempotency_key"),
758
+ type: text("type").notNull(),
759
+ payload: jsonb("payload").$type().notNull(),
760
+ actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
761
+ createdAt: timestamptz("created_at").notNull()
762
+ }, (table) => [
763
+ primaryKey({
764
+ name: "junior_conversation_events_conversation_id_seq_pk",
765
+ columns: [table.conversationId, table.seq]
766
+ }),
767
+ foreignKey({
768
+ name: "junior_conversation_events_conversation_id_junior_conversations_conversation_id_fk",
769
+ columns: [table.conversationId],
770
+ foreignColumns: [juniorConversations.conversationId]
771
+ }),
772
+ index("junior_conversation_events_history_version_idx").on(table.conversationId, table.historyVersion, table.seq),
773
+ index("junior_conversation_events_type_idx").on(table.conversationId, table.type, table.seq),
774
+ index("junior_conversation_events_plugin_report_idx").on(sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.createdAt).where(sql`${table.type} = 'structured_event'`),
775
+ index("junior_conversation_events_guardian_review_time_idx").on(table.createdAt).where(sql`${table.type} = 'guardian_action_reviewed'`),
776
+ index("junior_conversation_events_authorization_request_idx").on(table.conversationId, table.createdAt).where(sql`${table.type} = 'authorization_requested'`),
777
+ index("junior_conversation_events_plugin_conversation_idx").on(table.conversationId, sql`(${table.payload}->>'namespace')`, sql`(${table.payload}->>'name')`, table.seq).where(sql`${table.type} = 'structured_event'`),
778
+ index("junior_conversation_events_actor_identity_idx").on(table.actorIdentityId, table.conversationId, table.seq),
779
+ index("junior_conversation_events_author_idx").on(table.conversationId, table.actorIdentityId, table.seq).where(sql`${table.actorIdentityId} is not null`),
780
+ index("junior_conversation_events_message_role_idx").on(table.conversationId, sql`(${table.payload}->>'role')`, table.createdAt, table.seq).where(sql`${table.type} = 'message'`),
781
+ index("junior_conversation_events_user_message_time_idx").on(table.conversationId, table.createdAt, table.seq).where(sql`${table.type} = 'user_message' and ${isUserInstruction(table.payload)}`),
782
+ index("junior_conversation_events_message_search_idx").using("gin", sql`to_tsvector('english', ${table.payload}->>'text')`).where(sql`${table.type} = 'message'`),
783
+ uniqueIndex("junior_conversation_events_idempotency_idx").on(table.conversationId, table.idempotencyKey)
784
+ ]);
785
+ // src/db/schema/conversation-metrics.ts
786
+ const CONVERSATION_METRICS = [
787
+ "duration_ms",
788
+ "total_tokens",
789
+ "input_tokens",
790
+ "output_tokens",
791
+ "cached_input_tokens",
792
+ "cache_creation_tokens",
793
+ "reasoning_tokens",
794
+ "cost_micro_usd"
795
+ ];
796
+ /**
797
+ * One metric value for one Conversation Run. A Run is one Turn, so People
798
+ * spend reads the Identity of the Turn Actor from these rows.
799
+ */
800
+ const juniorConversationMetrics = pgTable("junior_conversation_metrics", {
801
+ conversationId: text("conversation_id").notNull(),
802
+ runId: text("run_id").notNull(),
803
+ metric: text("metric").$type().notNull(),
804
+ actorIdentityId: text("actor_identity_id").references(() => juniorIdentities.id),
805
+ value: doublePrecision("value").notNull(),
806
+ occurredAt: timestamptz("occurred_at").notNull(),
807
+ updatedAt: timestamptz("updated_at").notNull()
808
+ }, (table) => [
809
+ primaryKey({
810
+ name: "junior_conversation_metrics_conversation_id_run_id_metric_pk",
811
+ columns: [
812
+ table.conversationId,
813
+ table.runId,
814
+ table.metric
815
+ ]
816
+ }),
817
+ foreignKey({
818
+ name: "junior_conversation_metrics_conversation_id_junior_conversations_conversation_id_fk",
819
+ columns: [table.conversationId],
820
+ foreignColumns: [juniorConversations.conversationId]
821
+ }),
822
+ index("junior_conversation_metrics_actor_identity_occurred_at_idx").on(table.actorIdentityId, table.occurredAt),
823
+ index("junior_conversation_metrics_occurred_at_metric_idx").on(table.occurredAt, table.metric),
824
+ index("junior_conversation_metrics_turn_metric_occurred_at_idx").on(table.metric, table.occurredAt, table.actorIdentityId, table.conversationId, table.value).where(sql`${table.metric} IN ('duration_ms', 'total_tokens', 'cost_micro_usd')`)
825
+ ]);
826
+ // src/db/schema/conversation-embeddings.ts
827
+ /**
828
+ * One embedding per Conversation, for semantic search. Its text is the
829
+ * Conversation metadata. A derived index: the next metadata update replaces
830
+ * the row.
831
+ */
832
+ const juniorConversationEmbeddings = pgTable("junior_conversation_embeddings", {
833
+ conversationId: text("conversation_id").primaryKey(),
834
+ legacyBriefVersion: integer("brief_version"),
835
+ /** The `metadata_through_seq` of the embedded Conversation metadata. */
836
+ throughSeq: integer("through_seq"),
837
+ provider: text("provider").notNull(),
838
+ model: text("model").notNull(),
839
+ dimensions: integer("dimensions").notNull(),
840
+ embedding: embeddingVector("embedding").notNull(),
841
+ createdAt: timestamptz("created_at").defaultNow().notNull()
842
+ }, (table) => [foreignKey({
843
+ name: "junior_conversation_embeddings_conversation_fk",
844
+ columns: [table.conversationId],
845
+ foreignColumns: [juniorConversations.conversationId]
846
+ }).onDelete("cascade"), check("junior_conversation_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)]);
847
+ // src/db/schema/conversation-event-embeddings.ts
848
+ /**
849
+ * One embedding per searchable Conversation event, for semantic search of the
850
+ * history of one Conversation. A derived index: a purge that deletes the
851
+ * event deletes its row, and a new embedding model replaces the row.
852
+ */
853
+ const juniorConversationEventEmbeddings = pgTable("junior_conversation_event_embeddings", {
854
+ conversationId: text("conversation_id").notNull(),
855
+ seq: integer("seq").notNull(),
856
+ provider: text("provider").notNull(),
857
+ model: text("model").notNull(),
858
+ dimensions: integer("dimensions").notNull(),
859
+ embedding: embeddingHalfvec("embedding").notNull(),
860
+ createdAt: timestamptz("created_at").defaultNow().notNull()
861
+ }, (table) => [
862
+ primaryKey({
863
+ name: "junior_conversation_event_embeddings_pk",
864
+ columns: [table.conversationId, table.seq]
865
+ }),
866
+ foreignKey({
867
+ name: "junior_conversation_event_embeddings_event_fk",
868
+ columns: [table.conversationId, table.seq],
869
+ foreignColumns: [juniorConversationEvents.conversationId, juniorConversationEvents.seq]
870
+ }).onDelete("cascade"),
871
+ check("junior_conversation_event_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)
872
+ ]);
873
+ // src/db/schema/conversation-event-lexemes.ts
874
+ /**
875
+ * Stored full-text lexemes of one searchable Conversation event, for keyword
876
+ * search of the history of one Conversation. A derived index: a purge that
877
+ * deletes the event deletes its row. Events are immutable, so a row never
878
+ * changes.
879
+ */
880
+ const juniorConversationEventLexemes = pgTable("junior_conversation_event_lexemes", {
881
+ conversationId: text("conversation_id").notNull(),
882
+ seq: integer("seq").notNull(),
883
+ lexemes: tsvector("lexemes").notNull(),
884
+ createdAt: timestamptz("created_at").defaultNow().notNull()
885
+ }, (table) => [
886
+ primaryKey({
887
+ name: "junior_conversation_event_lexemes_pk",
888
+ columns: [table.conversationId, table.seq]
889
+ }),
890
+ foreignKey({
891
+ name: "junior_conversation_event_lexemes_event_fk",
892
+ columns: [table.conversationId, table.seq],
893
+ foreignColumns: [juniorConversationEvents.conversationId, juniorConversationEvents.seq]
894
+ }).onDelete("cascade"),
895
+ index("junior_conversation_event_lexemes_lexemes_idx").using("gin", table.lexemes)
896
+ ]);
897
+ // src/db/schema/conversation-briefs.ts
898
+ /**
899
+ * Legacy Brief versions. Conversation metadata replaced Briefs; only purge
900
+ * still deletes rows here.
901
+ * TODO(dcramer): Drop this table after the metadata backfill ships.
902
+ */
903
+ const juniorConversationBriefs = pgTable("junior_conversation_briefs", {
904
+ conversationId: text("conversation_id").notNull(),
905
+ version: integer("version").notNull(),
906
+ turnId: text("turn_id").notNull(),
907
+ throughSeq: integer("through_seq").notNull(),
908
+ content: jsonb("content").notNull(),
909
+ outcomeStatus: text("outcome_status"),
910
+ searchText: text("search_text").notNull(),
911
+ modelId: text("model_id").notNull(),
912
+ costMicroUsd: bigint("cost_micro_usd", { mode: "number" }),
913
+ legacyCostUsd: doublePrecision("cost_usd"),
914
+ createdAt: timestamptz("created_at").defaultNow().notNull()
915
+ }, (table) => [
916
+ primaryKey({
917
+ name: "junior_conversation_briefs_conversation_id_version_pk",
918
+ columns: [table.conversationId, table.version]
919
+ }),
920
+ foreignKey({
921
+ name: "junior_conversation_briefs_conversation_id_junior_conversations_conversation_id_fk",
922
+ columns: [table.conversationId],
923
+ foreignColumns: [juniorConversations.conversationId]
924
+ }).onDelete("cascade"),
925
+ uniqueIndex("junior_conversation_briefs_conversation_turn_idx").on(table.conversationId, table.turnId),
926
+ index("junior_conversation_briefs_conversation_version_idx").on(table.conversationId, table.version.desc()),
927
+ index("junior_conversation_briefs_created_at_idx").on(table.createdAt, table.conversationId),
928
+ index("junior_conversation_briefs_search_idx").using("gin", sql`to_tsvector('english', ${table.searchText})`)
929
+ ]);
930
+ // src/db/schema/conversation-bindings.ts
931
+ /** Provider conversation coordinates bound to Junior's opaque durable conversation id. */
932
+ const juniorConversationBindings = pgTable("junior_conversation_bindings", {
933
+ conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId),
934
+ provider: text("provider").notNull(),
935
+ providerTenantId: text("provider_tenant_id").notNull().default(""),
936
+ providerDestinationId: text("provider_destination_id").notNull(),
937
+ providerConversationId: text("provider_conversation_id").notNull(),
938
+ createdAt: timestamptz("created_at").notNull()
939
+ }, (table) => [primaryKey({
940
+ name: "junior_conversation_bindings_provider_conversation_pk",
941
+ columns: [
942
+ table.provider,
943
+ table.providerTenantId,
944
+ table.providerDestinationId,
945
+ table.providerConversationId
946
+ ]
947
+ }), index("junior_conversation_bindings_conversation_idx").on(table.conversationId)]);
948
+ // src/db/schema/conversation-participants.ts
949
+ /**
950
+ * One Participant: a linked user on one root conversation. Rows come from
951
+ * Turn Actors: the root Actor and the authors of Turn input messages, and
952
+ * the root Actor again when their Identity gets its User later. Thread
953
+ * context authors do not get a row. Access and feeds read only these rows.
954
+ * An unsubscribed row keeps access but leaves the active feed.
955
+ */
956
+ const juniorConversationParticipants = pgTable("junior_conversation_participants", {
957
+ userId: text("user_id").notNull().references(() => juniorUsers.id),
958
+ rootConversationId: text("root_conversation_id").notNull().references(() => juniorConversations.conversationId),
959
+ lastMessageAt: timestamptz("last_message_at").notNull(),
960
+ pinnedAt: timestamptz("pinned_at"),
961
+ /**
962
+ * The viewer's place for this pin in the Pinned section, from a drag
963
+ * reorder. Null until the first reorder, and cleared on unpin and
964
+ * re-pin. Null pins sort first, by activity.
965
+ */
966
+ pinPosition: integer("pin_position"),
967
+ /**
968
+ * Per-conversation auto-archive choice for this user. Null uses the
969
+ * user's `autoArchiveDefault`.
970
+ */
971
+ autoArchive: boolean("auto_archive"),
972
+ /**
973
+ * Set when this user left the conversation. It stays out of their
974
+ * active feed until they mention Junior in it again, subscribe, or pin
975
+ * it. The row keeps its access, so it is not deleted.
976
+ */
977
+ unsubscribedAt: timestamptz("unsubscribed_at")
978
+ }, (table) => [
979
+ primaryKey({
980
+ name: "junior_conversation_participants_user_root_pk",
981
+ columns: [table.userId, table.rootConversationId]
982
+ }),
983
+ index("junior_conversation_participants_user_activity_idx").on(table.userId, table.lastMessageAt.desc()),
984
+ index("junior_conversation_participants_root_idx").on(table.rootConversationId),
985
+ index("junior_conversation_participants_auto_archive_idx").on(table.userId).where(sql`${table.autoArchive}`),
986
+ index("junior_conversation_participants_unsubscribed_idx").on(table.userId, table.rootConversationId).where(sql`${table.unsubscribedAt} is not null`)
987
+ ]);
988
+ // src/db/schema/conversation-read-positions.ts
989
+ /**
990
+ * How far one signed-in user has read one Conversation transcript.
991
+ *
992
+ * `last_read_seq` is the event sequence of the last transcript row the user
993
+ * saw. It only moves forward, so clients on several devices can write in any
994
+ * order.
995
+ */
996
+ const juniorConversationReadPositions = pgTable("junior_conversation_read_positions", {
997
+ userId: text("user_id").notNull().references(() => juniorUsers.id),
998
+ conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId),
999
+ lastReadSeq: integer("last_read_seq").notNull(),
1000
+ updatedAt: timestamptz("updated_at").notNull()
1001
+ }, (table) => [primaryKey({
1002
+ name: "junior_conversation_read_positions_user_conversation_pk",
1003
+ columns: [table.userId, table.conversationId]
1004
+ })]);
1005
+ // src/db/schema/agent-bindings.ts
1006
+ const juniorAgentBindings = pgTable("junior_agent_bindings", {
1007
+ parentConversationId: text("parent_conversation_id").notNull().references(() => juniorConversations.conversationId),
1008
+ name: text("name").notNull(),
1009
+ childConversationId: text("child_conversation_id").notNull().references(() => juniorConversations.conversationId)
1010
+ }, (table) => [primaryKey({ columns: [table.parentConversationId, table.name] }), uniqueIndex("junior_agent_bindings_child_idx").on(table.childConversationId)]);
1011
+ // src/db/schema/location-configurations.ts
1012
+ /** Durable user configuration entries scoped to provider Locations. */
1013
+ const juniorLocationConfigurations = pgTable("junior_location_configurations", {
1014
+ locationId: text("location_id").notNull().references(() => juniorDestinations.id, { onDelete: "cascade" }),
1015
+ key: text("key").notNull(),
1016
+ value: text("value").notNull(),
1017
+ updatedAt: timestamptz("updated_at").notNull(),
1018
+ updatedBy: text("updated_by"),
1019
+ source: text("source"),
1020
+ expiresAt: text("expires_at")
1021
+ }, (table) => [primaryKey({ columns: [table.locationId, table.key] })]);
1022
+ // src/db/schema/automation-versions.ts
1023
+ /** One saved Automation definition. Lifecycle and scheduler state are not versioned. */
1024
+ const juniorAutomationVersions = pgTable("junior_automation_versions", {
1025
+ automationId: text("automation_id").notNull(),
1026
+ /** Starts at 1 and increases by 1 for each saved definition change. */
1027
+ version: integer("version").notNull(),
1028
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
1029
+ /** Slack principal that saved this definition. Null when unknown. */
1030
+ editedBy: jsonb("edited_by"),
1031
+ definition: jsonb("definition").notNull()
1032
+ }, (table) => [primaryKey({
1033
+ name: "junior_automation_versions_pk",
1034
+ columns: [table.automationId, table.version]
1035
+ }), foreignKey({
1036
+ name: "junior_automation_versions_automation_id_fk",
1037
+ columns: [table.automationId],
1038
+ foreignColumns: [juniorAutomations.id]
1039
+ }).onDelete("cascade")]);
1040
+ // src/db/schema/automation-runs.ts
1041
+ /**
1042
+ * One dispatch of an Automation, from claim or dispatch to its outcome. A
1043
+ * Scheduled automation run id is `<automation id>:<scheduled time>`. An event
1044
+ * automation run id is its dispatch id. Automation code sets
1045
+ * `conversation_id` when it dispatches the run. A run that was skipped, or
1046
+ * that failed before dispatch, has no Conversation.
1047
+ *
1048
+ * `automation_version` is the Automation version that the run dispatched. It
1049
+ * shows which instruction ran and who saved it after the definition changes.
1050
+ * It is null before dispatch, and when no saved version matched.
1051
+ */
1052
+ const juniorAutomationRuns = pgTable("junior_automation_runs", {
1053
+ id: text("id").primaryKey(),
1054
+ automationId: text("automation_id").notNull().references(() => juniorAutomations.id, { onDelete: "cascade" }),
1055
+ conversationId: text("conversation_id").unique().references(() => juniorConversations.conversationId),
1056
+ status: text("status").$type().notNull(),
1057
+ automationVersion: integer("automation_version"),
1058
+ scheduledForMs: bigint("scheduled_for_ms", { mode: "number" }),
1059
+ attempt: integer("attempt"),
1060
+ claimedAtMs: bigint("claimed_at_ms", { mode: "number" }),
1061
+ dispatchId: text("dispatch_id"),
1062
+ startedAtMs: bigint("started_at_ms", { mode: "number" }),
1063
+ completedAtMs: bigint("completed_at_ms", { mode: "number" }),
1064
+ errorMessage: text("error_message"),
1065
+ resultMessageTs: text("result_message_ts"),
1066
+ costMicroUsd: bigint("cost_micro_usd", { mode: "number" })
1067
+ }, (table) => [
1068
+ foreignKey({
1069
+ name: "junior_automation_runs_automation_version_fk",
1070
+ columns: [table.automationId, table.automationVersion],
1071
+ foreignColumns: [juniorAutomationVersions.automationId, juniorAutomationVersions.version]
1072
+ }),
1073
+ check("junior_automation_runs_status_check", sql`${table.status} in ('pending', 'running', 'completed', 'failed', 'blocked', 'skipped')`),
1074
+ index("junior_automation_runs_automation_idx").on(table.automationId, table.completedAtMs),
1075
+ index("junior_automation_runs_completed_idx").on(table.completedAtMs),
1076
+ index("junior_automation_runs_incomplete_idx").on(table.automationId, table.scheduledForMs).where(sql`${table.status} in ('pending', 'running')`)
1077
+ ]);
1078
+ // src/db/schema/automations.ts
1079
+ /**
1080
+ * The words of an Automation for search: its title, ranked above its task
1081
+ * and, for an event Automation, its trigger. The `simple` config keeps each
1082
+ * word as typed, so a prefix of it matches.
1083
+ */
1084
+ function automationSearchDocument(table) {
1085
+ return sql`(setweight(to_tsvector('simple', coalesce(${table.title}, '')), 'A') || setweight(to_tsvector('simple', coalesce(${table.instruction}, '') || ' ' || coalesce(${table.skill}, '') || ' ' || case when ${table.kind} = 'event' then coalesce(${table.identifier}, '') || ' ' || coalesce(${table.record}->'trigger'->>'label', '') || ' ' || coalesce(${table.namespace}, '') else '' end), 'B'))`;
1086
+ }
1087
+ /** The lowercase title of an Automation, for typo-tolerant search. */
1088
+ function automationFuzzyTitle(table) {
1089
+ return sql`lower(coalesce(${table.title}, ''))`;
1090
+ }
1091
+ /**
1092
+ * One row per Automation of either kind. `record` holds the fields that have
1093
+ * no column. Each write also copies the nested fields that queries filter or
1094
+ * search on into columns: `team_id`, `channel_id`, `creator_slack_user_id`,
1095
+ * the task `instruction` or `skill`, and the event trigger `namespace` and
1096
+ * `identifier`. Exactly one of `instruction` and `skill` is set, by the task
1097
+ * kind. A skill's context is only in `record`. An event trigger with no
1098
+ * identifier runs for every resource of its namespace, so its `identifier` is
1099
+ * null. The match index finds those rows with `identifier is null`.
1100
+ */
1101
+ const juniorAutomations = pgTable("junior_automations", {
1102
+ id: text("id").primaryKey(),
1103
+ kind: text("kind").$type().notNull(),
1104
+ teamId: text("team_id").notNull(),
1105
+ channelId: text("channel_id").notNull(),
1106
+ creatorSlackUserId: text("creator_slack_user_id").notNull(),
1107
+ /** Junior identity that created the Automation. It decides ownership. */
1108
+ creatorIdentityId: text("creator_identity_id").notNull().references(() => juniorIdentities.id),
1109
+ status: text("status").$type().notNull(),
1110
+ /** Why a run blocked this Automation, until its creator resumes it. */
1111
+ statusReason: text("status_reason"),
1112
+ title: text("title"),
1113
+ /** The instruction of an instruction task. Null for a skill task. */
1114
+ instruction: text("instruction"),
1115
+ /** The skill of a skill task. Null for an instruction task. */
1116
+ skill: text("skill"),
1117
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
1118
+ nextRunAtMs: bigint("next_run_at_ms", { mode: "number" }),
1119
+ runNowAtMs: bigint("run_now_at_ms", { mode: "number" }),
1120
+ /**
1121
+ * The latest run with an outcome. The list reads its end time and status
1122
+ * to order by activity and to find failed last runs.
1123
+ * `refreshAutomationLastRun` sets it after each run write. A purged run
1124
+ * clears it.
1125
+ */
1126
+ lastRunId: text("last_run_id").references(() => juniorAutomationRuns.id, { onDelete: "set null" }),
1127
+ /**
1128
+ * When core last saw this Automation recover after a person dismissed
1129
+ * its alert. A dismissed alert hides the Automation's alerts until then.
1130
+ */
1131
+ alertRecoveredAtMs: bigint("alert_recovered_at_ms", { mode: "number" }),
1132
+ namespace: text("namespace"),
1133
+ identifier: text("identifier"),
1134
+ record: jsonb("record").$type().notNull()
1135
+ }, (table) => [
1136
+ check("junior_automations_kind_check", sql`${table.kind} in ('scheduled', 'event')`),
1137
+ check("junior_automations_status_check", sql`${table.status} in ('active', 'blocked', 'paused', 'completed', 'deleted')`),
1138
+ check("junior_automations_task_check", sql`(${table.instruction} is null) <> (${table.skill} is null)`),
1139
+ check("junior_automations_record_check", sql`jsonb_typeof(${table.record}) = 'object'`),
1140
+ check("junior_automations_trigger_check", sql`(${table.kind} = 'scheduled' and ${table.namespace} is null and ${table.identifier} is null) or (${table.kind} = 'event' and ${table.namespace} is not null and ${table.nextRunAtMs} is null and ${table.runNowAtMs} is null and ${table.status} <> 'completed')`),
1141
+ index("junior_automations_team_idx").on(table.teamId, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`),
1142
+ index("junior_automations_creator_identity_idx").on(table.creatorIdentityId, table.createdAtMs, table.id),
1143
+ index("junior_automations_creator_slack_idx").on(table.teamId, table.creatorSlackUserId).where(sql`${table.status} <> 'deleted'`),
1144
+ index("junior_automations_last_run_idx").on(table.lastRunId),
1145
+ index("junior_automations_run_now_due_idx").on(table.runNowAtMs, table.createdAtMs, table.id).where(sql`${table.status} = 'active' AND ${table.runNowAtMs} IS NOT NULL`),
1146
+ index("junior_automations_next_run_due_idx").on(table.nextRunAtMs, table.createdAtMs, table.id).where(sql`${table.status} = 'active' AND ${table.nextRunAtMs} IS NOT NULL`),
1147
+ index("junior_automations_skill_idx").on(table.skill, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted' AND ${table.skill} IS NOT NULL`),
1148
+ index("junior_automations_match_idx").on(table.namespace, table.identifier, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`),
1149
+ index("junior_automations_search_idx").using("gin", automationSearchDocument(table)).where(sql`${table.status} <> 'deleted'`),
1150
+ index("junior_automations_title_trgm_idx").using("gin", sql`${automationFuzzyTitle(table)} gin_trgm_ops`).where(sql`${table.status} <> 'deleted'`)
1151
+ ]);
1152
+ // src/db/schema/inbox-items.ts
1153
+ /**
1154
+ * The words of an Inbox item for search: its title, ranked above its body.
1155
+ * The `simple` config keeps each word as typed, so a prefix of it matches.
1156
+ */
1157
+ function inboxItemSearchDocument(table) {
1158
+ return sql`(setweight(to_tsvector('simple', ${table.title}), 'A') || setweight(to_tsvector('simple', ${table.body}), 'B'))`;
1159
+ }
1160
+ /** The lowercase title of an Inbox item, for typo-tolerant search. */
1161
+ function inboxItemFuzzyTitle(table) {
1162
+ return sql`lower(${table.title})`;
1163
+ }
1164
+ /**
1165
+ * One Inbox item: something that needs a person. An action item stores its
1166
+ * `request`, and
1167
+ * its `answer` after an assignee submits it. `closed_at` is set for `done`
1168
+ * and `dismissed`. `closed_by_user_id` is null when an agent closed it.
1169
+ * `owner_kind` and `owner_id` name its owner. The owner kind decides how the
1170
+ * item gets its visibility and tenant, and where the Inbox stacks it. The id
1171
+ * has no foreign key, because it can name a row of more than one table.
1172
+ */
1173
+ const juniorInboxItems = pgTable("junior_inbox_items", {
1174
+ id: text("id").primaryKey(),
1175
+ kind: text("kind").$type().notNull(),
1176
+ status: text("status").$type().notNull(),
1177
+ /**
1178
+ * `private` when the Conversation that added it is not public. A private
1179
+ * item stays private and links only to that Conversation.
1180
+ */
1181
+ visibility: text("visibility").$type().notNull(),
1182
+ title: text("title").notNull(),
1183
+ body: text("body").notNull(),
1184
+ request: jsonb("request").$type(),
1185
+ answer: jsonb("answer").$type(),
1186
+ assignedToEveryone: boolean("assigned_to_everyone").notNull().default(false),
1187
+ dedupeKey: text("dedupe_key").notNull(),
1188
+ subjectId: text("subject_id"),
1189
+ subjectTitle: text("subject_title"),
1190
+ subjectUrl: text("subject_url"),
1191
+ /** The parsed subject title of a code change (`InboxItemSubjectTitleParts`). */
1192
+ subjectTitleParts: jsonb("subject_title_parts").$type(),
1193
+ ownerKind: text("owner_kind").$type().notNull().default("conversation"),
1194
+ ownerId: text("owner_id").notNull(),
1195
+ /**
1196
+ * Turn of the agent that added the item, or that last added it again with
1197
+ * its dedupe key. Null for a plugin item, which has no Turn.
1198
+ */
1199
+ addedByTurnId: text("added_by_turn_id"),
1200
+ /**
1201
+ * Provider tenant, such as a Slack workspace, of the Conversation that
1202
+ * added the item. A public item is visible only inside it.
1203
+ */
1204
+ provider: text("provider"),
1205
+ providerTenantId: text("provider_tenant_id"),
1206
+ automationId: text("automation_id").references(() => juniorAutomations.id, { onDelete: "set null" }),
1207
+ closedAt: timestamptz("closed_at"),
1208
+ closedByUserId: text("closed_by_user_id").references(() => juniorUsers.id, { onDelete: "set null" }),
1209
+ closeReason: text("close_reason"),
1210
+ createdAt: timestamptz("created_at").notNull(),
1211
+ updatedAt: timestamptz("updated_at").notNull()
1212
+ }, (table) => [
1213
+ check("junior_inbox_items_kind_check", sql`(${table.kind} = 'notice' and ${table.request} is null and ${table.answer} is null) or (${table.kind} = 'action' and (${table.request} is not null or ((${table.dedupeKey} like 'plugin:%' or ${table.dedupeKey} like 'automation:%' or ${table.dedupeKey} like 'todo:%') and ${table.answer} is null)))`),
1214
+ check("junior_inbox_items_owner_check", sql`(${table.ownerKind} = 'conversation' and ${table.dedupeKey} not like 'automation:%') or (${table.ownerKind} = 'automation' and ${table.dedupeKey} like 'automation:%')`),
1215
+ check("junior_inbox_items_status_check", sql`(${table.status} = 'open' and ${table.closedAt} is null) or (${table.status} in ('done', 'dismissed') and ${table.closedAt} is not null)`),
1216
+ check("junior_inbox_items_tenant_check", sql`(${table.provider} is null) = (${table.providerTenantId} is null)`),
1217
+ check("junior_inbox_items_visibility_check", sql`${table.visibility} = 'public' or not ${table.assignedToEveryone}`),
1218
+ uniqueIndex("junior_inbox_items_open_dedupe_uidx").on(sql`coalesce(${table.provider}, '')`, sql`coalesce(${table.providerTenantId}, '')`, table.dedupeKey).where(sql`${table.status} = 'open'`),
1219
+ index("junior_inbox_items_status_idx").on(table.status, table.updatedAt, table.id),
1220
+ index("junior_inbox_items_subject_idx").on(table.subjectId, table.status),
1221
+ index("junior_inbox_items_owner_idx").on(table.ownerKind, table.ownerId),
1222
+ index("junior_inbox_items_open_action_owner_idx").on(table.ownerId).where(sql`${table.status} = 'open' and ${table.kind} = 'action'`),
1223
+ index("junior_inbox_items_automation_idx").on(table.automationId, table.status),
1224
+ index("junior_inbox_items_answered_idx").on(table.ownerId, table.closedByUserId, table.closedAt).where(sql`${table.answer} is not null`),
1225
+ index("junior_inbox_items_search_idx").using("gin", inboxItemSearchDocument(table)),
1226
+ index("junior_inbox_items_title_trgm_idx").using("gin", sql`${inboxItemFuzzyTitle(table)} gin_trgm_ops`)
1227
+ ]);
1228
+ /** The assigned Users of an Inbox item. Everyone is a flag on the item. */
1229
+ const juniorInboxItemAssignees = pgTable("junior_inbox_item_assignees", {
1230
+ itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1231
+ userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" })
1232
+ }, (table) => [primaryKey({ columns: [table.itemId, table.userId] }), index("junior_inbox_item_assignees_user_idx").on(table.userId)]);
1233
+ /** The Conversations linked to an Inbox item. */
1234
+ const juniorInboxItemConversations = pgTable("junior_inbox_item_conversations", {
1235
+ itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1236
+ conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" })
1237
+ }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] }), index("junior_inbox_item_conversations_conversation_idx").on(table.conversationId)]);
1238
+ /**
1239
+ * The Slack message that shows an Inbox item in one linked Slack thread.
1240
+ * Junior updates it in place after each change.
1241
+ */
1242
+ const juniorInboxItemSlackCards = pgTable("junior_inbox_item_slack_cards", {
1243
+ itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1244
+ conversationId: text("conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
1245
+ teamId: text("team_id").notNull(),
1246
+ channelId: text("channel_id").notNull(),
1247
+ messageTs: text("message_ts").notNull()
1248
+ }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] })]);
1249
+ /**
1250
+ * One notification of one Inbox item event to one assigned User on one
1251
+ * channel: a Slack card in a thread of the item, or a web push. The key stops a second send for the same event, also on a
1252
+ * retry. `skip_reason` says why a `skipped` row sent nothing. A `sent` row
1253
+ * becomes `cleared` when the item closes, so the devices can close it.
1254
+ */
1255
+ const juniorInboxItemDeliveries = pgTable("junior_inbox_item_deliveries", {
1256
+ itemId: text("item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1257
+ userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1258
+ channel: text("channel").$type().notNull(),
1259
+ event: text("event").$type().notNull(),
1260
+ status: text("status").$type().notNull(),
1261
+ skipReason: text("skip_reason"),
1262
+ createdAt: timestamptz("created_at").notNull(),
1263
+ updatedAt: timestamptz("updated_at").notNull()
1264
+ }, (table) => [primaryKey({ columns: [
1265
+ table.itemId,
1266
+ table.userId,
1267
+ table.channel,
1268
+ table.event
1269
+ ] }), index("junior_inbox_item_deliveries_user_status_idx").on(table.userId, table.status, table.updatedAt)]);
1270
+ // src/db/schema/inbox-snoozes.ts
1271
+ /**
1272
+ * One person's snooze of one Inbox item. A `snoozed` row hides the item
1273
+ * from that person's Inbox until one of its triggers fires. `woken` and
1274
+ * `cancelled` are final. The item's own status says whether it resolved.
1275
+ * A trigger that wakes it records why in `wake_reason`, which only that
1276
+ * person sees, until they open or act on the item.
1277
+ */
1278
+ const juniorInboxSnoozes = pgTable("junior_inbox_snoozes", {
1279
+ id: text("id").primaryKey(),
1280
+ userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1281
+ inboxItemId: text("inbox_item_id").notNull().references(() => juniorInboxItems.id, { onDelete: "cascade" }),
1282
+ state: text("state").$type().notNull(),
1283
+ wakeReason: jsonb("wake_reason").$type(),
1284
+ createdAt: timestamptz("created_at").notNull()
1285
+ }, (table) => [
1286
+ check("junior_inbox_snoozes_state_check", sql`${table.state} in ('snoozed', 'woken', 'cancelled')`),
1287
+ uniqueIndex("junior_inbox_snoozes_snoozed_uidx").on(table.userId, table.inboxItemId).where(sql`${table.state} = 'snoozed'`),
1288
+ index("junior_inbox_snoozes_settled_idx").on(table.createdAt).where(sql`${table.state} <> 'snoozed'`),
1289
+ index("junior_inbox_snoozes_inbox_item_idx").on(table.inboxItemId)
1290
+ ]);
1291
+ /**
1292
+ * An Event that ends a snooze. `wake` brings the item back; `resolve`
1293
+ * dismisses the item and cancels the snooze. A snooze's triggers join with
1294
+ * OR: the first to fire wins, and the snooze ignores the rest. Time is a
1295
+ * `timer.fired` Event like any other.
1296
+ */
1297
+ const juniorInboxSnoozeTriggers = pgTable("junior_inbox_snooze_triggers", {
1298
+ snoozeId: text("snooze_id").notNull().references(() => juniorInboxSnoozes.id, { onDelete: "cascade" }),
1299
+ outcome: text("outcome").$type().notNull(),
1300
+ namespace: text("namespace").notNull(),
1301
+ identifier: text("identifier").notNull(),
1302
+ eventType: text("event_type").notNull(),
1303
+ match: jsonb("match").$type()
1304
+ }, (table) => [
1305
+ check("junior_inbox_snooze_triggers_outcome_check", sql`${table.outcome} in ('wake', 'resolve')`),
1306
+ index("junior_inbox_snooze_triggers_event_idx").on(table.namespace, table.identifier, table.eventType),
1307
+ index("junior_inbox_snooze_triggers_snooze_idx").on(table.snoozeId)
1308
+ ]);
1309
+ // src/db/schema/stats.ts
1310
+ /**
1311
+ * Daily named counters used by Junior and loaded plugins.
1312
+ * TODO: store hour keys when dashboard 24h workspace usage needs hourly bars.
1313
+ * `date` is a Postgres date column, so counters stay day-bucketed today.
1314
+ */
1315
+ const juniorStats = pgTable("junior_stats", {
1316
+ date: date("date", { mode: "string" }).notNull(),
1317
+ namespace: text("namespace").notNull(),
1318
+ metric: text("metric").notNull(),
1319
+ name: text("name").notNull(),
1320
+ count: bigint("value", { mode: "number" }).notNull().default(0),
1321
+ legacyCount: integer("count").notNull().default(0)
1322
+ }, (table) => [primaryKey({
1323
+ name: "junior_stats_date_namespace_metric_name_pk",
1324
+ columns: [
1325
+ table.date,
1326
+ table.namespace,
1327
+ table.metric,
1328
+ table.name
1329
+ ]
1330
+ })]);
1331
+ // src/db/schema/todos.ts
1332
+ /**
1333
+ * Gives each To-do its id and each change its version. One sequence serves
1334
+ * every Conversation, so history that a fork copies from its parent never
1335
+ * shows a version that the fork's own To-dos reuse.
1336
+ */
1337
+ const juniorTodoVersionSeq = pgSequence("junior_todo_version_seq");
1338
+ /**
1339
+ * The words of a To-do title for search. The `simple` config keeps each
1340
+ * word as typed, so a prefix of it matches.
1341
+ */
1342
+ function todoSearchDocument(table) {
1343
+ return sql`to_tsvector('simple', ${table.title})`;
1344
+ }
1345
+ /** The lowercase title of a To-do, for typo-tolerant search. */
1346
+ function todoFuzzyTitle(table) {
1347
+ return sql`lower(${table.title})`;
1348
+ }
1349
+ /**
1350
+ * One To-do: work that a Conversation has not finished. At most one
1351
+ * assignee: a Conversation (the list's own agent or one of its child agents)
1352
+ * or a User. A To-do without one belongs to the list's own agent.
1353
+ * `changed_by_user_id` is set when a person made the latest change.
1354
+ * `changed_by_conversation_id` is set when the assignee child agent closed
1355
+ * it, or core closed it on that child's result. Both are null when the
1356
+ * list's own agent made the latest change. Both User keys block deleting the User, as
1357
+ * Conversation participants do: setting them null would turn a person's
1358
+ * To-do into the agent's and hide an unseen change from `<todo-delta>`.
1359
+ */
1360
+ const juniorTodos = pgTable("junior_todos", {
1361
+ conversationId: text("conversation_id").notNull(),
1362
+ id: bigint("id", { mode: "number" }).notNull(),
1363
+ title: text("title").notNull(),
1364
+ notes: text("notes"),
1365
+ status: text("status").$type().notNull(),
1366
+ assigneeConversationId: text("assignee_conversation_id"),
1367
+ assigneeUserId: text("assignee_user_id").references(() => juniorUsers.id),
1368
+ version: bigint("version", { mode: "number" }).notNull(),
1369
+ changedByUserId: text("changed_by_user_id").references(() => juniorUsers.id),
1370
+ changedByConversationId: text("changed_by_conversation_id"),
1371
+ createdAt: timestamptz("created_at").notNull(),
1372
+ updatedAt: timestamptz("updated_at").notNull()
1373
+ }, (table) => [
1374
+ primaryKey({
1375
+ name: "junior_todos_pk",
1376
+ columns: [table.conversationId, table.id]
1377
+ }),
1378
+ foreignKey({
1379
+ name: "junior_todos_conversation_id_fk",
1380
+ columns: [table.conversationId],
1381
+ foreignColumns: [juniorConversations.conversationId]
1382
+ }).onDelete("cascade"),
1383
+ check("junior_todos_status_check", sql`${table.status} in ('open', 'in_progress', 'done', 'dropped')`),
1384
+ check("junior_todos_assignee_check", sql`${table.assigneeConversationId} is null or ${table.assigneeUserId} is null`),
1385
+ index("junior_todos_search_idx").using("gin", todoSearchDocument(table)),
1386
+ index("junior_todos_title_trgm_idx").using("gin", sql`${todoFuzzyTitle(table)} gin_trgm_ops`)
1387
+ ]);
1388
+ // src/db/schema/push-subscriptions.ts
1389
+ /**
1390
+ * One browser Web Push subscription for one user. A user can have one row for
1391
+ * each browser or installed dashboard app. The push service owns the endpoint.
1392
+ */
1393
+ const juniorPushSubscriptions = pgTable("junior_push_subscriptions", {
1394
+ id: text("id").primaryKey(),
1395
+ userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1396
+ endpoint: text("endpoint").notNull(),
1397
+ p256dh: text("p256dh").notNull(),
1398
+ auth: text("auth").notNull(),
1399
+ createdAt: timestamptz("created_at").notNull(),
1400
+ updatedAt: timestamptz("updated_at").notNull()
1401
+ }, (table) => [uniqueIndex("junior_push_subscriptions_endpoint_uidx").on(table.endpoint), index("junior_push_subscriptions_user_idx").on(table.userId)]);
1402
+ // src/db/schema/workspaces.ts
1403
+ /** Named recipe used to prepare a reusable Sandbox. */
1404
+ const juniorWorkspaces = pgTable("junior_workspaces", {
1405
+ id: text("id").primaryKey(),
1406
+ name: text("name").notNull(),
1407
+ setupScript: text("setup_script").notNull().default(""),
1408
+ vcpus: integer("vcpus"),
1409
+ createdAt: timestamptz("created_at").notNull(),
1410
+ updatedAt: timestamptz("updated_at").notNull()
1411
+ }, (table) => [uniqueIndex("junior_workspaces_name_idx").on(table.name)]);
1412
+ /** Repository included in one Workspace recipe. */
1413
+ const juniorWorkspaceRepos = pgTable("junior_workspace_repos", {
1414
+ workspaceId: text("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
1415
+ provider: text("provider").notNull(),
1416
+ repo: text("repo").notNull()
1417
+ }, (table) => [primaryKey({ columns: [
1418
+ table.workspaceId,
1419
+ table.provider,
1420
+ table.repo
1421
+ ] })]);
1422
+ // src/db/schema/snapshots.ts
1423
+ /**
1424
+ * Sandbox snapshot build and ready artifact for one Workspace recipe.
1425
+ * A ready row keeps its builder owner until the snapshot is discarded.
1426
+ */
1427
+ const juniorSnapshots = pgTable("junior_snapshots", {
1428
+ id: text("id").primaryKey(),
1429
+ workspaceId: text("workspace_id").notNull().references(() => juniorWorkspaces.id, { onDelete: "cascade" }),
1430
+ profileHash: text("profile_hash").notNull(),
1431
+ status: text("status").$type().notNull(),
1432
+ snapshotId: text("snapshot_id"),
1433
+ buildDurationMs: integer("build_duration_ms"),
1434
+ sizeBytes: bigint("size_bytes", { mode: "number" }),
1435
+ generatedAt: timestamptz("generated_at"),
1436
+ buildStartedAt: timestamptz("build_started_at"),
1437
+ buildPhase: text("build_phase").$type(),
1438
+ buildSandboxName: text("build_sandbox_name"),
1439
+ buildCommandId: text("build_command_id"),
1440
+ buildError: text("build_error"),
1441
+ createdAt: timestamptz("created_at").notNull(),
1442
+ updatedAt: timestamptz("updated_at").notNull()
1443
+ }, (table) => [
1444
+ check("junior_snapshots_status_check", sql`${table.status} in ('building', 'failed', 'ready')`),
1445
+ check("junior_snapshots_build_phase_check", sql`${table.buildPhase} is null or ${table.buildPhase} in ('created', 'dependencies_installed', 'repositories_prepared')`),
1446
+ check("junior_snapshots_ready_fields_check", sql`${table.status} <> 'ready' or (${table.snapshotId} is not null and ${table.buildDurationMs} is not null and ${table.generatedAt} is not null)`),
1447
+ check("junior_snapshots_build_fields_check", sql`${table.status} = 'ready' or (${table.buildStartedAt} is not null and ${table.buildPhase} is not null)`),
1448
+ check("junior_snapshots_build_duration_check", sql`${table.buildDurationMs} is null or ${table.buildDurationMs} >= 0`),
1449
+ check("junior_snapshots_size_bytes_check", sql`${table.sizeBytes} is null or ${table.sizeBytes} >= 0`),
1450
+ uniqueIndex("junior_snapshots_snapshot_id_uidx").on(table.snapshotId),
1451
+ index("junior_snapshots_workspace_idx").on(table.workspaceId),
1452
+ index("junior_snapshots_workspace_profile_status_idx").on(table.workspaceId, table.profileHash, table.status),
1453
+ uniqueIndex("junior_snapshots_active_build_uidx").on(table.workspaceId, table.profileHash).where(sql`${table.status} = 'building'`),
1454
+ index("junior_snapshots_workspace_status_idx").on(table.workspaceId, table.status)
1455
+ ]);
1456
+ // src/db/schema.ts
1457
+ const juniorSqlSchema = {
1458
+ juniorArtifacts,
1459
+ juniorAttachmentUploads,
1460
+ juniorAttachments,
1461
+ juniorMessageAttachments,
1462
+ juniorCodeChanges,
1463
+ juniorCodeRepositories,
1464
+ juniorConversationAnnotations,
1465
+ juniorApiTokens,
1466
+ juniorAgentBindings,
1467
+ juniorConversationEvents,
1468
+ juniorConversationMetrics,
1469
+ juniorConversationEmbeddings,
1470
+ juniorConversationEventEmbeddings,
1471
+ juniorConversationEventLexemes,
1472
+ juniorConversationBriefs,
1473
+ juniorConversationBindings,
1474
+ juniorConversationParticipants,
1475
+ juniorConversationReadPositions,
1476
+ juniorConversations,
1477
+ juniorLocationConfigurations,
1478
+ juniorMemoryEmbeddings,
1479
+ juniorMemoryMemories,
1480
+ juniorMemorySignals,
1481
+ juniorDestinations,
1482
+ juniorIdentities,
1483
+ juniorInboxSnoozes,
1484
+ juniorInboxSnoozeTriggers,
1485
+ juniorInboxItemAssignees,
1486
+ juniorInboxItemConversations,
1487
+ juniorInboxItemDeliveries,
1488
+ juniorInboxItemSlackCards,
1489
+ juniorInboxItems,
1490
+ juniorTodos,
1491
+ juniorPushSubscriptions,
1492
+ juniorSnapshots,
1493
+ juniorStats,
1494
+ juniorAutomationRuns,
1495
+ juniorAutomationVersions,
1496
+ juniorAutomations,
1497
+ juniorUsers,
1498
+ juniorWorkspaceRepos,
1499
+ juniorWorkspaces
1500
+ };
44
1501
  // src/chat/conversations/sql/detail-version.ts
45
1502
  /** SQL that advances `detail_version` inside a `juniorConversations` set. */
46
1503
  const nextDetailVersion = sql`${juniorConversations.detailVersion} + 1`;
@@ -1084,14 +2541,14 @@ async function resolveAssignee(db, value, tenant, findMentionedUserId) {
1084
2541
  if (mentionedUserId) return { userId: mentionedUserId };
1085
2542
  if (text.includes("@")) {
1086
2543
  const user = await findUserByEmailFromSql(db, text);
1087
- if (!user) throw new ToolInputError(`No User has the email ${text}.`);
2544
+ if (!user) throw new ToolInputError(`No User has the email ${text}. Use their mention, such as <@U123>, or another email.`);
1088
2545
  return { userId: user.id };
1089
2546
  }
1090
2547
  throw new ToolInputError(`Unknown assignee ${JSON.stringify(text)}. Use ${EVERYONE_ASSIGNEE}, an email, or a mention such as <@U123>.`);
1091
2548
  }
1092
2549
  /** Resolve the assignees of an Inbox item. One is required. */
1093
2550
  async function resolveAssignees(db, values, tenant, findMentionedUserId) {
1094
- if (values.length === 0) throw new ToolInputError("An inbox item needs at least one assignee.");
2551
+ if (values.length === 0) throw new ToolInputError("An inbox item needs at least one assignee. Add an entry to `assignees`.");
1095
2552
  const resolved = await mapBounded(values, (value) => resolveAssignee(db, value, tenant, findMentionedUserId));
1096
2553
  return {
1097
2554
  everyone: resolved.some((assignee) => "everyone" in assignee),
@@ -1143,28 +2600,42 @@ function inboxItemReaderForUser(user) {
1143
2600
  function inboxItemOwnedByConversation(conversationId) {
1144
2601
  return and(eq(juniorInboxItems.ownerKind, "conversation"), eq(juniorInboxItems.ownerId, conversationId));
1145
2602
  }
1146
- /** SQL: the Inbox item has this assigned User. */
2603
+ const todoOwner = alias(juniorConversations, "todo_owner");
2604
+ const todoRoot = alias(juniorConversations, "todo_root");
2605
+ const todoDestination = alias(juniorDestinations, "todo_destination");
2606
+ /** SQL: the User is a Participant of this root Conversation. */
2607
+ function participantOf(userId, rootConversationId) {
2608
+ return exists(getDb().select({ one: sql`1` }).from(juniorConversationParticipants).where(and(eq(juniorConversationParticipants.rootConversationId, rootConversationId), eq(juniorConversationParticipants.userId, userId))));
2609
+ }
2610
+ /**
2611
+ * SQL: the User can see the private content of the Conversation that owns
2612
+ * the item. This is the rule of `conversationAccessFromRows`: the User is a
2613
+ * Participant of the owner when it has no parent, even with no stored root.
2614
+ * Otherwise the owner needs a valid stored root, whose Destination is public
2615
+ * or whose Participants include the User.
2616
+ */
2617
+ function ownerConversationOpenTo(userId) {
2618
+ return exists(getDb().select({ one: sql`1` }).from(todoOwner).leftJoin(todoRoot, and(eq(todoRoot.conversationId, todoOwner.rootConversationId), eq(todoRoot.rootConversationId, todoRoot.conversationId), isNull(todoRoot.parentConversationId), or(isNotNull(todoOwner.parentConversationId), eq(todoOwner.rootConversationId, todoOwner.conversationId)))).leftJoin(todoDestination, eq(todoDestination.id, todoRoot.destinationId)).where(and(eq(todoOwner.conversationId, juniorInboxItems.ownerId), or(and(isNull(todoOwner.parentConversationId), participantOf(userId, todoOwner.conversationId)), and(isNotNull(todoRoot.conversationId), or(eq(todoDestination.visibility, "public"), participantOf(userId, todoRoot.conversationId)))))));
2619
+ }
2620
+ /**
2621
+ * SQL: the Inbox item has this assigned User. A To-do's item counts only
2622
+ * while the User can see its Conversation's private content, so a person
2623
+ * who loses access to the Conversation no longer sees or acts on it.
2624
+ */
1147
2625
  function inboxItemAssignedTo(userId) {
1148
- return sql`exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id} and ${juniorInboxItemAssignees.userId} = ${userId})`;
2626
+ return and(sql`exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id} and ${juniorInboxItemAssignees.userId} = ${userId})`, or(notLike(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`), ownerConversationOpenTo(userId)));
1149
2627
  }
1150
2628
  /**
1151
2629
  * SQL: the Inbox item needs this User. Only an open `action` item that is
1152
2630
  * assigned to the User needs them. A notice, an item for Everyone, and an
1153
- * item without assignees need no one. An assigned User can always see the
1154
- * item, so this rule needs no visibility check. The nav count and the
2631
+ * item without assignees need no one. An assigned User can see the item
2632
+ * (`inboxItemAssignedTo`), so this rule needs no other visibility check. The nav count and the
1155
2633
  * "Waiting on you" marker use this rule.
1156
2634
  */
1157
2635
  function inboxItemNeedsUser(userId) {
1158
2636
  return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), inboxItemAssignedTo(userId));
1159
2637
  }
1160
2638
  /**
1161
- * SQL: the Inbox item needs some person: an open `action` item with an
1162
- * assigned User. It is `inboxItemNeedsUser` for any User.
1163
- */
1164
- function inboxItemNeedsSomeone() {
1165
- return and(eq(juniorInboxItems.status, "open"), eq(juniorInboxItems.kind, "action"), sql`exists (select 1 from ${juniorInboxItemAssignees} where ${juniorInboxItemAssignees.itemId} = ${juniorInboxItems.id})`);
1166
- }
1167
- /**
1168
2639
  * SQL: the Inbox item waits for a person's input: an open `action` item,
1169
2640
  * whoever it is assigned to. An item with no assignees still waits for
1170
2641
  * anyone who can answer it. The Conversation that added it shows
@@ -1208,6 +2679,11 @@ function canReadInboxItem(item, reader) {
1208
2679
  * enough: a private item stays private when its Conversation becomes public.
1209
2680
  */
1210
2681
  async function canUserReadInboxItem(item, user) {
2682
+ const todo = inboxItemTodo(item);
2683
+ if (todo) {
2684
+ if (!item.assignees.some((assignee) => assignee.userId === user.id)) return false;
2685
+ return (await readConversationAccessFromSql(getDb(), [todo.conversationId], user)).get(todo.conversationId)?.canViewPrivateContent === true;
2686
+ }
1211
2687
  if (canReadInboxItem(item, inboxItemReaderForUser(user))) return true;
1212
2688
  const access = await readConversationAccessFromSql(getDb(), item.conversationIds, user);
1213
2689
  return item.conversationIds.some((id) => access.get(id)?.isParticipant === true);
@@ -1257,6 +2733,62 @@ const PLUGIN_INBOX_ITEM_KEY_PREFIX = "plugin:";
1257
2733
  * and closes. An agent cannot use the prefix.
1258
2734
  */
1259
2735
  const AUTOMATION_INBOX_ITEM_KEY_PREFIX = "automation:";
2736
+ /**
2737
+ * Dedupe keys with this prefix belong to To-dos for a person, which core
2738
+ * adds and closes as the To-do changes (`syncTodoInboxItems`). An agent
2739
+ * cannot use the prefix.
2740
+ */
2741
+ const TODO_INBOX_ITEM_KEY_PREFIX = "todo:";
2742
+ /**
2743
+ * Return the To-do that an item shows, or undefined for any other item. The
2744
+ * key is `todo:<conversationId>:<todoId>`, and a Conversation id can hold
2745
+ * colons.
2746
+ */
2747
+ function inboxItemTodo(item) {
2748
+ if (!item.dedupeKey.startsWith("todo:")) return void 0;
2749
+ const rest = item.dedupeKey.slice(5);
2750
+ const split = rest.lastIndexOf(":");
2751
+ const id = Number(rest.slice(split + 1));
2752
+ if (split <= 0 || !Number.isSafeInteger(id) || id <= 0) return void 0;
2753
+ return {
2754
+ conversationId: rest.slice(0, split),
2755
+ id
2756
+ };
2757
+ }
2758
+ /**
2759
+ * Dedupe keys with this prefix belong to reply notices, which core adds for
2760
+ * the starter of a dashboard Conversation and closes when they read the
2761
+ * reply. An agent cannot use the prefix or change the item.
2762
+ */
2763
+ const REPLY_NOTICE_KEY_PREFIX = "reply:";
2764
+ const USE_ANOTHER_KEY = "Use a different key.";
2765
+ /**
2766
+ * The dedupe key prefixes that core and plugins own, with their owner and
2767
+ * what to do instead. The add tool's input schema rejects a key that starts
2768
+ * with one of them.
2769
+ */
2770
+ const RESERVED_INBOX_ITEM_KEY_PREFIXES = [
2771
+ {
2772
+ owner: "a plugin",
2773
+ prefix: PLUGIN_INBOX_ITEM_KEY_PREFIX,
2774
+ instead: USE_ANOTHER_KEY
2775
+ },
2776
+ {
2777
+ owner: "an Automation alert",
2778
+ prefix: AUTOMATION_INBOX_ITEM_KEY_PREFIX,
2779
+ instead: USE_ANOTHER_KEY
2780
+ },
2781
+ {
2782
+ owner: "a reply notice",
2783
+ prefix: REPLY_NOTICE_KEY_PREFIX,
2784
+ instead: USE_ANOTHER_KEY
2785
+ },
2786
+ {
2787
+ owner: "a To-do",
2788
+ prefix: TODO_INBOX_ITEM_KEY_PREFIX,
2789
+ instead: `Assign a To-do to the person with ${UPDATE_TODOS_TOOL_NAME} instead.`
2790
+ }
2791
+ ];
1260
2792
  /** Return the plugin that owns a dedupe key, or undefined for an agent's key. */
1261
2793
  function inboxItemPlugin(dedupeKey) {
1262
2794
  if (!dedupeKey.startsWith("plugin:")) return void 0;
@@ -1276,10 +2808,12 @@ function isPluginInboxItem(item) {
1276
2808
  * Conversation, so private content never reaches its readers. A private
1277
2809
  * item changes only from the Conversation or Automation that added it. An
1278
2810
  * agent never changes an item that a plugin added, or an item that another
1279
- * owner kind, such as an Automation, owns.
2811
+ * owner kind, such as an Automation, owns, or a reply notice.
1280
2812
  */
1281
2813
  function canAgentChangeInboxItem(item, scope) {
1282
2814
  if (item.dedupeKey.startsWith("plugin:")) return false;
2815
+ if (item.dedupeKey.startsWith("todo:")) return false;
2816
+ if (item.dedupeKey.startsWith("reply:")) return false;
1283
2817
  if (item.owner.kind !== "conversation") return false;
1284
2818
  if (!isSameTenant(item.tenant, scope.tenant)) return false;
1285
2819
  if (item.visibility === "public") return !scope.inPrivateConversation;
@@ -1295,10 +2829,10 @@ async function requireInboxItemLinks(args) {
1295
2829
  const access = await readConversationAccessFromSql(getDb(), args.conversationIds, args.scope.user);
1296
2830
  for (const conversationId of args.conversationIds) {
1297
2831
  const conversation = access.get(conversationId);
1298
- if (!conversation || !isSameTenant(conversation.tenant, args.tenant)) throw new ToolInputError(`Conversation ${conversationId} is not found.`);
2832
+ if (!conversation || !isSameTenant(conversation.tenant, args.tenant)) throw new ToolInputError(`Conversation ${conversationId} is not found. Check conversation_ids, or use searchConversations to find the id.`);
1299
2833
  if (args.allowedIds.has(conversationId)) continue;
1300
- if (args.visibility === "private") throw new ToolInputError("A private item links only to the Conversation that added it.");
1301
- if (conversation.visibility !== "public") throw new ToolInputError(conversation.canViewPrivateContent ? `Conversation ${conversationId} is private. Only public Conversations can be linked.` : `Conversation ${conversationId} is not found.`);
2834
+ if (args.visibility === "private") throw new ToolInputError("A private item links only to the Conversation that added it. Remove the other ids from `conversation_ids`.");
2835
+ if (conversation.visibility !== "public") throw new ToolInputError(conversation.canViewPrivateContent ? `Conversation ${conversationId} is private. Only public Conversations can be linked.` : `Conversation ${conversationId} is not found. Check conversation_ids, or use searchConversations to find the id.`);
1302
2836
  }
1303
2837
  }
1304
2838
  /**
@@ -1315,7 +2849,7 @@ async function requireInboxItemAssignees(args) {
1315
2849
  const creatorId = args.automationId ? await automationCreatorUserId(getDb(), args.automationId) : void 0;
1316
2850
  const others = args.assignees.userIds.filter((id) => id !== args.scope.user?.id && id !== creatorId);
1317
2851
  const inConversation = await conversationParticipantUserIds(getDb(), args.conversationIds, others);
1318
- if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation.");
2852
+ if (others.some((id) => !inConversation.has(id))) throw new ToolInputError("A private item can be assigned only to people in its Conversation. Remove the other people from `assignees`.");
1319
2853
  }
1320
2854
  /**
1321
2855
  * Return whether a User can act on an open Inbox item: an assigned User,
@@ -1351,8 +2885,8 @@ const AUTHORIZATION_WAIT_MS = 864e5;
1351
2885
  /**
1352
2886
  * The request and the events that end its wait: the person connected, or a
1353
2887
  * Turn started or ended after the request. A stop or new input ends the
1354
- * parked Turn with `turn_completed`. A child agent invocation that needs a
1355
- * connection abandons its Turn and ends it as `blocked`, so nothing resumes
2888
+ * parked Turn with `turn_completed`. A child agent's Turn on a parent message
2889
+ * that needs a connection abandons its Turn and ends it as `blocked`, so nothing resumes
1356
2890
  * it and its parent gets the result instead.
1357
2891
  */
1358
2892
  const AUTHORIZATION_WAIT_EVENT_TYPES = [
@@ -1565,7 +3099,7 @@ function conversationWaitsOnStarterSql(conversation) {
1565
3099
  * or an idle Conversation.
1566
3100
  */
1567
3101
  function conversationStatusSql(conversation) {
1568
- const needsInput = sql`exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(conversation.conversationId), inboxItemNeedsInput())})`;
3102
+ const needsInput = sql`exists (select 1 from ${juniorInboxItems} where ${and(inboxItemOwnedByConversation(conversation.conversationId), inboxItemNeedsInput(), notLike(juniorInboxItems.dedupeKey, `${TODO_INBOX_ITEM_KEY_PREFIX}%`))})`;
1569
3103
  return sql`case
1570
3104
  when ${needsInput} or ${awaitsAuthorization(conversation.conversationId)} or ${conversationWaitsOnStarterSql(conversation)} then 'needs_input'
1571
3105
  when ${conversationIsActiveSql(conversation)} then 'working'
@@ -1670,6 +3204,15 @@ const MICRO_USD_PER_USD = 1e6;
1670
3204
  function usdToMicroUsd(usd) {
1671
3205
  return Math.round(usd * MICRO_USD_PER_USD);
1672
3206
  }
3207
+ /**
3208
+ * Round a USD amount to whole micro-USD, up with the chance of its fraction.
3209
+ * Use it for amounts far below one micro-USD, such as one short embedding
3210
+ * call: plain rounding stores zero each time, and this keeps a sum of many
3211
+ * amounts right on average.
3212
+ */
3213
+ function usdToMicroUsdUnbiased(usd) {
3214
+ return Math.floor(usd * MICRO_USD_PER_USD + Math.random());
3215
+ }
1673
3216
  /** Convert stored micro-USD to USD for an API response. */
1674
3217
  function microUsdToUsd(microUsd) {
1675
3218
  return microUsd / MICRO_USD_PER_USD;
@@ -1842,7 +3385,7 @@ function normalizeSessionSource(value) {
1842
3385
  visibility: value.visibility,
1843
3386
  conversationId: value.conversationId
1844
3387
  };
1845
- if (value.kind === "event" || value.kind === "scheduled_automation" || value.kind === "event_automation" || value.kind === "plugin_dispatch" || value.kind === "agent_invocation") return;
3388
+ if (value.kind === "event" || value.kind === "scheduled_automation" || value.kind === "event_automation" || value.kind === "plugin_dispatch" || value.kind === "parent_message") return;
1846
3389
  const threadTs = value.threadTs?.trim();
1847
3390
  return {
1848
3391
  kind: "slack",
@@ -2067,6 +3610,7 @@ const ROOT = {
2067
3610
  waitsForSignIn: true,
2068
3611
  gated: false,
2069
3612
  failureNotice: "none",
3613
+ endResult: "none",
2070
3614
  sessionTasks: true,
2071
3615
  relatedConversations: true,
2072
3616
  tools: {
@@ -2087,6 +3631,8 @@ const PERSON_IN_THREAD = {
2087
3631
  ...ROOT,
2088
3632
  promptMode: "thread",
2089
3633
  sender: "person",
3634
+ failureNotice: "parent",
3635
+ endResult: "parent",
2090
3636
  sessionTasks: false,
2091
3637
  relatedConversations: false,
2092
3638
  tools: {
@@ -2100,7 +3646,9 @@ const CHILD_AGENT_TURN = {
2100
3646
  idleNeedsPendingWork: false,
2101
3647
  waitsForSignIn: false,
2102
3648
  gated: true,
2103
- failureNotice: "none",
3649
+ missingAnswerError: "No reply was sent.",
3650
+ failureNotice: "parent",
3651
+ endResult: "parent",
2104
3652
  sessionTasks: false,
2105
3653
  relatedConversations: false,
2106
3654
  tools: {
@@ -2124,11 +3672,6 @@ const THREAD_TOOLS = {
2124
3672
  subscriptions: PERSON_IN_THREAD.tools.subscriptions,
2125
3673
  userCustomization: PERSON_IN_THREAD.tools.userCustomization
2126
3674
  };
2127
- const AGENT_IN_TASK = {
2128
- ...CHILD_AGENT_TURN,
2129
- missingAnswerError: "No reply was sent.",
2130
- failureNotice: "parent"
2131
- };
2132
3675
  const AUTOMATION_RUN = {
2133
3676
  delivery: "conversation",
2134
3677
  promptMode: "automation",
@@ -2137,6 +3680,7 @@ const AUTOMATION_RUN = {
2137
3680
  waitsForSignIn: true,
2138
3681
  gated: true,
2139
3682
  failureNotice: "none",
3683
+ endResult: "none",
2140
3684
  sessionTasks: true,
2141
3685
  relatedConversations: false,
2142
3686
  tools: {
@@ -2167,6 +3711,15 @@ const LEAD_TOOLS = [
2167
3711
  "updateUserCustomization",
2168
3712
  "noReply"
2169
3713
  ];
3714
+ const LEAD_DIRECT_TOOLS = [
3715
+ "searchConversations",
3716
+ "searchConversationEvents",
3717
+ "readConversationEvent",
3718
+ "searchInboxItems",
3719
+ "searchEventTypes",
3720
+ "listWatches",
3721
+ "stopWatchingResources"
3722
+ ];
2170
3723
  const LEAD = {
2171
3724
  ...ROOT,
2172
3725
  promptMode: "lead",
@@ -2175,7 +3728,8 @@ const LEAD = {
2175
3728
  ...ROOT.tools,
2176
3729
  agents: "lead",
2177
3730
  subscriptions: false,
2178
- only: LEAD_TOOLS
3731
+ only: LEAD_TOOLS,
3732
+ direct: LEAD_DIRECT_TOOLS
2179
3733
  }
2180
3734
  };
2181
3735
  /** Return the behavior of one Turn. */
@@ -2185,7 +3739,7 @@ function turnBehavior(args) {
2185
3739
  case "automation": return args.personInput ? PERSON_IN_AUTOMATION : AUTOMATION_RUN;
2186
3740
  case "thread": return args.personInput ? PERSON_IN_THREAD : AGENT_IN_THREAD;
2187
3741
  case "task":
2188
- if (!args.personInput) return AGENT_IN_TASK;
3742
+ if (!args.personInput) return CHILD_AGENT_TURN;
2189
3743
  throw new Error("A task Conversation cannot have a person's input");
2190
3744
  case "lead": return LEAD;
2191
3745
  }
@@ -2198,7 +3752,7 @@ function turnBehavior(args) {
2198
3752
  function promptModeTurnTools(mode) {
2199
3753
  switch (mode) {
2200
3754
  case "automation": return AUTOMATION_RUN.tools;
2201
- case "child_agent": return AGENT_IN_TASK.tools;
3755
+ case "child_agent": return CHILD_AGENT_TURN.tools;
2202
3756
  case "thread": return THREAD_TOOLS;
2203
3757
  case "conversation": return ROOT.tools;
2204
3758
  case "lead": return LEAD.tools;
@@ -2243,7 +3797,7 @@ function personSourcePlatform(source) {
2243
3797
  case "scheduled_automation":
2244
3798
  case "event_automation":
2245
3799
  case "plugin_dispatch":
2246
- case "agent_invocation": return;
3800
+ case "parent_message": return;
2247
3801
  }
2248
3802
  }
2249
3803
  /** Return a short label that names a Source, such as `slack:T1:C1`. */
@@ -2256,7 +3810,7 @@ function sourceLabel(source) {
2256
3810
  case "scheduled_automation":
2257
3811
  case "event_automation":
2258
3812
  case "plugin_dispatch":
2259
- case "agent_invocation": return source.kind;
3813
+ case "parent_message": return source.kind;
2260
3814
  }
2261
3815
  }
2262
3816
  /**
@@ -2789,6 +4343,151 @@ async function refreshLastMessageAt(executor, conversationId) {
2789
4343
  const db = executor.db();
2790
4344
  await db.update(juniorConversations).set({ lastMessageAt: lastMessageAtSql(db) }).where(eq(juniorConversations.conversationId, conversationId));
2791
4345
  }
4346
+ // src/chat/actor.ts
4347
+ /**
4348
+ * Canonical actor identity.
4349
+ *
4350
+ * Runtime actors are platform-scoped actors. Stored Slack actor parsing
4351
+ * remains explicit so durable conversation metadata is not repaired on read.
4352
+ */
4353
+ const SLACK_USER_ID_DISPLAY_PATTERN = /^[UW][A-Z0-9]{5,}$/;
4354
+ const EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
4355
+ const exactStoredStringSchema = z.string().min(1).refine((value) => value === value.trim());
4356
+ const storedSlackActorSchema = z.object({
4357
+ email: exactStoredStringSchema.optional(),
4358
+ fullName: exactStoredStringSchema.optional(),
4359
+ platform: z.literal("slack").optional(),
4360
+ slackUserId: exactStoredStringSchema.optional(),
4361
+ slackUserName: exactStoredStringSchema.optional(),
4362
+ teamId: exactStoredStringSchema.optional()
4363
+ }).strict();
4364
+ /** Return whether an actor is a platform-scoped user actor. */
4365
+ function isUserActor(actor) {
4366
+ return Boolean(actor && "userId" in actor);
4367
+ }
4368
+ function clean(value) {
4369
+ const trimmed = value?.trim();
4370
+ return trimmed ? trimmed : void 0;
4371
+ }
4372
+ function isSyntheticActorUserId(value) {
4373
+ return value.toLowerCase() === "unknown";
4374
+ }
4375
+ /** Return whether a value has the shape of a Slack user id. */
4376
+ function isSlackUserId(value) {
4377
+ return SLACK_USER_ID_DISPLAY_PATTERN.test(value);
4378
+ }
4379
+ function cleanActorDisplayName(value, userId) {
4380
+ const displayName = clean(value);
4381
+ if (!displayName) return;
4382
+ if (displayName.toLowerCase() === "unknown") return;
4383
+ if (userId && displayName === userId) return;
4384
+ return isSlackUserId(displayName) ? void 0 : displayName;
4385
+ }
4386
+ function cleanActorEmail(value) {
4387
+ const email = clean(value);
4388
+ return email && EMAIL_PATTERN.test(email) ? email : void 0;
4389
+ }
4390
+ /** Keep actor ids exact at platform boundaries before they enter owned state. */
4391
+ function parseActorUserId(value) {
4392
+ if (typeof value !== "string" || value.length === 0) return;
4393
+ if (value !== value.trim() || isSyntheticActorUserId(value)) return;
4394
+ return value;
4395
+ }
4396
+ /** Assert persisted actor ids without read-side repair. */
4397
+ function isActorUserId(value) {
4398
+ return parseActorUserId(value) === value;
4399
+ }
4400
+ /** Build Junior's canonical platform actor from exact actor ids and profile data. */
4401
+ function createActor(input, context) {
4402
+ const platform = context.platform ?? input?.platform;
4403
+ if (!platform) return;
4404
+ const contextUserId = parseActorUserId(context.userId);
4405
+ if (context.userId !== void 0 && !contextUserId) return;
4406
+ const inputUserId = parseActorUserId(input?.userId);
4407
+ if (input?.userId !== void 0 && !inputUserId) return;
4408
+ const actorUserId = contextUserId ?? inputUserId;
4409
+ if (!actorUserId) return;
4410
+ const contextTeamId = parseSlackTeamId(context.teamId);
4411
+ if (context.teamId !== void 0 && !contextTeamId) return;
4412
+ const inputTeamId = parseSlackTeamId(input?.teamId);
4413
+ if (input?.teamId !== void 0 && !inputTeamId) return;
4414
+ const actorTeamId = contextTeamId ?? inputTeamId;
4415
+ if (platform === "slack" && !actorTeamId) return;
4416
+ const canUseInputProfile = (!contextUserId || !inputUserId || contextUserId === inputUserId) && (platform !== "slack" || !contextTeamId || !inputTeamId || contextTeamId === inputTeamId);
4417
+ const actor = {
4418
+ ...canUseInputProfile && cleanActorEmail(input?.email) ? { email: cleanActorEmail(input?.email) } : void 0,
4419
+ ...canUseInputProfile && cleanActorDisplayName(input?.fullName, actorUserId) ? { fullName: cleanActorDisplayName(input?.fullName, actorUserId) } : void 0,
4420
+ platform,
4421
+ userId: actorUserId,
4422
+ ...canUseInputProfile && cleanActorDisplayName(input?.userName, actorUserId) ? { userName: cleanActorDisplayName(input?.userName, actorUserId) } : void 0
4423
+ };
4424
+ if (platform === "slack") return {
4425
+ ...actor,
4426
+ platform,
4427
+ teamId: actorTeamId
4428
+ };
4429
+ return {
4430
+ ...actor,
4431
+ platform
4432
+ };
4433
+ }
4434
+ /** Build Junior's canonical actor from Slack profile data. */
4435
+ function createSlackActor(teamId, userId, profile) {
4436
+ const actorUserId = parseActorUserId(userId);
4437
+ const actorTeamId = parseSlackTeamId(teamId);
4438
+ if (!actorTeamId || !actorUserId) throw new Error("Slack actor requires team and user ids");
4439
+ const actor = createActor({
4440
+ email: profile?.email,
4441
+ fullName: profile?.fullName,
4442
+ platform: "slack",
4443
+ teamId: actorTeamId,
4444
+ userId: actorUserId,
4445
+ userName: profile?.userName
4446
+ }, {
4447
+ teamId: actorTeamId,
4448
+ userId: actorUserId
4449
+ });
4450
+ if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
4451
+ return actor;
4452
+ }
4453
+ /** Parse a serialized Slack actor that crossed a runtime boundary. */
4454
+ function parseStoredSlackActor(value) {
4455
+ const parsed = storedSlackActorSchema.safeParse(value);
4456
+ if (!parsed.success) return;
4457
+ if (parsed.data.slackUserId !== void 0 && !parseActorUserId(parsed.data.slackUserId)) return;
4458
+ if (parsed.data.teamId !== void 0 && !parseSlackTeamId(parsed.data.teamId)) return;
4459
+ if ((parsed.data.platform !== void 0 || parsed.data.teamId !== void 0) && (!parsed.data.platform || !parsed.data.teamId)) return;
4460
+ return parsed.data;
4461
+ }
4462
+ /** Convert a runtime Slack actor into its durable session shape. */
4463
+ function toStoredSlackActor(actor) {
4464
+ return {
4465
+ ...actor.email ? { email: actor.email } : void 0,
4466
+ ...actor.fullName ? { fullName: actor.fullName } : void 0,
4467
+ platform: actor.platform,
4468
+ slackUserId: actor.userId,
4469
+ ...actor.userName ? { slackUserName: actor.userName } : void 0,
4470
+ teamId: actor.teamId
4471
+ };
4472
+ }
4473
+ /**
4474
+ * Resolve a Slack resume actor from stored profile data and the active actor.
4475
+ *
4476
+ * TODO(dcramer): Require Actor and remove ID-only construction after no
4477
+ * deployed Turn cursor can omit Actor.
4478
+ */
4479
+ function createSlackResumeActor(args) {
4480
+ if (args.actor) {
4481
+ if (args.actor.platform !== "slack" || args.actor.teamId !== args.teamId || args.actor.userId !== args.userId) throw new Error("Stored Slack actor did not match resume actor");
4482
+ }
4483
+ const actor = createActor(args.actor, {
4484
+ platform: "slack",
4485
+ teamId: args.teamId,
4486
+ userId: args.userId
4487
+ });
4488
+ if (!actor || actor.platform !== "slack") throw new Error("Slack actor requires team and user ids");
4489
+ return actor;
4490
+ }
2792
4491
  // src/chat/conversations/sql/event-actor.ts
2793
4492
  const authorMetaSchema = z.object({ author: z.object({
2794
4493
  email: z.string().optional().catch(void 0),
@@ -2965,13 +4664,18 @@ function conversationDescendants(tree, conversationId) {
2965
4664
  }
2966
4665
  return descendants;
2967
4666
  }
2968
- /** Set or clear the shared archive of the given Conversations. */
2969
- async function setArchivedAt(db, conversationIds, archivedAt) {
2970
- if (conversationIds.length === 0) return;
2971
- await db.update(juniorConversations).set({
4667
+ /**
4668
+ * Set or clear the shared archive and count the rows written. This is the
4669
+ * only write of `archived_at`. `conversations` names the rows by id or by a
4670
+ * condition. `guard` is a condition that each row must still meet when it is
4671
+ * written, so a stale read loses to a newer change.
4672
+ */
4673
+ async function setArchivedAt(db, conversations, archivedAt, guard) {
4674
+ if (!(conversations instanceof SQL) && conversations.length === 0) return 0;
4675
+ return (await db.update(juniorConversations).set({
2972
4676
  archivedAt,
2973
4677
  detailVersion: nextDetailVersion
2974
- }).where(inArray(juniorConversations.conversationId, [...conversationIds]));
4678
+ }).where(and(conversations instanceof SQL ? conversations : inArray(juniorConversations.conversationId, [...conversations]), guard)).returning({ conversationId: juniorConversations.conversationId })).length;
2975
4679
  }
2976
4680
  /**
2977
4681
  * Restore one archived Conversation and its archived ancestors, so it shows
@@ -3538,6 +5242,497 @@ var SqlConversationMessageSearchStore = class {
3538
5242
  function createSqlConversationMessageSearchStore(executor) {
3539
5243
  return new SqlConversationMessageSearchStore(executor);
3540
5244
  }
5245
+ // src/db/info-messages.ts
5246
+ /**
5247
+ * Send Postgres `INFO` messages from every pool connection to `onInfo`.
5248
+ * A migration uses `RAISE INFO` to report its result to the operator.
5249
+ * Postgres always sends `INFO` to the client. Its own messages, such as
5250
+ * "already exists, skipping", are `NOTICE`, so they stay out.
5251
+ */
5252
+ function forwardInfoMessages(pool, onInfo) {
5253
+ pool.on("connect", (client) => {
5254
+ client.on("notice", (notice) => {
5255
+ if (notice.severity === "INFO" && notice.message) onInfo(notice.message);
5256
+ });
5257
+ });
5258
+ }
5259
+ // src/db/postgres-error.ts
5260
+ const MAX_CAUSE_DEPTH = 5;
5261
+ /**
5262
+ * Return whether a PostgreSQL failure, or an error that it wraps as `cause`,
5263
+ * has the requested SQLSTATE.
5264
+ */
5265
+ function isPostgresErrorCode(error, code) {
5266
+ let current = error;
5267
+ for (let depth = 0; depth < MAX_CAUSE_DEPTH && typeof current === "object" && current !== null; depth += 1) {
5268
+ if ("code" in current && current.code === code) return true;
5269
+ current = "cause" in current ? current.cause : void 0;
5270
+ }
5271
+ return false;
5272
+ }
5273
+ // src/db/migrate.ts
5274
+ const LOCK_TIMEOUT_MS = 5e3;
5275
+ const LOCK_ATTEMPTS = 5;
5276
+ const LOCK_RETRY_DELAY_MS = 5e3;
5277
+ const LOCK_NOT_AVAILABLE = "55P03";
5278
+ const MIGRATION_LOCK_POLL_MS = 1e3;
5279
+ const CONCURRENT_STATEMENT = /^(?:CREATE (?:UNIQUE )?INDEX|DROP INDEX|REINDEX)\b[^;]*\bCONCURRENTLY\b/i;
5280
+ const CONCURRENT_INDEX = /^CREATE (?:UNIQUE )?INDEX CONCURRENTLY IF NOT EXISTS "([a-z0-9_]+)" /i;
5281
+ /** Statement text without its leading comment lines. */
5282
+ function sqlOf(statement) {
5283
+ return statement.split("\n").filter((line) => !line.trim().startsWith("--")).join("\n").trim();
5284
+ }
5285
+ /**
5286
+ * Index builds of a migration that only builds indexes concurrently, or
5287
+ * undefined for a migration that runs in a transaction.
5288
+ */
5289
+ function concurrentIndexes(tag, statements) {
5290
+ const sql = statements.map(sqlOf).filter(Boolean);
5291
+ if (!sql.some((statement) => CONCURRENT_STATEMENT.test(statement))) return;
5292
+ return sql.map((statement) => {
5293
+ const name = CONCURRENT_INDEX.exec(statement)?.[1];
5294
+ if (!name) throw new Error(`Migration ${tag}: a migration that uses CONCURRENTLY must contain only CREATE [UNIQUE] INDEX CONCURRENTLY IF NOT EXISTS "name" statements.`);
5295
+ return {
5296
+ name,
5297
+ statement
5298
+ };
5299
+ });
5300
+ }
5301
+ /**
5302
+ * Wait for the migration lock by polling `pg_try_advisory_lock`. A session
5303
+ * blocked in `pg_advisory_lock` holds a snapshot, and `CREATE INDEX
5304
+ * CONCURRENTLY` waits for every older snapshot, so a second migrator that
5305
+ * blocked there would deadlock with the build of the first.
5306
+ */
5307
+ async function waitForMigrationLock(tryLock) {
5308
+ while (!await tryLock()) await new Promise((resolve) => setTimeout(resolve, MIGRATION_LOCK_POLL_MS));
5309
+ }
5310
+ async function retryOnLockTimeout(tag, apply) {
5311
+ for (let attempt = 1;; attempt += 1) try {
5312
+ await apply();
5313
+ return;
5314
+ } catch (error) {
5315
+ if (attempt >= LOCK_ATTEMPTS || !isPostgresErrorCode(error, LOCK_NOT_AVAILABLE)) throw error;
5316
+ logWarn("db.migration.lock_timeout", {
5317
+ "app.db.migration.tag": tag,
5318
+ "app.db.migration.attempt": attempt
5319
+ });
5320
+ await new Promise((resolve) => setTimeout(resolve, LOCK_RETRY_DELAY_MS));
5321
+ }
5322
+ }
5323
+ /**
5324
+ * Apply pending Drizzle migrations, each in its own transaction.
5325
+ *
5326
+ * Drizzle's `migrate()` runs every pending migration in one transaction
5327
+ * (drizzle-orm#3249), so locks from earlier migrations stay held while later
5328
+ * migrations wait for theirs. That can deadlock with live traffic. This keeps
5329
+ * Drizzle's journal table and skip rule, so existing databases are unaffected.
5330
+ * A migration that waits too long for a lock rolls back and runs again. A
5331
+ * migration that only builds indexes concurrently runs outside a transaction.
5332
+ */
5333
+ async function applyMigrations(executor, config) {
5334
+ const schema = config.migrationsSchema ?? "drizzle";
5335
+ const table = `"${schema}"."${config.migrationsTable ?? "__drizzle_migrations"}"`;
5336
+ await executor.execute(`CREATE SCHEMA IF NOT EXISTS "${schema}"`);
5337
+ await executor.execute(`CREATE TABLE IF NOT EXISTS ${table} (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint)`);
5338
+ const [last] = await executor.query(`SELECT created_at::text AS "createdAt" FROM ${table} ORDER BY created_at DESC LIMIT 1`);
5339
+ const appliedAt = Number(last?.createdAt ?? 0);
5340
+ for (const migration of readMigrationFiles(config)) {
5341
+ if (migration.folderMillis <= appliedAt) continue;
5342
+ const tag = String(migration.folderMillis);
5343
+ const recordApplied = () => executor.execute(`INSERT INTO ${table} (hash, created_at) VALUES ($1, $2)`, [migration.hash, migration.folderMillis]);
5344
+ const indexes = concurrentIndexes(tag, migration.sql);
5345
+ if (indexes) {
5346
+ for (const { name, statement } of indexes) {
5347
+ const [state] = await executor.query(`SELECT indisvalid AND indisready AS usable FROM pg_index WHERE indexrelid = to_regclass($1)`, [name]);
5348
+ if (state && !state.usable) await executor.execute(`DROP INDEX CONCURRENTLY IF EXISTS "${name}"`);
5349
+ await executor.execute(statement);
5350
+ }
5351
+ await recordApplied();
5352
+ continue;
5353
+ }
5354
+ await retryOnLockTimeout(tag, async () => {
5355
+ await executor.transaction(async () => {
5356
+ await executor.execute(`SET LOCAL lock_timeout = ${LOCK_TIMEOUT_MS}`);
5357
+ for (const statement of migration.sql) await executor.execute(statement);
5358
+ await recordApplied();
5359
+ });
5360
+ });
5361
+ }
5362
+ }
5363
+ // src/db/neon.ts
5364
+ const POOL_MAX = 10;
5365
+ function toWebSocketError(error, failure) {
5366
+ if (error instanceof Error) return error;
5367
+ const event = error ?? {};
5368
+ const cause = event.error instanceof Error ? event.error : void 0;
5369
+ const reason = typeof event.message === "string" && event.message || cause?.message || cause && `${cause.name} (no message)` || typeof event.type === "string" && event.type || String(error);
5370
+ return new Error(`WebSocket ${failure}: ${reason}`, event.error === void 0 ? void 0 : { cause: event.error });
5371
+ }
5372
+ function warnWebSocketFailure(name, error, failure) {
5373
+ const reported = toWebSocketError(error, failure);
5374
+ logWarn(name, {
5375
+ "app.db.driver": "neon",
5376
+ "error.type": reported.name,
5377
+ "exception.message": reported.message
5378
+ });
5379
+ }
5380
+ /**
5381
+ * Sends a pool query over Neon's SQL-over-HTTP endpoint when no idle
5382
+ * WebSocket client is free.
5383
+ *
5384
+ * pg-pool reuses the newest idle client, so light polling keeps one or two
5385
+ * clients warm and the rest idle out. A parallel read batch then opens about
5386
+ * eight WebSockets, each with a new Postgres session. An HTTP query reuses the
5387
+ * proxy's cached backend connection, so the batch skips that handshake. The
5388
+ * warm path stays on WebSocket. `connect()` and transactions are unchanged.
5389
+ */
5390
+ var OverflowPool = class extends Pool$1 {
5391
+ pendingAcquires = 0;
5392
+ webSocketOnly = new AsyncLocalStorage();
5393
+ sql;
5394
+ dispatcher;
5395
+ statementTimeoutMs;
5396
+ constructor(args) {
5397
+ super({
5398
+ connectionString: args.connectionString,
5399
+ max: POOL_MAX,
5400
+ idleTimeoutMillis: 3e5,
5401
+ min: 1,
5402
+ statement_timeout: args.statementTimeoutMs
5403
+ });
5404
+ this.sql = neon(args.connectionString, { fullResults: true });
5405
+ this.dispatcher = args.dispatcher;
5406
+ this.statementTimeoutMs = args.statementTimeoutMs;
5407
+ this.on("remove", () => this.reconnectWhenEmpty());
5408
+ }
5409
+ query(input, values, callback) {
5410
+ const query = typeof input === "string" ? { text: input } : input;
5411
+ if (callback !== void 0 || typeof values === "function" || typeof query?.text !== "string" || "submit" in query) return super.query(input, values, callback);
5412
+ const params = values ?? query.values ?? [];
5413
+ if (this.webSocketOnly.getStore() || this.idleCount > this.pendingAcquires || this.totalCount === 0) return this.queryWebSocket(query, params);
5414
+ this.growInBackground();
5415
+ return this.queryHttp(query, params);
5416
+ }
5417
+ growInBackground() {
5418
+ setImmediate(() => {
5419
+ if (this.ending || this.idleCount > 0 || this.totalCount >= POOL_MAX) return;
5420
+ this.openClient();
5421
+ });
5422
+ }
5423
+ reconnectWhenEmpty() {
5424
+ setImmediate(() => {
5425
+ if (this.ending || this.totalCount > 0) return;
5426
+ this.openClient();
5427
+ });
5428
+ }
5429
+ openClient() {
5430
+ this.connect((error, client) => {
5431
+ if (client) {
5432
+ client.release();
5433
+ return;
5434
+ }
5435
+ warnWebSocketFailure("db.pool.client.connect_failed", error, "connect failed");
5436
+ });
5437
+ }
5438
+ /** Keep every pool query in `callback` on WebSocket. */
5439
+ async onWebSocket(callback) {
5440
+ return await this.webSocketOnly.run(true, callback);
5441
+ }
5442
+ async queryWebSocket(query, params) {
5443
+ const client = await this.acquire();
5444
+ try {
5445
+ const result = await client.query({
5446
+ ...query,
5447
+ values: params
5448
+ });
5449
+ client.release();
5450
+ return result;
5451
+ } catch (error) {
5452
+ client.release(error);
5453
+ throw error;
5454
+ }
5455
+ }
5456
+ acquire() {
5457
+ this.pendingAcquires++;
5458
+ return new Promise((resolve, reject) => {
5459
+ this.connect((error, client) => {
5460
+ this.pendingAcquires--;
5461
+ if (client) resolve(client);
5462
+ else reject(error ?? /* @__PURE__ */ new Error("pg pool returned no client"));
5463
+ });
5464
+ });
5465
+ }
5466
+ async queryHttp(query, params) {
5467
+ const fetchOptions = { dispatcher: this.dispatcher };
5468
+ if (this.statementTimeoutMs) fetchOptions.signal = AbortSignal.timeout(this.statementTimeoutMs);
5469
+ return await withScope(async (scope) => {
5470
+ scope.setAttributes({ "app.db.transport": "http" });
5471
+ return await this.sql.query(query.text, params, {
5472
+ arrayMode: query.rowMode === "array",
5473
+ fullResults: true,
5474
+ types: query.types ?? this.options.types,
5475
+ fetchOptions
5476
+ });
5477
+ });
5478
+ }
5479
+ };
5480
+ var NeonExecutor = class {
5481
+ transactionClient = new AsyncLocalStorage();
5482
+ savepointId = 0;
5483
+ isolatedQueryId = 0;
5484
+ pool;
5485
+ dispatcher;
5486
+ constructor(pool, dispatcher) {
5487
+ this.pool = pool;
5488
+ this.dispatcher = dispatcher;
5489
+ }
5490
+ db() {
5491
+ return drizzle(this.queryClient(), { schema: juniorSqlSchema });
5492
+ }
5493
+ async execute(statement, params = []) {
5494
+ await this.queryClient().query(statement, [...params]);
5495
+ }
5496
+ async query(statement, params = []) {
5497
+ return (await this.queryClient().query(statement, [...params])).rows;
5498
+ }
5499
+ async queryIsolated(statement, params = []) {
5500
+ const client = await this.pool.connect();
5501
+ try {
5502
+ return (await client.query({
5503
+ name: `junior_isolated_${++this.isolatedQueryId}`,
5504
+ text: statement,
5505
+ values: [...params]
5506
+ })).rows;
5507
+ } finally {
5508
+ client.release(true);
5509
+ }
5510
+ }
5511
+ async migrate(config) {
5512
+ await applyMigrations(this, config);
5513
+ }
5514
+ async transaction(callback) {
5515
+ const existingClient = this.transactionClient.getStore();
5516
+ if (existingClient) {
5517
+ const savepoint = `junior_savepoint_${++this.savepointId}`;
5518
+ await existingClient.query(`SAVEPOINT ${savepoint}`);
5519
+ try {
5520
+ const result = await callback();
5521
+ await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
5522
+ return result;
5523
+ } catch (error) {
5524
+ await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
5525
+ await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
5526
+ throw error;
5527
+ }
5528
+ }
5529
+ const client = await this.pool.connect();
5530
+ try {
5531
+ await client.query("BEGIN");
5532
+ const result = await this.transactionClient.run(client, callback);
5533
+ await client.query("COMMIT");
5534
+ return result;
5535
+ } catch (error) {
5536
+ await client.query("ROLLBACK");
5537
+ throw error;
5538
+ } finally {
5539
+ client.release();
5540
+ }
5541
+ }
5542
+ async withLock(lockName, callback) {
5543
+ if (!lockName) throw new Error("SQL lock name is required");
5544
+ const existingClient = this.transactionClient.getStore();
5545
+ if (existingClient) {
5546
+ await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
5547
+ return await callback();
5548
+ }
5549
+ const client = await this.pool.connect();
5550
+ try {
5551
+ await client.query("BEGIN");
5552
+ return await this.transactionClient.run(client, async () => {
5553
+ try {
5554
+ await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
5555
+ const result = await callback();
5556
+ await client.query("COMMIT");
5557
+ return result;
5558
+ } catch (error) {
5559
+ await client.query("ROLLBACK");
5560
+ throw error;
5561
+ }
5562
+ });
5563
+ } finally {
5564
+ client.release();
5565
+ }
5566
+ }
5567
+ async withMigrationLock(migrationTable, callback) {
5568
+ const client = await this.pool.connect();
5569
+ const lockName = `junior:migrate:${migrationTable}`;
5570
+ try {
5571
+ await waitForMigrationLock(async () => {
5572
+ return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
5573
+ });
5574
+ return await this.pool.onWebSocket(callback);
5575
+ } finally {
5576
+ client.release(true);
5577
+ }
5578
+ }
5579
+ async close() {
5580
+ await this.pool.end();
5581
+ await this.dispatcher.close();
5582
+ }
5583
+ queryClient() {
5584
+ return this.transactionClient.getStore() ?? this.pool;
5585
+ }
5586
+ };
5587
+ /** Create the shared Neon-backed Junior SQL executor. */
5588
+ function createNeonJuniorSqlExecutor(args) {
5589
+ const { onInfo, ...poolArgs } = args;
5590
+ const dispatcher = new Agent({ allowH2: true });
5591
+ const pool = new OverflowPool({
5592
+ ...poolArgs,
5593
+ dispatcher
5594
+ });
5595
+ pool.on("error", (error) => {
5596
+ warnWebSocketFailure("db.pool.client.failed", error, "idle client failed");
5597
+ });
5598
+ if (onInfo) forwardInfoMessages(pool, onInfo);
5599
+ return new NeonExecutor(pool, dispatcher);
5600
+ }
5601
+ // src/db/postgres.ts
5602
+ const { Pool } = pg;
5603
+ var PostgresExecutor = class {
5604
+ transactionClient = new AsyncLocalStorage();
5605
+ savepointId = 0;
5606
+ isolatedQueryId = 0;
5607
+ pool;
5608
+ constructor(pool) {
5609
+ this.pool = pool;
5610
+ }
5611
+ db() {
5612
+ return drizzle$1(this.queryClient(), { schema: juniorSqlSchema });
5613
+ }
5614
+ async execute(statement, params = []) {
5615
+ await this.queryClient().query(statement, [...params]);
5616
+ }
5617
+ async query(statement, params = []) {
5618
+ return (await this.queryClient().query(statement, [...params])).rows;
5619
+ }
5620
+ async queryIsolated(statement, params = []) {
5621
+ const client = await this.pool.connect();
5622
+ try {
5623
+ return (await client.query({
5624
+ name: `junior_isolated_${++this.isolatedQueryId}`,
5625
+ text: statement,
5626
+ values: [...params]
5627
+ })).rows;
5628
+ } finally {
5629
+ client.release(true);
5630
+ }
5631
+ }
5632
+ async migrate(config) {
5633
+ await applyMigrations(this, config);
5634
+ }
5635
+ async transaction(callback) {
5636
+ const existingClient = this.transactionClient.getStore();
5637
+ if (existingClient) {
5638
+ const savepoint = `junior_savepoint_${++this.savepointId}`;
5639
+ await existingClient.query(`SAVEPOINT ${savepoint}`);
5640
+ try {
5641
+ const result = await callback();
5642
+ await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
5643
+ return result;
5644
+ } catch (error) {
5645
+ await existingClient.query(`ROLLBACK TO SAVEPOINT ${savepoint}`);
5646
+ await existingClient.query(`RELEASE SAVEPOINT ${savepoint}`);
5647
+ throw error;
5648
+ }
5649
+ }
5650
+ const client = await this.pool.connect();
5651
+ try {
5652
+ await client.query("BEGIN");
5653
+ const result = await this.transactionClient.run(client, callback);
5654
+ await client.query("COMMIT");
5655
+ return result;
5656
+ } catch (error) {
5657
+ await client.query("ROLLBACK");
5658
+ throw error;
5659
+ } finally {
5660
+ client.release();
5661
+ }
5662
+ }
5663
+ async withLock(lockName, callback) {
5664
+ if (!lockName) throw new Error("SQL lock name is required");
5665
+ const existingClient = this.transactionClient.getStore();
5666
+ if (existingClient) {
5667
+ await existingClient.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
5668
+ return await callback();
5669
+ }
5670
+ const client = await this.pool.connect();
5671
+ try {
5672
+ await client.query("BEGIN");
5673
+ return await this.transactionClient.run(client, async () => {
5674
+ try {
5675
+ await client.query("SELECT pg_advisory_xact_lock(hashtext($1))", [lockName]);
5676
+ const result = await callback();
5677
+ await client.query("COMMIT");
5678
+ return result;
5679
+ } catch (error) {
5680
+ await client.query("ROLLBACK");
5681
+ throw error;
5682
+ }
5683
+ });
5684
+ } finally {
5685
+ client.release();
5686
+ }
5687
+ }
5688
+ async withMigrationLock(migrationTable, callback) {
5689
+ const client = await this.pool.connect();
5690
+ const lockName = `junior:migrate:${migrationTable}`;
5691
+ try {
5692
+ await waitForMigrationLock(async () => {
5693
+ return (await client.query("SELECT pg_try_advisory_lock(hashtext($1)) AS locked", [lockName])).rows[0]?.locked === true;
5694
+ });
5695
+ return await callback();
5696
+ } finally {
5697
+ client.release(true);
5698
+ }
5699
+ }
5700
+ async close() {
5701
+ await this.pool.end();
5702
+ }
5703
+ queryClient() {
5704
+ return this.transactionClient.getStore() ?? this.pool;
5705
+ }
5706
+ };
5707
+ /** Create the shared Node Postgres-backed Junior SQL executor. */
5708
+ function createPostgresJuniorSqlExecutor(args) {
5709
+ const pool = new Pool({
5710
+ application_name: args.applicationName,
5711
+ connectionString: args.connectionString,
5712
+ max: 3,
5713
+ statement_timeout: args.statementTimeoutMs
5714
+ });
5715
+ pool.on("error", (error) => {
5716
+ logException(error, "db.pool.client.failed", { "app.db.driver": "postgres" });
5717
+ });
5718
+ if (args.onInfo) forwardInfoMessages(pool, args.onInfo);
5719
+ return new PostgresExecutor(pool);
5720
+ }
5721
+ // src/db/executor.ts
5722
+ /** Create the SQL executor appropriate for the configured database URL. */
5723
+ function createJuniorSqlExecutor(args) {
5724
+ const statementTimeoutMs = args.statementTimeoutMs ?? 3e4;
5725
+ if (args.driver === "postgres") return createPostgresJuniorSqlExecutor({
5726
+ connectionString: args.connectionString,
5727
+ onInfo: args.onInfo,
5728
+ statementTimeoutMs
5729
+ });
5730
+ return createNeonJuniorSqlExecutor({
5731
+ connectionString: args.connectionString,
5732
+ onInfo: args.onInfo,
5733
+ statementTimeoutMs
5734
+ });
5735
+ }
3541
5736
  // src/chat/db.ts
3542
5737
  var db_exports = /* @__PURE__ */ __exportAll({
3543
5738
  closeDb: () => closeDb,
@@ -3606,4 +5801,4 @@ async function closeDb() {
3606
5801
  current = void 0;
3607
5802
  await previous?.db.close();
3608
5803
  }
3609
- export { conversationWaitsOnUserSql as $, resolveActorIdentityId as $t, isTopLevelKind as A, agentTurnTotalTokens as An, activeParticipantUserIds as At, claimProviderConversation as B, requireSlackDestination as Bn, readIdentityByIdFromSql as Bt, createSqlStore as C, conversationIsNotUnsubscribedRoot as Cn, isOnlyAssignee as Ct, hasConversationMetadata as D, viewerMarksFromParticipant as Dn, requireInboxItemAssignees as Dt, dispatchInstructionsInvokeSkills as E, rootVisibleToViewer as En, readInboxItemAgentScope as Et, turnBehavior as F, conversationDetailTouch as Fn, findUserByEmailFromSql as Ft, microUsdToUsd as G, hasUserPhoto as Gt, parseSessionSource as H, resolveViewerUser as Ht, watchRepeatsChildResults as I, nextDetailVersion as In, listAdminUsersFromSql as It, conversationRangeColumns as J, readAvatarFetch as Jt, usdToMicroUsd as K, identityAvatarUrl as Kt, locationFromRow as L, touchConversationDetail as Ln, readActorIdentity as Lt, postsRunNotices as M, hasAgentTurnUsage as Mn, resolveAssignee as Mt, promptModeTurnTools as N, resolveRootConversationId as Nn, resolveAssignees as Nt, isPersonInput as O, addAgentTurnUsage as On, requireInboxItemLinks as Ot, sourceLabel as P, rootConversationIsArchived as Pn, findUserByEmail as Pt, conversationTurnFailedSql as Q, SYSTEM_IDENTITY_ID as Qt, setFirstConversationLocation as R, createSlackDestination as Rn, readActorIdentityFromSql as Rt, userMessageQueries as S, conversationIsMemberRoot as Sn, isAutomationAlertItem as St, deliversFinalText as T, readMemberParticipants as Tn, itemNeedsUser as Tt, conversationCostOf as U, setUserAdminFromSql as Ut, getConversationIdByProviderConversation as V, sameDestination as Vn, readViewerAvatarUrl as Vt, microUsdSql as W, updateViewerDisplayName as Wt, conversationIsActiveSql as X, userAvatarUrlsFromIdentities as Xt, conversationUsageCostExpr as Y, readUserAvatarUrls as Yt, conversationStatusSql as Z, userAvatarUrlsFromJoinedPhotos as Zt, readConversationTrees as _, conversationAccessFromRows as _n, inboxItemOwnedByConversation as _t, getConversationStore as a, findUserByVerifiedEmails as an, AUTOMATION_INBOX_ITEM_KEY_PREFIX as at, loadConversationSlackTenantIds as b, readConversationAccessRows as bn, inboxItemReaderForUserInConversation as bt, hasAnnotationKey as c, recordGoogleSignIn as cn, canAgentChangeInboxItem as ct, eventFromRow as d, readCachedUserByEmail as dn, inboxItemAssignedTo as dt, saveActorAvatar as en, executionIsActive as et, copyMessageLinks as f, ToolInputError as fn, inboxItemForUser as ft, conversationDescendants as g, canReadConversation as gn, inboxItemNeedsUser as gt, conversationAncestors as h, canAddConversationMessages as hn, inboxItemNeedsSomeone as ht, getConversationMessageSearchStore as i, findSlackUserByPrimaryEmail as in, treeAwaitsAuthorization as it, personSourcePlatform as j, agentTurnUsageSchema as jn, automationCreatorUserId as jt, isPersonSource as k, agentTurnCostUsd as kn, EVERYONE_ASSIGNEE as kt, treeHasAnnotationKey as l, saveUserTimezone as ln, canReadInboxItem as lt, withConversationEventLock as m, canAccessConversation as mn, inboxItemNeedsInput as mt, db_exports as n, deleteProviderIdentityForUser as nn, conversationKindSql as nt, getDb as o, linkedSlackUser as on, PLUGIN_INBOX_ITEM_KEY_PREFIX as ot, deleteMessageLinks as p, isToolInputError as pn, inboxItemLinkedTo as pt, conversationAggregateColumns as q, parseAvatarUrl as qt, getConversationEventStore as r, findLinkedSlackUser as rn, awaitsAuthorizationFrom as rt, getSqlExecutor as s, readUserTimezone as sn, canActOnInboxItem as st, closeDb as t, deleteProviderIdentityForSlackUser as tn, conversationKindFromRow as tt, createSqlConversationEventStore as u, upsertLinkedIdentity as un, canUserReadInboxItem as ut, setArchivedAt as v, createConversationAccessReader as vn, inboxItemPlugin as vt, withConversationMutationLock as w, conversationPinnedForUser as wn, isPluginInboxItem as wt, lastMessageAtSql as x, readableSlackTeamId as xn, inboxItemVisibleTo as xt, conversationSlackTenantId as y, readConversationAccessFromSql as yn, inboxItemReaderForUser as yt, startLocationThread as z, parseDestination as zn, readIdentityById as zt };
5804
+ export { microUsdSql as $, juniorWorkspaceRepos as $n, MEMORY_SOURCE_PLATFORMS as $r, readIdentityByIdFromSql as $t, lastMessageAtSql as A, conversationAccessFromRows as An, juniorConversationEvents as Ar, inboxItemPlugin as At, personSourcePlatform as B, rootVisibleToViewer as Bn, juniorConversations as Br, requireInboxItemAssignees as Bt, createSlackActor as C, upsertLinkedIdentity as Cn, juniorConversationReadPositions as Cr, canUserReadInboxItem as Ct, parseActorUserId as D, canAccessConversation as Dn, juniorConversationEventEmbeddings as Dr, inboxItemNeedsInput as Dt, isUserActor as E, isToolInputError as En, juniorConversationEventLexemes as Er, inboxItemLinkedTo as Et, dispatchInstructionsInvokeSkills as F, conversationIdsWithParticipantUser as Fn, juniorCodeChanges as Fr, isAutomationAlertItem as Ft, watchRepeatsChildResults as G, agentTurnUsageSchema as Gn, juniorDestinations as Gr, resolveAssignee as Gt, promptModeTurnTools as H, addAgentTurnUsage as Hn, slackPersonPredicate as Hr, EVERYONE_ASSIGNEE as Ht, hasConversationMetadata as I, conversationIsMemberRoot as In, juniorCodeRepositories as Ir, isOnlyAssignee as It, startLocationThread as J, rootConversationIsArchived as Jn, juniorMemorySignals as Jr, findUserByEmailFromSql as Jt, locationFromRow as K, hasAgentTurnUsage as Kn, juniorMemoryEmbeddings as Kr, resolveAssignees as Kt, isPersonInput as L, conversationIsNotUnsubscribedRoot as Ln, juniorAttachmentUploads as Lr, isPluginInboxItem as Lt, createSqlStore as M, readConversationAccessFromSql as Mn, juniorConversationAnnotations as Mr, inboxItemReaderForUserInConversation as Mt, withConversationMutationLock as N, readConversationAccessRows as Nn, codeChangeSearchDocument as Nr, inboxItemTodo as Nt, parseStoredSlackActor as O, canAddConversationMessages as On, juniorConversationEmbeddings as Or, inboxItemNeedsUser as Ot, deliversFinalText as P, readableSlackTeamId as Pn, codeRepositorySearchDocument as Pr, inboxItemVisibleTo as Pt, conversationCostOf as Q, juniorSnapshots as Qn, MEMORY_SCOPES as Qr, readIdentityById as Qt, isPersonSource as R, conversationPinnedForUser as Rn, juniorAttachments as Rr, itemNeedsUser as Rt, createActor as S, slackMessageTsSchema as Si, saveUserTimezone as Sn, juniorAgentBindings as Sr, canReadInboxItem as St, isActorUserId as T, ToolInputError as Tn, juniorConversationBriefs as Tr, inboxItemForUser as Tt, sourceLabel as U, agentTurnCostUsd as Un, slackPersonSearchDocument as Ur, activeParticipantUserIds as Ut, postsRunNotices as V, viewerMarksFromParticipant as Vn, juniorIdentities as Vr, requireInboxItemLinks as Vt, turnBehavior as W, agentTurnTotalTokens as Wn, juniorUsers as Wr, automationCreatorUserId as Wt, getConversationIdByProviderConversation as X, nextDetailVersion as Xn, MEMORY_EMBEDDING_DIMENSIONS as Xr, readActorIdentity as Xt, claimProviderConversation as Y, conversationDetailTouch as Yn, memoryPrefixDocument as Yr, listAdminUsersFromSql as Yt, parseSessionSource as Z, touchConversationDetail as Zn, MEMORY_KINDS as Zr, readActorIdentityFromSql as Zt, conversationDescendants as _, slackChannelIdSchema as _i, findSlackUserByPrimaryEmail as _n, automationSearchDocument as _r, REPLY_NOTICE_KEY_PREFIX as _t, getDb as a, parseEmbeddingBatch as ai, identityAvatarUrl as an, todoSearchDocument as ar, conversationUsageCostExpr as at, conversationSlackTenantId as b, parseSlackMessageTs as bi, readUserTimezone as bn, juniorAutomationVersions as br, canActOnInboxItem as bt, isPostgresErrorCode as c, createSlackDestination as ci, readUserAvatarUrls as cn, juniorInboxSnoozes as cr, conversationTurnFailedSql as ct, createSqlConversationEventStore as d, sameDestination as di, SYSTEM_IDENTITY_ID as dn, juniorInboxItemAssignees as dr, conversationKindFromRow as dt, MEMORY_SUBJECT_TYPES as ei, readViewerAvatarUrl as en, juniorWorkspaces as er, microUsdToUsd as et, eventFromRow as f, parseSlackChannelId as fi, resolveActorIdentityId as fn, juniorInboxItemConversations as fr, conversationKindSql as ft, conversationAncestors as g, slackBotIdSchema as gi, findLinkedSlackUser as gn, automationFuzzyTitle as gr, PLUGIN_INBOX_ITEM_KEY_PREFIX as gt, withConversationEventLock as h, parseSlackUserId as hi, deleteProviderIdentityForUser as hn, juniorInboxItems as hr, AUTOMATION_INBOX_ITEM_KEY_PREFIX as ht, getConversationStore as i, guardedCosineDistance as ii, hasUserPhoto as in, todoFuzzyTitle as ir, conversationRangeColumns as it, userMessageQueries as j, createConversationAccessReader as jn, juniorApiTokens as jr, inboxItemReaderForUser as jt, toStoredSlackActor as k, canReadConversation as kn, juniorConversationMetrics as kr, inboxItemOwnedByConversation as kt, hasAnnotationKey as l, parseDestination as li, userAvatarUrlsFromIdentities as ln, inboxItemFuzzyTitle as lr, conversationWaitsOnUserSql as lt, deleteMessageLinks as m, parseSlackTeamId as mi, deleteProviderIdentityForSlackUser as mn, juniorInboxItemSlackCards as mr, treeAwaitsAuthorization as mt, getConversationEventStore as n, cosineDistance as ni, setUserAdminFromSql as nn, juniorTodoVersionSeq as nr, usdToMicroUsdUnbiased as nt, getSqlExecutor as o, refreshEmbeddings as oi, parseAvatarUrl as on, juniorStats as or, conversationIsActiveSql as ot, copyMessageLinks as p, parseSlackChannelReferenceId as pi, saveActorAvatar as pn, juniorInboxItemDeliveries as pr, awaitsAuthorizationFrom as pt, setFirstConversationLocation as q, resolveRootConversationId as qn, juniorMemoryMemories as qr, findUserByEmail as qt, getConversationMessageSearchStore as r, embedText as ri, updateViewerDisplayName as rn, juniorTodos as rr, conversationAggregateColumns as rt, createJuniorSqlExecutor as s, juniorArtifacts as si, readAvatarFetch as sn, juniorInboxSnoozeTriggers as sr, conversationStatusSql as st, db_exports as t, memoryRuntimeContextSchema as ti, resolveViewerUser as tn, juniorPushSubscriptions as tr, usdToMicroUsd as tt, treeHasAnnotationKey as u, requireSlackDestination as ui, userAvatarUrlsFromJoinedPhotos as un, inboxItemSearchDocument as ur, executionIsActive as ut, readConversationTrees as v, slackTeamIdSchema as vi, findUserByVerifiedEmails as vn, juniorAutomations as vr, RESERVED_INBOX_ITEM_KEY_PREFIXES as vt, createSlackResumeActor as w, readCachedUserByEmail as wn, juniorConversationParticipants as wr, inboxItemAssignedTo as wt, loadConversationSlackTenantIds as x, slackMessageTsFromMs as xi, recordGoogleSignIn as xn, juniorLocationConfigurations as xr, canAgentChangeInboxItem as xt, setArchivedAt as y, slackUserIdSchema as yi, linkedSlackUser as yn, juniorAutomationRuns as yr, TODO_INBOX_ITEM_KEY_PREFIX as yt, isTopLevelKind as z, readMemberParticipants as zn, juniorMessageAttachments as zr, readInboxItemAgentScope as zt };