@sentry/junior 0.309.0 → 0.311.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 (117) hide show
  1. package/dist/adapter-B1wujchl.js +259 -0
  2. package/dist/{adapter-context-1YUbMpD3.js → adapter-context-G2M0y6rP.js} +2 -2
  3. package/dist/{admin-u30A8TcD.js → admin-DCiBhUT1.js} +1 -2
  4. package/dist/{agent-runner-sJLhgPQV.js → agent-runner-BVHPUIc8.js} +695 -1817
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +8 -7
  7. package/dist/api.d.ts +21 -3
  8. package/dist/api.js +1479 -372
  9. package/dist/{app-B_7Wn0en.d.ts → app-Cw5Vy6H6.d.ts} +14 -3
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +233 -506
  12. package/dist/{background-compaction-queue-CUJXVKG3.js → background-compaction-queue-CJDnWVOJ.js} +4 -4
  13. package/dist/{briefs-BHi70IR5.js → briefs-BDjnug6Y.js} +3 -3
  14. package/dist/{catalog-runtime-Chc_IP2o.js → catalog-runtime-DMY3VV-D.js} +1 -1
  15. package/dist/cli/chat.js +16 -16
  16. package/dist/cli/check.js +23 -29
  17. package/dist/cli/init.js +1 -6
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +8 -7
  20. package/dist/cli/snapshot-create.js +5 -5
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-BIyIdTtA.js → config-BrXDQefC.js} +239 -5
  24. package/dist/{continue-in-slack-BQJBfiQh.js → continue-in-slack-DNXSC9So.js} +6 -5
  25. package/dist/{conversation-CzrLhdHG.js → conversation-ca__NDQW.js} +48 -9
  26. package/dist/{conversation-feed-B9e3_gxz.js → conversation-feed-DkinDu5o.js} +15 -6
  27. package/dist/{conversation-privacy-CkTW29hd.js → conversation-privacy-DxttrKb9.js} +1 -1
  28. package/dist/{conversation-turn-CZaYQUum.js → conversation-turn-DWw7Xhdr.js} +42 -39
  29. package/dist/{credential-sync-58m_CyIJ.js → credential-sync-Bk8wGb8Y.js} +15 -16
  30. package/dist/{db-B4Hjxr-u.d.ts → db-7ETESH44.d.ts} +3 -1
  31. package/dist/{db-CFUpEZi9.js → db-DTxzH7u5.js} +1618 -1041
  32. package/dist/{executor-DXL0O0MV.js → executor-DqTiYj9S.js} +454 -96
  33. package/dist/{history-N7IVbUom.js → history-CYstOMKX.js} +6 -0
  34. package/dist/{html-CaBu2VbT.js → html-B9Sl4Axb.js} +6 -6
  35. package/dist/{install-DhTBUUov.js → install-Sg4ePfLl.js} +2 -2
  36. package/dist/instrumentation.js +3 -3
  37. package/dist/{lineage-CxtOI2_p.js → lineage-BHAMpNKr.js} +2 -2
  38. package/dist/{logging-BNUovdcX.js → logging-FjclQsXu.js} +47 -9
  39. package/dist/{message-DcUsS2vg.js → message-CJ7_RL50.js} +5 -8
  40. package/dist/{model-input-o3rEqgwM.js → model-input-CMLh4Cwq.js} +3 -3
  41. package/dist/nitro.d.ts +1 -1
  42. package/dist/nitro.js +3 -3
  43. package/dist/{oauth-callback-server-1Fizd1EM.js → oauth-callback-server-RVcbiDjL.js} +2 -2
  44. package/dist/{oauth-relay-DOwngqdM.js → oauth-relay-Bu9kkaQu.js} +1 -1
  45. package/dist/{projection-Ce4pmhKP.js → projection-Cns7XwWa.js} +9206 -5318
  46. package/dist/{prompt-DEqjDVMs.js → prompt-CDqcsDYC.js} +4 -4
  47. package/dist/{registry-CNE4ZBnG.js → registry-BPwuOP2O.js} +5 -8
  48. package/dist/{resolve-qbPg-aC-.js → resolve-BK29bBry.js} +3 -3
  49. package/dist/rule-DAxQY-1h.js +20 -0
  50. package/dist/{runner-eGIxpAMf.js → runner-BcAE-cJm.js} +10 -10
  51. package/dist/{sandbox-egress-signals-DMFB1kCp.js → sandbox-egress-signals-C-q0go5b.js} +1 -1
  52. package/dist/{schedule-Cire6NU7.js → schedule-BLJ476XQ.js} +209 -43
  53. package/dist/{schema-CfIey9Ao.js → schema-BLgSZXcL.js} +255 -49
  54. package/dist/{schema-DriSvB40.d.ts → schema-DYcJeV7d.d.ts} +701 -62
  55. package/dist/{service-account-Cw_LWZ4-.js → service-account-gN0zqf0S.js} +68 -68
  56. package/dist/{service-account-B1VXCTqg.js → service-account-iJoCtkHR.js} +3 -3
  57. package/dist/{skills-Zg8-vrje.js → skills-BoZ80epJ.js} +77 -31
  58. package/dist/{slack-conversation-unfurl-DA51qH0c.js → slack-conversation-unfurl-CogYrITA.js} +8 -10
  59. package/dist/{spawn-DBi4-zD8.js → spawn-Dk92r7mX.js} +5 -6
  60. package/dist/{state-C-Ftk23K.js → state-DH3Cmgp3.js} +4 -4
  61. package/dist/{stop-D9xideLM.js → stop-CYsfc0Ed.js} +1064 -314
  62. package/dist/{store-BjIXA0Al.js → store-DmmMIrQi.js} +5 -5
  63. package/dist/{task-queue-D0_qbnpo.js → task-queue-C_zldF5J.js} +3 -3
  64. package/dist/{task-runner-DQMq4XY0.js → task-runner-C7oCJQIx.js} +21 -14
  65. package/dist/{thread-context-D0i1e-5O.js → thread-context-BW2BsQbH.js} +13 -11
  66. package/dist/{turn-session-routing-C0l68I_O.js → turn-session-routing-Xh_2nSQe.js} +52 -54
  67. package/dist/{validation-CRbvRPvu.js → validation-DrJd0nnq.js} +1 -1
  68. package/dist/{version-BYdVs12p.js → version-CNKZ8owc.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{warmup-DN9OHN1-.js → warmup-BWdHew2H.js} +14289 -7197
  71. package/dist/{web-message-id-BT8Mg8LL.js → web-message-id-Ch5dPq-a.js} +32 -144
  72. package/dist/{worker-C9ZfJXmV.js → worker-t9qpu_Zx.js} +7 -8
  73. package/migrations/0124_artifact_visibility.sql +9 -0
  74. package/migrations/0125_artifact_public_sha_index.sql +1 -0
  75. package/migrations/0126_artifact_drop_public.sql +8 -0
  76. package/migrations/0127_artifact_path.sql +4 -0
  77. package/migrations/0128_artifact_path_index.sql +1 -0
  78. package/migrations/0129_review_item_answered_index.sql +1 -0
  79. package/migrations/0130_review_item_status_index.sql +1 -0
  80. package/migrations/0131_brief_outcome_status.sql +1 -0
  81. package/migrations/0132_brief_outcome_status_backfill.sql +7 -0
  82. package/migrations/0133_brief_created_at_index.sql +1 -0
  83. package/migrations/0134_slack_person_search_index.sql +1 -0
  84. package/migrations/0135_code_change_size.sql +3 -0
  85. package/migrations/0136_merge_conflict_notice_dismiss.sql +16 -0
  86. package/migrations/0137_inbox_snoozes.sql +27 -0
  87. package/migrations/0138_code_change_search_index.sql +2 -0
  88. package/migrations/0139_review_item_owner.sql +22 -0
  89. package/migrations/0140_review_item_owner_index.sql +1 -0
  90. package/migrations/0141_memory_core_adoption.sql +89 -0
  91. package/migrations/0142_memory_core_indexes.sql +17 -0
  92. package/migrations/meta/0124_snapshot.json +5516 -0
  93. package/migrations/meta/0125_snapshot.json +5516 -0
  94. package/migrations/meta/0126_snapshot.json +5488 -0
  95. package/migrations/meta/0127_snapshot.json +5519 -0
  96. package/migrations/meta/0128_snapshot.json +5519 -0
  97. package/migrations/meta/0129_snapshot.json +5547 -0
  98. package/migrations/meta/0130_snapshot.json +5563 -0
  99. package/migrations/meta/0131_snapshot.json +5569 -0
  100. package/migrations/meta/0132_snapshot.json +5569 -0
  101. package/migrations/meta/0133_snapshot.json +5590 -0
  102. package/migrations/meta/0134_snapshot.json +5606 -0
  103. package/migrations/meta/0135_snapshot.json +5624 -0
  104. package/migrations/meta/0136_snapshot.json +5624 -0
  105. package/migrations/meta/0137_snapshot.json +5864 -0
  106. package/migrations/meta/0138_snapshot.json +5894 -0
  107. package/migrations/meta/0139_snapshot.json +5898 -0
  108. package/migrations/meta/0140_snapshot.json +5919 -0
  109. package/migrations/meta/0141_snapshot.json +6429 -0
  110. package/migrations/meta/0142_snapshot.json +6457 -0
  111. package/migrations/meta/_journal.json +134 -1
  112. package/package.json +6 -7
  113. package/dist/result-ZGnDzcsb.js +0 -548
  114. package/dist/session-stop-P2XdTiwr.js +0 -4252
  115. package/dist/turn-user-message-nBVvOXjs.js +0 -364
  116. package/dist/users-DdjMjbmM.js +0 -181
  117. package/dist/viewer-DudYrQGj.js +0 -212
@@ -1,10 +1,11 @@
1
- import { h as logWarn, p as logException } from "./logging-BNUovdcX.js";
1
+ import { h as logWarn, p as logException } from "./logging-FjclQsXu.js";
2
2
  import { _ as withScope } from "./sentry-CPbZjomA.js";
3
- import "./config-BIyIdTtA.js";
3
+ import "./config-BrXDQefC.js";
4
+ import * as z from "zod";
4
5
  import { AsyncLocalStorage } from "node:async_hooks";
6
+ import { actorSchema, sourceSchema } from "@sentry/junior-plugin-api";
5
7
  import { sql } from "drizzle-orm";
6
8
  import { bigint, boolean, check, customType, date, doublePrecision, foreignKey, index, integer, jsonb, pgSequence, pgTable, primaryKey, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core";
7
- import { embeddingHalfvec, embeddingVector } from "@sentry/junior-plugin-api/embeddings";
8
9
  import { Pool as Pool$1, neon } from "@neondatabase/serverless";
9
10
  import { drizzle } from "drizzle-orm/neon-serverless";
10
11
  import { Agent } from "undici";
@@ -14,9 +15,9 @@ import { drizzle as drizzle$1 } from "drizzle-orm/node-postgres";
14
15
  // src/db/schema/timestamps.ts
15
16
  const timestamptz = (name) => timestamp(name, { withTimezone: true });
16
17
  // src/db/schema/artifacts.ts
17
- /** Durable metadata for conversation-owned public artifacts. */
18
+ /** Durable metadata for conversation-owned artifacts. */
18
19
  const juniorArtifacts = pgTable("junior_artifacts", {
19
- /** Public identity used in `/public/artifacts/<id>.<ext>`. */
20
+ /** Row identity. A public row serves at `/public/artifacts/<id>.<ext>`. */
20
21
  id: text("id").primaryKey(),
21
22
  conversationId: text("conversation_id").notNull(),
22
23
  sha256: text("sha256").notNull(),
@@ -24,15 +25,295 @@ const juniorArtifacts = pgTable("junior_artifacts", {
24
25
  storageKey: text("storage_key").notNull(),
25
26
  contentType: text("content_type").notNull(),
26
27
  bytes: integer("bytes").notNull(),
27
- public: boolean("public").notNull(),
28
+ /**
29
+ * Path under the Sandbox `artifacts/` directory for a live file. Null for
30
+ * a public frozen copy, such as a published image.
31
+ */
32
+ path: text("path"),
33
+ visibility: text("visibility").$type().notNull().default("conversation"),
28
34
  createdAt: timestamptz("created_at").notNull(),
29
- /** Set when the artifact should stop being served publicly. */
35
+ /** Set when the artifact is unpublished or its live file is deleted. */
30
36
  deleteRequestedAt: timestamptz("delete_requested_at")
31
37
  }, (table) => [
32
- uniqueIndex("junior_artifacts_conversation_sha_uidx").on(table.conversationId, table.sha256),
38
+ check("junior_artifacts_visibility_check", sql`${table.visibility} in ('conversation', 'internal', 'public')`),
39
+ check("junior_artifacts_path_visibility_check", sql`(${table.path} is null) = (${table.visibility} = 'public')`),
40
+ uniqueIndex("junior_artifacts_conversation_path_uidx").on(table.conversationId, table.path),
41
+ uniqueIndex("junior_artifacts_public_sha_uidx").on(table.conversationId, table.sha256).where(sql`${table.visibility} = 'public'`),
33
42
  index("junior_artifacts_gc_idx").on(table.deleteRequestedAt, table.createdAt),
34
43
  index("junior_artifacts_conversation_idx").on(table.conversationId)
35
44
  ]);
45
+ // src/db/embeddings.ts
46
+ /**
47
+ * Shared parts of the derived embedding indexes. Each owner keeps its own
48
+ * table, so a foreign key still deletes a vector with its source row. These
49
+ * helpers keep the column types, the distance SQL, the batch checks, and the
50
+ * backfill loop the same in every table.
51
+ */
52
+ function pgvectorColumn(dataType) {
53
+ return customType({
54
+ dataType() {
55
+ return dataType;
56
+ },
57
+ toDriver(value) {
58
+ return JSON.stringify(value);
59
+ },
60
+ fromDriver(value) {
61
+ return value.slice(1, -1).split(",").map(Number);
62
+ }
63
+ });
64
+ }
65
+ /**
66
+ * pgvector `vector` column without a fixed size, so a new embedding model
67
+ * needs no migration. Each table records the size of each row in its own
68
+ * column.
69
+ */
70
+ const embeddingVector = pgvectorColumn("vector");
71
+ /**
72
+ * Half-precision `embeddingVector`: 2 bytes per value instead of 4, for
73
+ * tables that hold many vectors.
74
+ */
75
+ const embeddingHalfvec = pgvectorColumn("halfvec");
76
+ const embeddingResultSchema = z.object({
77
+ costUsd: z.number().finite().nonnegative().optional(),
78
+ dimensions: z.number().int().positive(),
79
+ model: z.string().min(1),
80
+ provider: z.string().min(1),
81
+ vectors: z.array(z.array(z.number().finite()))
82
+ }).strict();
83
+ /**
84
+ * Validate an embedder result: one vector per text, all of the reported
85
+ * size. With `dimensions`, the size must be one that the table accepts. With
86
+ * `expected`, the result must come from that provider and model, because a
87
+ * backfill that finds rows by model would see a row of another model as
88
+ * missing on every run.
89
+ */
90
+ function parseEmbeddingBatch(raw, args) {
91
+ const result = embeddingResultSchema.parse(raw);
92
+ if (args.dimensions && !args.dimensions.includes(result.dimensions)) throw new Error("Unsupported embedding vector size.");
93
+ if (result.vectors.length !== args.textCount) throw new Error("Embedding provider returned an unexpected vector count.");
94
+ if (result.vectors.some((vector) => vector.length !== result.dimensions)) throw new Error("Embedding provider returned an unexpected vector size.");
95
+ 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}.`);
96
+ return {
97
+ dimensions: result.dimensions,
98
+ model: result.model,
99
+ provider: result.provider,
100
+ vectors: result.vectors
101
+ };
102
+ }
103
+ /** Embed one text with the embedder's model and return its vector. */
104
+ async function embedText(embedder, input) {
105
+ const batch = parseEmbeddingBatch(await embedder.embedTexts({
106
+ inputType: input.inputType,
107
+ texts: [input.text]
108
+ }), {
109
+ expected: embedder,
110
+ textCount: 1
111
+ });
112
+ return {
113
+ model: batch.model,
114
+ provider: batch.provider,
115
+ vector: batch.vectors[0]
116
+ };
117
+ }
118
+ function vectorSize(query) {
119
+ if (query.length === 0) throw new Error("Embedding vector is empty.");
120
+ return sql.raw(String(query.length));
121
+ }
122
+ /**
123
+ * Cosine distance from a stored vector to a query vector. Both sides are cast
124
+ * to the query size, the form that an HNSW expression index on that size
125
+ * matches. The cast fails on a stored vector of another size, so filter on the
126
+ * size first, as the index predicate does, or use `guardedCosineDistance`.
127
+ * A caller with another copy of drizzle-orm embeds the result in its own
128
+ * `sql` template to get its own `SQL` type.
129
+ */
130
+ function cosineDistance(args) {
131
+ const size = vectorSize(args.query);
132
+ const type = sql.raw(args.type);
133
+ return sql`(${args.column}::${type}(${size})) <=> ${JSON.stringify(args.query)}::${type}(${size})`;
134
+ }
135
+ /**
136
+ * `cosineDistance`, or null for a stored vector of another size. Postgres
137
+ * does not promise to check a WHERE term before it computes an ORDER BY or
138
+ * SELECT expression, and pgvector fails on vectors of two sizes. CASE fixes
139
+ * the order.
140
+ */
141
+ function guardedCosineDistance(args) {
142
+ return sql`CASE WHEN ${args.dimensions} = ${vectorSize(args.query)} THEN ${cosineDistance(args)} END`;
143
+ }
144
+ /**
145
+ * Embed items that have no current vector, one batch at a time, and store
146
+ * each batch before the next starts. `listMissing` returns the next items in
147
+ * the caller's order, after the last item of the previous page, so each run
148
+ * ends even when a write leaves an item missing. Text that trims to nothing
149
+ * is skipped, because the embedder rejects it. A provider failure stops the
150
+ * run and keeps the batches stored before it, so a later run continues.
151
+ */
152
+ async function refreshEmbeddings(args) {
153
+ const now = args.now ?? Date.now;
154
+ let after;
155
+ let embedded = 0;
156
+ for (;;) {
157
+ const remaining = (args.maxItems ?? 1e400) - embedded;
158
+ if (remaining <= 0 || args.deadlineMs !== void 0 && now() >= args.deadlineMs) return {
159
+ done: false,
160
+ embedded
161
+ };
162
+ const page = await args.listMissing({
163
+ after,
164
+ limit: Math.min(args.batchSize, remaining)
165
+ });
166
+ after = page.at(-1);
167
+ if (!after) return {
168
+ done: true,
169
+ embedded
170
+ };
171
+ const items = page.filter((item) => item.text.trim() !== "");
172
+ if (items.length === 0) continue;
173
+ const batch = parseEmbeddingBatch(await args.embedder.embedTexts({
174
+ inputType: "document",
175
+ texts: items.map((item) => item.text)
176
+ }), {
177
+ ...args.dimensions ? { dimensions: args.dimensions } : void 0,
178
+ expected: args.embedder,
179
+ textCount: items.length
180
+ });
181
+ await args.write(items.map((item, index) => ({
182
+ item,
183
+ vector: batch.vectors[index]
184
+ })), batch);
185
+ embedded += items.length;
186
+ }
187
+ }
188
+ // src/db/schema/tsvector.ts
189
+ /** Postgres full-text lexemes. Queries read them only through SQL. */
190
+ const tsvector = customType({ dataType() {
191
+ return "tsvector";
192
+ } });
193
+ // src/chat/memory/types.ts
194
+ const MEMORY_KINDS = [
195
+ "preference",
196
+ "procedure",
197
+ "knowledge"
198
+ ];
199
+ const MEMORY_SCOPES = ["private", "public"];
200
+ const MEMORY_SUBJECT_TYPES = [
201
+ "user",
202
+ "conversation",
203
+ "general"
204
+ ];
205
+ const MEMORY_SOURCE_PLATFORMS = [
206
+ "slack",
207
+ "local",
208
+ "web"
209
+ ];
210
+ const MEMORY_EMBEDDING_METRICS = ["cosine"];
211
+ /** Things that can happen to a stored memory and feed future recall weights. */
212
+ /** `contradicted` and `superseded` record why a memory was retired. */
213
+ const MEMORY_SIGNALS = [
214
+ "duplicate",
215
+ "contradicted",
216
+ "superseded"
217
+ ];
218
+ /**
219
+ * Vector sizes the embeddings table can store, so one table can hold vectors
220
+ * from an old and a new model while a model change is in progress. Only 1024
221
+ * has an HNSW index.
222
+ */
223
+ const MEMORY_EMBEDDING_DIMENSIONS = [1024, 1536];
224
+ const nonEmptyStringSchema = z.string().min(1);
225
+ /** Host data used to set memory access, subject, and source. */
226
+ const memoryRuntimeContextSchema = z.object({
227
+ conversationId: nonEmptyStringSchema.optional(),
228
+ locationId: nonEmptyStringSchema.optional(),
229
+ actor: actorSchema.optional(),
230
+ source: sourceSchema,
231
+ /** User linked to the active Actor. */
232
+ userId: nonEmptyStringSchema.optional()
233
+ }).strict();
234
+ // src/db/schema/memory.ts
235
+ const juniorMemoryMemories = pgTable("junior_memory_memories", {
236
+ id: text("id").primaryKey(),
237
+ scope: text("scope", { enum: MEMORY_SCOPES }).notNull(),
238
+ scopeKey: text("scope_key").notNull(),
239
+ kind: text("type", { enum: MEMORY_KINDS }).notNull(),
240
+ subjectType: text("subject_type", { enum: MEMORY_SUBJECT_TYPES }).notNull(),
241
+ subjectKey: text("subject_key"),
242
+ content: text("content").notNull(),
243
+ searchVector: tsvector("search_vector").generatedAlwaysAs(sql`to_tsvector('english', "content")`),
244
+ sourcePlatform: text("source_platform", { enum: MEMORY_SOURCE_PLATFORMS }).notNull(),
245
+ sourceKey: text("source_key").notNull(),
246
+ /** Location where Junior learned the memory, when known. */
247
+ locationId: text("location_id"),
248
+ /** Conversation where Junior learned the memory, when known. */
249
+ conversationId: text("conversation_id"),
250
+ idempotencyKey: text("idempotency_key"),
251
+ observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull(),
252
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
253
+ expiresAtMs: bigint("expires_at_ms", { mode: "number" }),
254
+ supersededAtMs: bigint("superseded_at_ms", { mode: "number" }),
255
+ supersededById: text("superseded_by_id"),
256
+ archivedAtMs: bigint("archived_at_ms", { mode: "number" }),
257
+ archiveReason: text("archive_reason")
258
+ }, (table) => [
259
+ 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`),
260
+ index("junior_memory_memories_expiration_idx").on(table.expiresAtMs).where(sql`${table.archivedAtMs} IS NULL AND ${table.expiresAtMs} IS NOT NULL`),
261
+ 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`),
262
+ 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`),
263
+ 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'`),
264
+ check("junior_memory_memories_scope_check", sql`${table.scope} IN ('private', 'public')`),
265
+ check("junior_memory_memories_kind_check", sql`${table.kind} IN (
266
+ 'preference',
267
+ 'procedure',
268
+ 'knowledge'
269
+ )`),
270
+ check("junior_memory_memories_subject_type_check", sql`${table.subjectType} IN ('user', 'conversation', 'general')`),
271
+ 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)`),
272
+ check("junior_memory_memories_source_platform_check", sql`${table.sourcePlatform} IN ('slack', 'local', 'web')`)
273
+ ]);
274
+ const juniorMemoryEmbeddings = pgTable("junior_memory_embeddings", {
275
+ memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
276
+ provider: text("provider").notNull(),
277
+ model: text("model").notNull(),
278
+ dimensions: integer("dimensions").notNull(),
279
+ metric: text("metric", { enum: MEMORY_EMBEDDING_METRICS }).notNull(),
280
+ contentHash: text("content_hash").notNull(),
281
+ embedding: embeddingVector("embedding").notNull(),
282
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull()
283
+ }, (table) => [
284
+ primaryKey({ columns: [
285
+ table.memoryId,
286
+ table.provider,
287
+ table.model
288
+ ] }),
289
+ index("junior_memory_embeddings_model_idx").on(table.provider, table.model, table.dimensions, table.metric),
290
+ index("junior_memory_embeddings_embedding_1024_hnsw_idx").using("hnsw", sql`(${table.embedding}::vector(1024)) vector_cosine_ops`).with({
291
+ m: 16,
292
+ ef_construction: 64
293
+ }).where(sql`${table.dimensions} = 1024`),
294
+ check("junior_memory_embeddings_metric_check", sql`${table.metric} IN ('cosine')`),
295
+ check("junior_memory_embeddings_dimensions_check", sql`${table.dimensions} IN (${sql.raw(MEMORY_EMBEDDING_DIMENSIONS.join(", "))}) AND vector_dims(${table.embedding}) = ${table.dimensions}`)
296
+ ]);
297
+ /**
298
+ * Thin log of signals about stored memories, such as a capture that resolved
299
+ * to an existing memory. Callers count recent rows to weigh memories.
300
+ */
301
+ const juniorMemorySignals = pgTable("junior_memory_signals", {
302
+ memoryId: text("memory_id").notNull().references(() => juniorMemoryMemories.id, { onDelete: "cascade" }),
303
+ signal: text("signal", { enum: MEMORY_SIGNALS }).notNull(),
304
+ idempotencyKey: text("idempotency_key").notNull(),
305
+ /** Conversation where Junior saw the signal, when known. */
306
+ conversationId: text("conversation_id"),
307
+ observedAtMs: bigint("observed_at_ms", { mode: "number" }).notNull()
308
+ }, (table) => [
309
+ primaryKey({ columns: [
310
+ table.memoryId,
311
+ table.signal,
312
+ table.idempotencyKey
313
+ ] }),
314
+ index("junior_memory_signals_observed_idx").on(table.memoryId, table.signal, table.observedAtMs),
315
+ check("junior_memory_signals_signal_check", sql`${table.signal} IN ('duplicate', 'contradicted', 'superseded')`)
316
+ ]);
36
317
  // src/db/schema/destinations.ts
37
318
  const juniorDestinations = pgTable("junior_destinations", {
38
319
  id: text("id").primaryKey(),
@@ -72,6 +353,17 @@ const juniorUsers = pgTable("junior_users", {
72
353
  updatedAt: timestamptz("updated_at").notNull()
73
354
  }, (table) => [uniqueIndex("junior_users_primary_email_normalized_uidx").on(table.primaryEmailNormalized)]);
74
355
  // src/db/schema/identities.ts
356
+ /** Words of a Slack person's name and handle, for prefix search. */
357
+ function slackPersonSearchDocument(table) {
358
+ return sql`to_tsvector('simple', coalesce(${table.displayName}, '') || ' ' || coalesce(${table.handle}, ''))`;
359
+ }
360
+ /**
361
+ * Slack people. Literal values, so a prepared query with this predicate
362
+ * can use the partial index.
363
+ */
364
+ function slackPersonPredicate(table) {
365
+ return sql`${table.provider} = 'slack' AND ${table.kind} = 'user'`;
366
+ }
75
367
  const juniorIdentities = pgTable("junior_identities", {
76
368
  id: text("id").primaryKey(),
77
369
  kind: text("kind").$type().notNull(),
@@ -93,7 +385,8 @@ const juniorIdentities = pgTable("junior_identities", {
93
385
  uniqueIndex("junior_identities_provider_subject_uidx").on(table.provider, table.providerTenantId, table.providerSubjectId),
94
386
  index("junior_identities_user_idx").on(table.userId),
95
387
  index("junior_identities_verified_email_idx").on(table.emailNormalized).where(sql`${table.emailVerified} = true AND ${table.emailNormalized} IS NOT NULL`),
96
- index("junior_identities_kind_provider_idx").on(table.kind, table.provider)
388
+ index("junior_identities_kind_provider_idx").on(table.kind, table.provider),
389
+ index("junior_identities_slack_person_search_idx").using("gin", slackPersonSearchDocument(table)).where(slackPersonPredicate(table))
97
390
  ]);
98
391
  // src/db/schema/conversations.ts
99
392
  const juniorConversations = pgTable("junior_conversations", {
@@ -248,6 +541,17 @@ const juniorAttachmentUploads = pgTable("junior_attachment_uploads", {
248
541
  createdAt: timestamptz("created_at").notNull()
249
542
  }, (table) => [index("junior_attachment_uploads_gc_idx").on(table.storageProvider, table.createdAt)]);
250
543
  // src/db/schema/code.ts
544
+ /**
545
+ * Words of a repository name, for prefix search. `owner/repo` is one token
546
+ * to the text parser, so the slash becomes a space.
547
+ */
548
+ function codeRepositorySearchDocument(table) {
549
+ return sql`to_tsvector('simple', translate(${table.name}, '/', ' '))`;
550
+ }
551
+ /** The number and the title words of a code change, for prefix search. */
552
+ function codeChangeSearchDocument(table) {
553
+ return sql`to_tsvector('simple', ${table.number}::text || ' ' || coalesce(${table.title}, ''))`;
554
+ }
251
555
  /** Repository known to Junior through an installed code plugin. */
252
556
  const juniorCodeRepositories = pgTable("junior_code_repositories", {
253
557
  id: uuid("id").primaryKey(),
@@ -256,12 +560,15 @@ const juniorCodeRepositories = pgTable("junior_code_repositories", {
256
560
  providerId: text("provider_id").notNull(),
257
561
  url: text("url"),
258
562
  updatedAt: timestamptz("updated_at").notNull()
259
- }, (table) => [uniqueIndex("junior_code_repositories_provider_id_idx").on(table.provider, table.providerId)]);
563
+ }, (table) => [uniqueIndex("junior_code_repositories_provider_id_idx").on(table.provider, table.providerId), index("junior_code_repositories_search_idx").using("gin", codeRepositorySearchDocument(table))]);
260
564
  /** Latest known state for one code change created by Junior. */
261
565
  const juniorCodeChanges = pgTable("junior_code_changes", {
262
566
  id: uuid("id").primaryKey(),
567
+ additions: integer("additions"),
568
+ changedFiles: integer("changed_files"),
263
569
  closedAt: timestamptz("closed_at"),
264
570
  conversationIds: text("conversation_ids").array().notNull().default(sql`ARRAY[]::text[]`),
571
+ deletions: integer("deletions"),
265
572
  draft: boolean("draft").notNull().default(false),
266
573
  /** Latest push, review, or comment by a person, from the code plugin. */
267
574
  lastActivityAt: timestamptz("last_activity_at"),
@@ -281,6 +588,7 @@ const juniorCodeChanges = pgTable("junior_code_changes", {
281
588
  index("junior_code_changes_merged_at_idx").on(table.mergedAt),
282
589
  index("junior_code_changes_closed_at_idx").on(table.closedAt),
283
590
  index("junior_code_changes_repository_state_idx").on(table.repositoryId, table.state, table.updatedAt.desc()),
591
+ index("junior_code_changes_search_idx").using("gin", codeChangeSearchDocument(table)),
284
592
  index("junior_code_changes_open_idx").on(table.id).where(sql`${table.state} = 'open'`)
285
593
  ]);
286
594
  // src/db/schema/conversation-annotations.ts
@@ -415,6 +723,7 @@ const juniorConversationBriefs = pgTable("junior_conversation_briefs", {
415
723
  turnId: text("turn_id").notNull(),
416
724
  throughSeq: integer("through_seq").notNull(),
417
725
  content: jsonb("content").$type().notNull(),
726
+ outcomeStatus: text("outcome_status").$type(),
418
727
  searchText: text("search_text").notNull(),
419
728
  modelId: text("model_id").notNull(),
420
729
  costMicroUsd: bigint("cost_micro_usd", { mode: "number" }),
@@ -432,6 +741,7 @@ const juniorConversationBriefs = pgTable("junior_conversation_briefs", {
432
741
  }).onDelete("cascade"),
433
742
  uniqueIndex("junior_conversation_briefs_conversation_turn_idx").on(table.conversationId, table.turnId),
434
743
  index("junior_conversation_briefs_conversation_version_idx").on(table.conversationId, table.version.desc()),
744
+ index("junior_conversation_briefs_created_at_idx").on(table.createdAt, table.conversationId),
435
745
  index("junior_conversation_briefs_search_idx").using("gin", sql`to_tsvector('english', ${table.searchText})`)
436
746
  ]);
437
747
  // src/db/schema/conversation-embeddings.ts
@@ -479,11 +789,6 @@ const juniorConversationEventEmbeddings = pgTable("junior_conversation_event_emb
479
789
  }).onDelete("cascade"),
480
790
  check("junior_conversation_event_embeddings_dimensions_check", sql`vector_dims(${table.embedding}) = ${table.dimensions}`)
481
791
  ]);
482
- // src/db/schema/tsvector.ts
483
- /** Postgres full-text lexemes. Queries read them only through SQL. */
484
- const tsvector = customType({ dataType() {
485
- return "tsvector";
486
- } });
487
792
  // src/db/schema/conversation-event-lexemes.ts
488
793
  /**
489
794
  * Stored full-text lexemes of one searchable Conversation event, for keyword
@@ -630,28 +935,62 @@ const juniorLocationConfigurations = pgTable("junior_location_configurations", {
630
935
  source: text("source"),
631
936
  expiresAt: text("expires_at")
632
937
  }, (table) => [primaryKey({ columns: [table.locationId, table.key] })]);
633
- // src/db/schema/stats.ts
938
+ // src/db/schema/automation-versions.ts
939
+ /** One saved Automation definition. Lifecycle and scheduler state are not versioned. */
940
+ const juniorAutomationVersions = pgTable("junior_automation_versions", {
941
+ automationId: text("automation_id").notNull(),
942
+ /** Starts at 1 and increases by 1 for each saved definition change. */
943
+ version: integer("version").notNull(),
944
+ createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
945
+ /** Slack principal that saved this definition. Null when unknown. */
946
+ editedBy: jsonb("edited_by"),
947
+ definition: jsonb("definition").notNull()
948
+ }, (table) => [primaryKey({
949
+ name: "junior_automation_versions_pk",
950
+ columns: [table.automationId, table.version]
951
+ }), foreignKey({
952
+ name: "junior_automation_versions_automation_id_fk",
953
+ columns: [table.automationId],
954
+ foreignColumns: [juniorAutomations.id]
955
+ }).onDelete("cascade")]);
956
+ // src/db/schema/automation-runs.ts
634
957
  /**
635
- * Daily named counters used by Junior and loaded plugins.
636
- * TODO: store hour keys when dashboard 24h workspace usage needs hourly bars.
637
- * `date` is a Postgres date column, so counters stay day-bucketed today.
958
+ * One dispatch of an Automation, from claim or dispatch to its outcome. A
959
+ * Scheduled automation run id is `<automation id>:<scheduled time>`. An event
960
+ * automation run id is its dispatch id. Automation code sets
961
+ * `conversation_id` when it dispatches the run. A run that was skipped, or
962
+ * that failed before dispatch, has no Conversation.
963
+ *
964
+ * `automation_version` is the Automation version that the run dispatched. It
965
+ * shows which instruction ran and who saved it after the definition changes.
966
+ * It is null before dispatch, and when no saved version matched.
638
967
  */
639
- const juniorStats = pgTable("junior_stats", {
640
- date: date("date", { mode: "string" }).notNull(),
641
- namespace: text("namespace").notNull(),
642
- metric: text("metric").notNull(),
643
- name: text("name").notNull(),
644
- count: bigint("value", { mode: "number" }).notNull().default(0),
645
- legacyCount: integer("count").notNull().default(0)
646
- }, (table) => [primaryKey({
647
- name: "junior_stats_date_namespace_metric_name_pk",
648
- columns: [
649
- table.date,
650
- table.namespace,
651
- table.metric,
652
- table.name
653
- ]
654
- })]);
968
+ const juniorAutomationRuns = pgTable("junior_automation_runs", {
969
+ id: text("id").primaryKey(),
970
+ automationId: text("automation_id").notNull().references(() => juniorAutomations.id, { onDelete: "cascade" }),
971
+ conversationId: text("conversation_id").unique().references(() => juniorConversations.conversationId),
972
+ status: text("status").$type().notNull(),
973
+ automationVersion: integer("automation_version"),
974
+ scheduledForMs: bigint("scheduled_for_ms", { mode: "number" }),
975
+ attempt: integer("attempt"),
976
+ claimedAtMs: bigint("claimed_at_ms", { mode: "number" }),
977
+ dispatchId: text("dispatch_id"),
978
+ startedAtMs: bigint("started_at_ms", { mode: "number" }),
979
+ completedAtMs: bigint("completed_at_ms", { mode: "number" }),
980
+ errorMessage: text("error_message"),
981
+ resultMessageTs: text("result_message_ts"),
982
+ costMicroUsd: bigint("cost_micro_usd", { mode: "number" })
983
+ }, (table) => [
984
+ foreignKey({
985
+ name: "junior_automation_runs_automation_version_fk",
986
+ columns: [table.automationId, table.automationVersion],
987
+ foreignColumns: [juniorAutomationVersions.automationId, juniorAutomationVersions.version]
988
+ }),
989
+ check("junior_automation_runs_status_check", sql`${table.status} in ('pending', 'running', 'completed', 'failed', 'blocked', 'skipped')`),
990
+ index("junior_automation_runs_automation_idx").on(table.automationId, table.completedAtMs),
991
+ index("junior_automation_runs_completed_idx").on(table.completedAtMs),
992
+ index("junior_automation_runs_incomplete_idx").on(table.automationId, table.scheduledForMs).where(sql`${table.status} in ('pending', 'running')`)
993
+ ]);
655
994
  // src/db/schema/automations.ts
656
995
  /**
657
996
  * One row per Automation of either kind. `record` holds the fields that have
@@ -689,6 +1028,11 @@ const juniorAutomations = pgTable("junior_automations", {
689
1028
  * clears it.
690
1029
  */
691
1030
  lastRunId: text("last_run_id").references(() => juniorAutomationRuns.id, { onDelete: "set null" }),
1031
+ /**
1032
+ * When core last saw this Automation recover after a person dismissed
1033
+ * its alert. A dismissed alert hides the Automation's alerts until then.
1034
+ */
1035
+ alertRecoveredAtMs: bigint("alert_recovered_at_ms", { mode: "number" }),
692
1036
  namespace: text("namespace"),
693
1037
  identifier: text("identifier"),
694
1038
  record: jsonb("record").$type().notNull()
@@ -707,68 +1051,15 @@ const juniorAutomations = pgTable("junior_automations", {
707
1051
  index("junior_automations_skill_idx").on(table.skill, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted' AND ${table.skill} IS NOT NULL`),
708
1052
  index("junior_automations_match_idx").on(table.namespace, table.identifier, table.createdAtMs, table.id).where(sql`${table.status} <> 'deleted'`)
709
1053
  ]);
710
- // src/db/schema/automation-versions.ts
711
- /** One saved Automation definition. Lifecycle and scheduler state are not versioned. */
712
- const juniorAutomationVersions = pgTable("junior_automation_versions", {
713
- automationId: text("automation_id").notNull(),
714
- /** Starts at 1 and increases by 1 for each saved definition change. */
715
- version: integer("version").notNull(),
716
- createdAtMs: bigint("created_at_ms", { mode: "number" }).notNull(),
717
- /** Slack principal that saved this definition. Null when unknown. */
718
- editedBy: jsonb("edited_by"),
719
- definition: jsonb("definition").notNull()
720
- }, (table) => [primaryKey({
721
- name: "junior_automation_versions_pk",
722
- columns: [table.automationId, table.version]
723
- }), foreignKey({
724
- name: "junior_automation_versions_automation_id_fk",
725
- columns: [table.automationId],
726
- foreignColumns: [juniorAutomations.id]
727
- }).onDelete("cascade")]);
728
- // src/db/schema/automation-runs.ts
729
- /**
730
- * One dispatch of an Automation, from claim or dispatch to its outcome. A
731
- * Scheduled automation run id is `<automation id>:<scheduled time>`. An event
732
- * automation run id is its dispatch id. Automation code sets
733
- * `conversation_id` when it dispatches the run. A run that was skipped, or
734
- * that failed before dispatch, has no Conversation.
735
- *
736
- * `automation_version` is the Automation version that the run dispatched. It
737
- * shows which instruction ran and who saved it after the definition changes.
738
- * It is null before dispatch, and when no saved version matched.
739
- */
740
- const juniorAutomationRuns = pgTable("junior_automation_runs", {
741
- id: text("id").primaryKey(),
742
- automationId: text("automation_id").notNull().references(() => juniorAutomations.id, { onDelete: "cascade" }),
743
- conversationId: text("conversation_id").unique().references(() => juniorConversations.conversationId),
744
- status: text("status").$type().notNull(),
745
- automationVersion: integer("automation_version"),
746
- scheduledForMs: bigint("scheduled_for_ms", { mode: "number" }),
747
- attempt: integer("attempt"),
748
- claimedAtMs: bigint("claimed_at_ms", { mode: "number" }),
749
- dispatchId: text("dispatch_id"),
750
- startedAtMs: bigint("started_at_ms", { mode: "number" }),
751
- completedAtMs: bigint("completed_at_ms", { mode: "number" }),
752
- errorMessage: text("error_message"),
753
- resultMessageTs: text("result_message_ts"),
754
- costMicroUsd: bigint("cost_micro_usd", { mode: "number" })
755
- }, (table) => [
756
- foreignKey({
757
- name: "junior_automation_runs_automation_version_fk",
758
- columns: [table.automationId, table.automationVersion],
759
- foreignColumns: [juniorAutomationVersions.automationId, juniorAutomationVersions.version]
760
- }),
761
- check("junior_automation_runs_status_check", sql`${table.status} in ('pending', 'running', 'completed', 'failed', 'blocked', 'skipped')`),
762
- index("junior_automation_runs_automation_idx").on(table.automationId, table.completedAtMs),
763
- index("junior_automation_runs_completed_idx").on(table.completedAtMs),
764
- index("junior_automation_runs_incomplete_idx").on(table.automationId, table.scheduledForMs).where(sql`${table.status} in ('pending', 'running')`)
765
- ]);
766
1054
  // src/db/schema/review-items.ts
767
1055
  /**
768
1056
  * One Review item: something that needs a person. An action item stores its
769
1057
  * `request`, and
770
1058
  * its `answer` after an assignee submits it. `closed_at` is set for `done`
771
1059
  * and `dismissed`. `closed_by_user_id` is null when an agent closed it.
1060
+ * `owner_kind` and `owner_id` name its owner. The owner kind decides how the
1061
+ * item gets its visibility and tenant, and where the Inbox stacks it. The id
1062
+ * has no foreign key, because it can name a row of more than one table.
772
1063
  */
773
1064
  const juniorReviewItems = pgTable("junior_review_items", {
774
1065
  id: text("id").primaryKey(),
@@ -788,8 +1079,8 @@ const juniorReviewItems = pgTable("junior_review_items", {
788
1079
  subjectId: text("subject_id"),
789
1080
  subjectTitle: text("subject_title"),
790
1081
  subjectUrl: text("subject_url"),
791
- /** Conversation of the agent that added the item. */
792
- addedByConversationId: text("added_by_conversation_id").notNull().references(() => juniorConversations.conversationId, { onDelete: "cascade" }),
1082
+ ownerKind: text("owner_kind").$type().notNull().default("conversation"),
1083
+ ownerId: text("owner_id").notNull(),
793
1084
  /**
794
1085
  * Turn of the agent that added the item, or that last added it again with
795
1086
  * its dedupe key. Null for a plugin item, which has no Turn.
@@ -808,14 +1099,18 @@ const juniorReviewItems = pgTable("junior_review_items", {
808
1099
  createdAt: timestamptz("created_at").notNull(),
809
1100
  updatedAt: timestamptz("updated_at").notNull()
810
1101
  }, (table) => [
811
- check("junior_review_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:%' and ${table.answer} is null)))`),
1102
+ check("junior_review_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:%') and ${table.answer} is null)))`),
1103
+ check("junior_review_items_owner_check", sql`(${table.ownerKind} = 'conversation' and ${table.dedupeKey} not like 'automation:%') or (${table.ownerKind} = 'automation' and ${table.dedupeKey} like 'automation:%')`),
812
1104
  check("junior_review_items_status_check", sql`(${table.status} = 'open' and ${table.closedAt} is null) or (${table.status} in ('done', 'dismissed') and ${table.closedAt} is not null)`),
813
1105
  check("junior_review_items_tenant_check", sql`(${table.provider} is null) = (${table.providerTenantId} is null)`),
814
1106
  check("junior_review_items_visibility_check", sql`${table.visibility} = 'public' or not ${table.assignedToEveryone}`),
815
1107
  uniqueIndex("junior_review_items_open_dedupe_uidx").on(sql`coalesce(${table.provider}, '')`, sql`coalesce(${table.providerTenantId}, '')`, table.dedupeKey).where(sql`${table.status} = 'open'`),
816
1108
  index("junior_review_items_status_idx").on(table.status, table.updatedAt, table.id),
817
1109
  index("junior_review_items_subject_idx").on(table.subjectId, table.status),
818
- index("junior_review_items_automation_idx").on(table.automationId, table.status)
1110
+ index("junior_review_items_owner_idx").on(table.ownerKind, table.ownerId),
1111
+ index("junior_review_items_open_action_owner_idx").on(table.ownerId).where(sql`${table.status} = 'open' and ${table.kind} = 'action'`),
1112
+ index("junior_review_items_automation_idx").on(table.automationId, table.status),
1113
+ index("junior_review_items_answered_idx").on(table.ownerId, table.closedByUserId, table.closedAt).where(sql`${table.answer} is not null`)
819
1114
  ]);
820
1115
  /** The assigned Users of a Review item. Everyone is a flag on the item. */
821
1116
  const juniorReviewItemAssignees = pgTable("junior_review_item_assignees", {
@@ -838,6 +1133,64 @@ const juniorReviewItemSlackCards = pgTable("junior_review_item_slack_cards", {
838
1133
  channelId: text("channel_id").notNull(),
839
1134
  messageTs: text("message_ts").notNull()
840
1135
  }, (table) => [primaryKey({ columns: [table.itemId, table.conversationId] })]);
1136
+ // src/db/schema/inbox-snoozes.ts
1137
+ /**
1138
+ * One person's snooze of one Review item. A `snoozed` row hides the item
1139
+ * from that person's Inbox until one of its triggers fires. `woken` and
1140
+ * `cancelled` are final. The item's own status says whether it resolved.
1141
+ */
1142
+ const juniorInboxSnoozes = pgTable("junior_inbox_snoozes", {
1143
+ id: text("id").primaryKey(),
1144
+ userId: text("user_id").notNull().references(() => juniorUsers.id, { onDelete: "cascade" }),
1145
+ reviewItemId: text("review_item_id").notNull().references(() => juniorReviewItems.id, { onDelete: "cascade" }),
1146
+ state: text("state").$type().notNull(),
1147
+ createdAt: timestamptz("created_at").notNull()
1148
+ }, (table) => [
1149
+ check("junior_inbox_snoozes_state_check", sql`${table.state} in ('snoozed', 'woken', 'cancelled')`),
1150
+ uniqueIndex("junior_inbox_snoozes_snoozed_uidx").on(table.userId, table.reviewItemId).where(sql`${table.state} = 'snoozed'`),
1151
+ index("junior_inbox_snoozes_settled_idx").on(table.createdAt).where(sql`${table.state} <> 'snoozed'`),
1152
+ index("junior_inbox_snoozes_review_item_idx").on(table.reviewItemId)
1153
+ ]);
1154
+ /**
1155
+ * An Event that ends a snooze. `wake` brings the item back; `resolve`
1156
+ * dismisses the item and cancels the snooze. A snooze's triggers join with
1157
+ * OR: the first to fire wins, and the snooze ignores the rest. Time is a
1158
+ * `timer.fired` Event like any other.
1159
+ */
1160
+ const juniorInboxSnoozeTriggers = pgTable("junior_inbox_snooze_triggers", {
1161
+ snoozeId: text("snooze_id").notNull().references(() => juniorInboxSnoozes.id, { onDelete: "cascade" }),
1162
+ outcome: text("outcome").$type().notNull(),
1163
+ namespace: text("namespace").notNull(),
1164
+ identifier: text("identifier").notNull(),
1165
+ eventType: text("event_type").notNull(),
1166
+ match: jsonb("match").$type()
1167
+ }, (table) => [
1168
+ check("junior_inbox_snooze_triggers_outcome_check", sql`${table.outcome} in ('wake', 'resolve')`),
1169
+ index("junior_inbox_snooze_triggers_event_idx").on(table.namespace, table.identifier, table.eventType),
1170
+ index("junior_inbox_snooze_triggers_snooze_idx").on(table.snoozeId)
1171
+ ]);
1172
+ // src/db/schema/stats.ts
1173
+ /**
1174
+ * Daily named counters used by Junior and loaded plugins.
1175
+ * TODO: store hour keys when dashboard 24h workspace usage needs hourly bars.
1176
+ * `date` is a Postgres date column, so counters stay day-bucketed today.
1177
+ */
1178
+ const juniorStats = pgTable("junior_stats", {
1179
+ date: date("date", { mode: "string" }).notNull(),
1180
+ namespace: text("namespace").notNull(),
1181
+ metric: text("metric").notNull(),
1182
+ name: text("name").notNull(),
1183
+ count: bigint("value", { mode: "number" }).notNull().default(0),
1184
+ legacyCount: integer("count").notNull().default(0)
1185
+ }, (table) => [primaryKey({
1186
+ name: "junior_stats_date_namespace_metric_name_pk",
1187
+ columns: [
1188
+ table.date,
1189
+ table.namespace,
1190
+ table.metric,
1191
+ table.name
1192
+ ]
1193
+ })]);
841
1194
  // src/db/schema/plan-items.ts
842
1195
  /**
843
1196
  * Gives each Plan item its id and each change its version. One sequence
@@ -971,8 +1324,13 @@ const juniorSqlSchema = {
971
1324
  juniorConversationReadPositions,
972
1325
  juniorConversations,
973
1326
  juniorLocationConfigurations,
1327
+ juniorMemoryEmbeddings,
1328
+ juniorMemoryMemories,
1329
+ juniorMemorySignals,
974
1330
  juniorDestinations,
975
1331
  juniorIdentities,
1332
+ juniorInboxSnoozes,
1333
+ juniorInboxSnoozeTriggers,
976
1334
  juniorReviewItemAssignees,
977
1335
  juniorReviewItemConversations,
978
1336
  juniorReviewItemSlackCards,
@@ -1479,4 +1837,4 @@ function createJuniorSqlExecutor(args) {
1479
1837
  statementTimeoutMs
1480
1838
  });
1481
1839
  }
1482
- export { juniorConversationEvents as A, juniorUsers as B, juniorConversationEventLexemes as C, CONVERSATION_METRICS as D, juniorConversationBriefs as E, juniorAttachmentUploads as F, juniorArtifacts as H, juniorAttachments as I, juniorMessageAttachments as L, juniorConversationAnnotations as M, juniorCodeChanges as N, juniorConversationMetrics as O, juniorCodeRepositories as P, juniorConversations as R, juniorConversationBindings as S, juniorConversationEmbeddings as T, juniorDestinations as V, juniorLocationConfigurations as _, juniorWorkspaces as a, juniorConversationReadPositions as b, juniorPlanItems as c, juniorReviewItemSlackCards as d, juniorReviewItems as f, juniorStats as g, juniorAutomations as h, juniorWorkspaceRepos as i, juniorApiTokens as j, isUserInstruction as k, juniorReviewItemAssignees as l, juniorAutomationVersions as m, isPostgresErrorCode as n, juniorPushSubscriptions as o, juniorAutomationRuns as p, juniorSnapshots as r, juniorPlanItemVersionSeq as s, createJuniorSqlExecutor as t, juniorReviewItemConversations as u, juniorAgentBindings as v, juniorConversationEventEmbeddings as w, juniorConversationParticipants as x, juniorAgentInvocations as y, juniorIdentities as z };
1840
+ export { MEMORY_SCOPES as $, juniorConversationMetrics as A, juniorAttachments as B, juniorConversationParticipants as C, juniorConversationEmbeddings as D, juniorConversationEventEmbeddings as E, codeChangeSearchDocument as F, slackPersonSearchDocument as G, juniorConversations as H, codeRepositorySearchDocument as I, juniorMemoryEmbeddings as J, juniorUsers as K, juniorCodeChanges as L, juniorConversationEvents as M, juniorApiTokens as N, juniorConversationBriefs as O, juniorConversationAnnotations as P, MEMORY_KINDS as Q, juniorCodeRepositories as R, juniorConversationReadPositions as S, juniorConversationEventLexemes as T, juniorIdentities as U, juniorMessageAttachments as V, slackPersonPredicate as W, juniorMemorySignals as X, juniorMemoryMemories as Y, MEMORY_EMBEDDING_DIMENSIONS as Z, juniorAutomationRuns as _, juniorWorkspaces as a, guardedCosineDistance as at, juniorAgentBindings as b, juniorPlanItems as c, juniorArtifacts as ct, juniorInboxSnoozes as d, MEMORY_SOURCE_PLATFORMS as et, juniorReviewItemAssignees as f, juniorAutomations as g, juniorReviewItems as h, juniorWorkspaceRepos as i, embedText as it, isUserInstruction as j, CONVERSATION_METRICS as k, juniorStats as l, juniorReviewItemSlackCards as m, isPostgresErrorCode as n, memoryRuntimeContextSchema as nt, juniorPushSubscriptions as o, parseEmbeddingBatch as ot, juniorReviewItemConversations as p, juniorDestinations as q, juniorSnapshots as r, cosineDistance as rt, juniorPlanItemVersionSeq as s, refreshEmbeddings as st, createJuniorSqlExecutor as t, MEMORY_SUBJECT_TYPES as tt, juniorInboxSnoozeTriggers as u, juniorAutomationVersions as v, juniorConversationBindings as w, juniorAgentInvocations as x, juniorLocationConfigurations as y, juniorAttachmentUploads as z };