@sentry/junior 0.287.0 → 0.289.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 (79) hide show
  1. package/dist/{adapter-CL-HUKgd.js → adapter-tE1wnl0T.js} +1 -1
  2. package/dist/{admin-C9urXVfi.js → admin-BmsPbmO_.js} +2 -2
  3. package/dist/{agent-runner-Bfnw551N.js → agent-runner-bvl8U5uH.js} +489 -165
  4. package/dist/api/schema.d.ts +2 -2
  5. package/dist/api/schema.js +7 -7
  6. package/dist/api.d.ts +1 -1
  7. package/dist/api.js +628 -238
  8. package/dist/{app-DBY5TnfY.d.ts → app-Cu454FXq.d.ts} +2 -2
  9. package/dist/app.d.ts +1 -1
  10. package/dist/app.js +550 -71
  11. package/dist/assistant-reply-1N9oxyyb.js +58 -0
  12. package/dist/{automation-DksGNDRO.js → automation-DWbjJltM.js} +2 -2
  13. package/dist/{background-compaction-queue-CYI909P5.js → background-compaction-queue-D36oCldp.js} +161 -90
  14. package/dist/{briefs-DaXiMWzT.js → briefs-CV-1qkXa.js} +3 -3
  15. package/dist/{catalog-runtime-BCIuBe4d.js → catalog-runtime-BNK4uJVZ.js} +1 -1
  16. package/dist/cli/chat.js +14 -14
  17. package/dist/cli/check.js +3 -3
  18. package/dist/cli/main.js +3 -3
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/snapshot-create.js +4 -4
  21. package/dist/cli/upgrade.d.ts +1 -1
  22. package/dist/cli/upgrade.js +3 -3
  23. package/dist/{config-CkHcUMN7.js → config-DHAy7XlP.js} +363 -8
  24. package/dist/{connections-BnIj0wtx.js → connections-C3VmH3cf.js} +7 -129
  25. package/dist/{conversation-E7ZPJx2H.js → conversation-CwC8K3RZ.js} +22 -5
  26. package/dist/{conversation-pending-messages-DVch6YQw.js → conversation-pending-messages-B0cuLReP.js} +1 -1
  27. package/dist/{conversation-privacy-DF1hW0ja.js → conversation-privacy-Bky_veSp.js} +1 -1
  28. package/dist/{credential-sync-CzMar9hq.js → credential-sync-dY9o0YSj.js} +28 -20
  29. package/dist/{db-DJ11eZqq.js → db-BS2Kql3j.js} +81 -46
  30. package/dist/{db-YDKKDxlh.d.ts → db-BebRmhsH.d.ts} +10 -2
  31. package/dist/{executor-BY9TB31g.js → executor-cc4nH86C.js} +125 -18
  32. package/dist/instrumentation.js +2 -2
  33. package/dist/{logging-BO5zU6Mt.js → logging-CtCJmt9p.js} +3 -2
  34. package/dist/{media-Cz1ZiV1U.js → media-BepyEUNm.js} +5 -1
  35. package/dist/{message-CsUbuEc8.js → message-C5VuRcP9.js} +9 -9
  36. package/dist/nitro.d.ts +1 -1
  37. package/dist/nitro.js +19 -41
  38. package/dist/{oauth-callback-server-hiDKK0_n.js → oauth-callback-server-KRrYUZ35.js} +2 -2
  39. package/dist/{projection-CL_YWeGf.js → projection-BFJG58TG.js} +448 -721
  40. package/dist/{prompt-BHOEQSmf.js → prompt-D15oftoL.js} +5 -5
  41. package/dist/{registry-BriFLnaJ.js → registry-C_JrgqUz.js} +1 -1
  42. package/dist/{resolve-Bt6GgAiA.js → resolve-Cn_7JfP-.js} +3 -3
  43. package/dist/{result-Bo1TZu0Q.js → result-CIbQFLp6.js} +16 -10
  44. package/dist/{runner-D3YeCQgt.js → runner-BwmaMJVO.js} +8 -8
  45. package/dist/{sandbox-egress-signals-CcnSPP4S.js → sandbox-egress-signals-BOQ8gn7i.js} +1 -1
  46. package/dist/{schedule-BTp__wrw.js → schedule-cP0AACm1.js} +11 -2
  47. package/dist/{schema-BWE3RJEB.js → schema-Bptz19Ja.js} +72 -14
  48. package/dist/{schema-C6fsEwjo.d.ts → schema-DQaFSkZZ.d.ts} +122 -3
  49. package/dist/{service-account-DiQQuuw7.js → service-account-AGw_pANb.js} +3 -3
  50. package/dist/{service-account-r6fl0b-9.js → service-account-CLZfF8O1.js} +3 -3
  51. package/dist/{session-stop-B2Nut40V.js → session-stop-CbzKf7UI.js} +84 -31
  52. package/dist/{skills-CD5aJdzg.js → skills-CcAJBquq.js} +2 -2
  53. package/dist/{spawn-CalgZQiu.js → spawn-BvAk2vTI.js} +5 -5
  54. package/dist/{stop-kujZLbi0.js → stop-BQU4u7la.js} +893 -519
  55. package/dist/{store-DdIEUL1q.js → store-DE7NJOvQ.js} +4 -16
  56. package/dist/{task-runner-D_RDr2Hu.js → task-runner-Q_7duP_T.js} +31 -27
  57. package/dist/{turn-failure-response-B5nV1Er-.js → turn-failure-response-aWZLfUM8.js} +18 -9
  58. package/dist/{validation-K4pqwoVZ.js → validation-BOoPeIJR.js} +1 -1
  59. package/dist/{version-DBvhk1X9.js → version-Db0MFy61.js} +1 -1
  60. package/dist/version.js +1 -1
  61. package/dist/{viewer-DrMmFUul.js → viewer-FFEFu9In.js} +4 -4
  62. package/dist/warmup-DDzrA9Gv.js +967 -0
  63. package/dist/{work-ljRoODGu.js → work-BBJK458E.js} +16 -15
  64. package/dist/{worker-CYO1Q0Js.js → worker-2iU5RFyq.js} +7 -31
  65. package/migrations/0089_conversation_paused_status.sql +3 -0
  66. package/migrations/0090_guardian_review_time_index.sql +20 -0
  67. package/migrations/0091_conversation_participant_unsubscribed_index.sql +20 -0
  68. package/migrations/0092_turn_metric_actor.sql +12 -0
  69. package/migrations/0093_participant_root_actor_backfill.sql +18 -0
  70. package/migrations/0094_conversation_delivery_paused_at.sql +1 -0
  71. package/migrations/meta/0089_snapshot.json +4372 -0
  72. package/migrations/meta/0090_snapshot.json +4388 -0
  73. package/migrations/meta/0091_snapshot.json +4410 -0
  74. package/migrations/meta/0092_snapshot.json +4446 -0
  75. package/migrations/meta/0093_snapshot.json +4446 -0
  76. package/migrations/meta/0094_snapshot.json +4452 -0
  77. package/migrations/meta/_journal.json +42 -0
  78. package/package.json +6 -5
  79. package/dist/assistant-reply-u_PRYzuz.js +0 -65
package/dist/api.js CHANGED
@@ -1,33 +1,34 @@
1
- import { $a as createPluginLogger, Ai as hash, Ci as updateWorkspace, Fo as createPluginCache, In as isExperimentalFeatureEnabled, La as workspaceRepoCheckoutPath, Nr as reviewItemReaderForUser, Or as isOnlyAssignee, Pa as SANDBOX_RUNTIME, Rn as createUserTokenStore, Si as listWorkspacesByRepository, Tr as canActOnReviewItem, Zn as getPlugins, _i as createWorkspace, ar as resolveNotificationTimezone, br as reviewItemsNeedingUserVersionQuery, cr as readNotificationSchedule, di as getDashboardSettingsLink, do as readConversationBriefThrough, ir as sendPushNotificationToUser, ki as create, lr as saveNotificationSchedule, no as readConversationAccessFromSql, or as deletePushSubscription, po as readConversationEventPage, pr as countReviewItemsNeedingUser, rr as readWebPushConfig, sr as listPushSubscriptions, to as createConversationAccessReader, ur as savePushSubscription, vi as deleteWorkspace, wi as WorkspaceValidationError, xi as listWorkspaces, xr as searchReviewItems, yi as getWorkspace, yr as listWaitingConversations } from "./projection-CL_YWeGf.js";
2
- import { H as getAttachmentStorage, M as escapeXml, n as botConfig } from "./config-CkHcUMN7.js";
3
- import { m as logInfo, p as logException } from "./logging-BO5zU6Mt.js";
4
- import { a as getConversationStore, b as withConversationMutationLock, o as getDb, s as getSqlExecutor, x as conversationKindFromRow, z as nextDetailVersion } from "./db-DJ11eZqq.js";
5
- import { A as juniorConversations, D as juniorCodeChanges, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, S as juniorConversationMetrics, T as juniorApiTokens, j as juniorIdentities, w as juniorConversationEvents } from "./executor-BY9TB31g.js";
6
- import { n as INPUT_IMAGE_TYPES, t as INLINE_VIDEO_TYPES } from "./media-Cz1ZiV1U.js";
7
- import { n as pluginCatalogRuntime } from "./catalog-runtime-BCIuBe4d.js";
8
- import { $ as readViewerAutomationSummary, Et as throwApiError, G as changeViewerAutomationLifecycle, J as updateViewerAutomation, K as deleteViewerTask, Q as readViewerAutomationRuns, S as createSlackReviewItemShow, Tt as jsonResponse, W as activateViewerAutomationVersion, Y as ViewerTaskNotFoundError, Z as readViewerAutomationExecutions, _t as readLiveAttachment, et as readViewerAutomationVersions, it as listOwnedWatches, m as readStats, mt as webActorFromUser, nt as AutomationEditError, q as readViewerAutomationEdit, qt as listChildAgents, tt as readViewerAutomations, v as setConversationSubscription, wt as emptyResponse, xt as archiveConversation } from "./agent-runner-Bfnw551N.js";
9
- import { n as briefEntriesFromReportEvents, u as completeText } from "./prompt-BHOEQSmf.js";
10
- import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarImage, t as findUserByEmail } from "./viewer-DrMmFUul.js";
11
- import { r as getStateAdapter } from "./adapter-CL-HUKgd.js";
12
- import { r as notificationScheduleSchema } from "./schedule-BTp__wrw.js";
13
- import { C as createConversationBodySchema, E as forkConversationResponseSchema, O as conversationReadPositionSchema, T as forkConversationBodySchema, c as conversationDetailQuerySchema, d as conversationEventPageSchema, f as conversationEventsQuerySchema, h as conversationParamsSchema, k as conversationReadReportSchema, l as conversationDetailReportSchema, m as conversationFeedSchema, n as CONVERSATION_VERSION_HEADER, o as conversationAttachmentParamsSchema, p as conversationFeedQuerySchema, r as acceptedConversationMessageSchema, t as CONVERSATION_DETAIL_VERSION_HEADER, w as createConversationMessageBodySchema } from "./conversation-E7ZPJx2H.js";
14
- import { O as getEventCatalog, et as readUserCustomization, tt as saveUserCustomization } from "./session-stop-B2Nut40V.js";
1
+ import { $a as readConversationAccessFromSql, $n as isPausedBySlack, Aa as SANDBOX_RUNTIME, En as createUserTokenStore, Er as reviewItemReaderForUserInConversation, Gn as readWebPushConfig, Jn as deletePushSubscription, Kn as sendPushNotificationToUser, Na as workspaceRepoCheckoutPath, Qa as createConversationAccessReader, Qn as savePushSubscription, Ti as hash, Tr as reviewItemReaderForUser, Xn as readNotificationSchedule, Ya as createPluginLogger, Yn as listPushSubscriptions, Zn as saveNotificationSchedule, _i as listWorkspacesByRepository, ai as getDashboardSettingsLink, dr as searchReviewItems, fi as createWorkspace, gi as listWorkspaces, hr as canActOnReviewItem, jo as createPluginCache, lo as readConversationEventPage, lr as listWaitingConversations, mi as getWorkspace, mr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, pi as deleteWorkspace, qn as resolveNotificationTimezone, rr as countReviewItemsNeedingUser, so as readConversationBriefThrough, to as conversationIsMemberRoot, ur as reviewItemsNeedingUserVersionQuery, vi as updateWorkspace, wi as create, wr as reviewItemNeedsUser, yi as WorkspaceValidationError, yr as isOnlyAssignee, zn as getPlugins } from "./projection-BFJG58TG.js";
2
+ import { L as escapeXml, n as botConfig, q as getAttachmentStorage } from "./config-DHAy7XlP.js";
3
+ import { m as logInfo, p as logException } from "./logging-CtCJmt9p.js";
4
+ import { f as parseSlackTeamId, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
5
+ import { J as nextDetailVersion, a as getConversationStore, b as withConversationMutationLock, o as getDb, s as getSqlExecutor, v as loadConversationSlackTenantIds, x as conversationKindFromRow } from "./db-BS2Kql3j.js";
6
+ import { A as juniorConversations, D as juniorCodeChanges, E as juniorConversationAnnotations, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, S as juniorConversationMetrics, T as juniorApiTokens, j as juniorIdentities, l as juniorReviewItems, s as juniorReviewItemConversations, w as juniorConversationEvents } from "./executor-cc4nH86C.js";
7
+ import { n as INPUT_IMAGE_TYPES, t as INLINE_VIDEO_TYPES } from "./media-BepyEUNm.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-BNK4uJVZ.js";
9
+ import { $ as readViewerAutomationSummary, $t as resumeConversationDelivery, A as runWithSlackInstallation, Ct as emptyResponse, G as changeViewerAutomationLifecycle, J as updateViewerAutomation, K as deleteViewerTask, Q as readViewerAutomationRuns, Qt as pauseConversationDelivery, S as createSlackReviewItemShow, Tt as throwApiError, W as activateViewerAutomationVersion, Y as ViewerTaskNotFoundError, Z as readViewerAutomationExecutions, Zt as canPauseConversationDelivery, _t as readLiveAttachment, bt as archiveConversation, et as readViewerAutomationVersions, it as listOwnedWatches, m as readStats, mt as webActorFromUser, nt as AutomationEditError, on as listChildAgents, q as readViewerAutomationEdit, tt as readViewerAutomations, v as setConversationSubscription, wt as jsonResponse } from "./agent-runner-bvl8U5uH.js";
10
+ import { n as briefEntriesFromReportEvents, u as completeText } from "./prompt-D15oftoL.js";
11
+ import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarImage, t as findUserByEmail } from "./viewer-FFEFu9In.js";
12
+ import { r as getStateAdapter } from "./adapter-tE1wnl0T.js";
13
+ import { r as notificationScheduleSchema } from "./schedule-cP0AACm1.js";
14
+ import { A as renameConversationBodySchema, C as createConversationBodySchema, E as forkConversationResponseSchema, M as conversationReadPositionSchema, N as conversationReadReportSchema, T as forkConversationBodySchema, c as conversationDetailQuerySchema, d as conversationEventPageSchema, f as conversationEventsQuerySchema, h as conversationParamsSchema, j as renameConversationResponseSchema, l as conversationDetailReportSchema, m as conversationFeedSchema, n as CONVERSATION_VERSION_HEADER, o as conversationAttachmentParamsSchema, p as conversationFeedQuerySchema, r as acceptedConversationMessageSchema, t as CONVERSATION_DETAIL_VERSION_HEADER, w as createConversationMessageBodySchema } from "./conversation-CwC8K3RZ.js";
15
+ import { g as getVercelConversationWorkQueue } from "./background-compaction-queue-D36oCldp.js";
16
+ import { O as getEventCatalog, et as readUserCustomization, rt as isExperimentalFeatureEnabled, tt as saveUserCustomization } from "./session-stop-CbzKf7UI.js";
15
17
  import { E as userCustomizationSchema, a as fillUtcSixHours, c as trailingUtcDayWindow, d as utcDayKey, f as utcHourKey, i as fillUtcHours, l as trailingUtcHourWindow, m as apiErrorSchema, n as HOUR_MS$1, o as startOfUtcHour, r as fillUtcDays, s as sumUtcHoursIntoSixHours, t as DAY_MS$1, u as trailingUtcSixHourWindow } from "./reporting-window-B3Ze-Qnt.js";
16
- import { s as getSandboxResources, t as getCachedSnapshot } from "./resolve-Bt6GgAiA.js";
17
- import { _ as getVercelConversationWorkQueue } from "./background-compaction-queue-CYI909P5.js";
18
- import { J as AutomationConflictError, St as automationEventCatalog, dt as conversationRangeColumns, ft as conversationUsageCostExpr, lt as conversationActiveDaysColumn, st as readAutomationTitlesByConversationId, ut as conversationAggregateColumns } from "./task-runner-D_RDr2Hu.js";
19
- import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-DiQQuuw7.js";
20
- import { N as ScheduleIntentError, P as compileScheduleIntent, _ as automationSummarySchema, b as automationVersionListSchema, c as automationLifecycleSchema, d as automationParamsSchema, f as automationRunListSchema, g as automationSchedulePreviewSchema, h as automationScheduleIntentSchema, i as automationExecutionListSchema, l as automationListQuerySchema, n as automationEditSchema, r as automationEventCatalogSchema, t as automationEditErrorSchema, u as automationListSchema, v as automationUpdateSchema, x as automationVersionParamsSchema, y as automationVersionActivateSchema } from "./automation-DksGNDRO.js";
21
- import { _ as pluginsSchema, b as skillReportsSchema, c as conversationUnchangedDetailWithMailboxSchema, d as healthReportSchema, f as pluginOperationalReportFeedSchema, l as steerConversationPendingMessagesBodySchema, n as cancelConversationPendingMessagesResponseSchema, r as conversationDetailWithMailboxReportSchema, s as conversationPendingMessagesReportSchema, t as cancelConversationPendingMessagesBodySchema, u as steerConversationPendingMessagesResponseSchema, v as runtimeInfoReportSchema } from "./conversation-pending-messages-DVch6YQw.js";
22
- import { $ as readReviewItemForUser, C as createConversationForViewer, E as cancelConversationPendingMessagesForViewer, F as isAllowedSignInEmail, M as getProductionSlackAdapter, O as requireConversationPendingMessages, S as appendConversationMessageForViewer, X as ReviewItemActionError, Z as actOnReviewItem, _ as keepQuickQuestionForViewer, a as pinConversation, at as setConversationAutoArchive, c as continueConversationInSlackForViewer, d as readConversationTreeMetricsFromSql, f as conversationVersionQuery, g as forkConversationForViewer, h as reportConversationRead, i as readConversationFeed, k as resolveMentions, l as readConversationAuxiliaryCostsFromSql, m as markConversationUnread, n as steerConversationPendingMessagesForViewer, nt as archiveViewerDoneConversations, o as reorderPinnedConversations, ot as updateUserAutoArchiveSettings, p as readConversationDetailEtag, r as conversationFeedVersionQuery, rt as readUserAutoArchiveSettings, s as readConversationDetail, t as stopConversationTurnForViewer, tt as DEFAULT_AUTO_ARCHIVE_SETTINGS, u as childAgentTotalsReport, ut as readHealthReport, v as readConversationEvents, x as readFirstHumanMessageTexts, y as conversationSummaryFromStoredConversation } from "./stop-kujZLbi0.js";
23
- import { a as startConnection, n as isConnectableProvider, r as listConnections, s as htmlCallbackResponse, t as disconnectConnection } from "./connections-BnIj0wtx.js";
24
- import { A as actorDirectoryReportSchema, At as conversationCatchUpSchema, B as activityHours$1, C as startServiceAccountSignInResponseSchema, Ct as conversationSubscriptionBodySchema, Dt as reorderPinnedConversationsBodySchema, E as personalTokenListSchema, Et as pinConversationResponseSchema, G as pushSubscriptionDeleteBodySchema, I as locationDetailReportSchema, J as connectionParamsSchema, K as testNotificationResponseSchema, L as locationDirectoryReportSchema, M as avatarParamsSchema, N as personParamsSchema, O as personalTokenParamsSchema, Ot as reorderPinnedConversationsResponseSchema, P as personalSpendReportSchema, R as locationParamsSchema, St as markConversationUnreadBodySchema, T as createdPersonalTokenSchema, Tt as pinConversationBodySchema, U as notificationSettingsSchema, V as activitySixHours$1, W as pushSubscriptionBodySchema, X as disconnectConnectionResponseSchema, Z as startConnectionResponseSchema, _ as reviewItemSchema, _t as archiveConversationBodySchema, b as serviceAccountListSchema, bt as conversationAutoArchiveSchema, c as workspaceListSchema, d as workspaceSchema, dt as continueConversationInSlackResponseSchema, f as reviewItemActionSchema, ft as stopConversationTurnResponseSchema, g as reviewItemParamsSchema, gt as renameConversationResponseSchema, h as reviewItemListSchema, ht as renameConversationBodySchema, i as statsReportSchema, it as codeRepositoryReportSchema, j as actorProfileReportSchema, k as revokePersonalTokenResponseSchema, kt as conversationCatchUpBodySchema, l as workspaceParamsSchema, lt as conversationChildAgentsReportSchema, m as reviewItemListQuerySchema, n as versionsSchema, nt as codePersonReportSchema, o as deleteWorkspaceResponseSchema, p as reviewItemCountSchema, pt as conversationStatsReportSchema, q as connectionListSchema, rt as codeRepositoryParamsSchema, s as workspaceBodySchema, st as conversationWatchesReportSchema, t as versionsQuerySchema, tt as codeOverviewReportSchema, ut as continueConversationInSlackBodySchema, v as reviewItemWaitingConversationsSchema, vt as archiveConversationResponseSchema, w as createPersonalTokenBodySchema, wt as conversationSubscriptionResponseSchema, x as serviceAccountParamsSchema, xt as conversationUnreadSchema, y as disconnectServiceAccountResponseSchema, yt as archiveDoneConversationsResponseSchema, z as activityDays$1 } from "./schema-BWE3RJEB.js";
18
+ import { s as getSandboxResources, t as getCachedSnapshot } from "./resolve-Cn_7JfP-.js";
19
+ import { J as AutomationConflictError, bt as automationEventCatalog, lt as conversationAggregateColumns, st as readAutomationTitlesByConversationId, ut as conversationRangeColumns } from "./task-runner-Q_7duP_T.js";
20
+ import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-AGw_pANb.js";
21
+ import { N as ScheduleIntentError, P as compileScheduleIntent, _ as automationSummarySchema, b as automationVersionListSchema, c as automationLifecycleSchema, d as automationParamsSchema, f as automationRunListSchema, g as automationSchedulePreviewSchema, h as automationScheduleIntentSchema, i as automationExecutionListSchema, l as automationListQuerySchema, n as automationEditSchema, r as automationEventCatalogSchema, t as automationEditErrorSchema, u as automationListSchema, v as automationUpdateSchema, x as automationVersionParamsSchema, y as automationVersionActivateSchema } from "./automation-DWbjJltM.js";
22
+ import { _ as pluginsSchema, b as skillReportsSchema, c as conversationUnchangedDetailWithMailboxSchema, d as healthReportSchema, f as pluginOperationalReportFeedSchema, l as steerConversationPendingMessagesBodySchema, n as cancelConversationPendingMessagesResponseSchema, r as conversationDetailWithMailboxReportSchema, s as conversationPendingMessagesReportSchema, t as cancelConversationPendingMessagesBodySchema, u as steerConversationPendingMessagesResponseSchema, v as runtimeInfoReportSchema } from "./conversation-pending-messages-B0cuLReP.js";
23
+ import { $ as actOnReviewItem, C as createConversationForViewer, E as cancelConversationPendingMessagesForViewer, F as isAllowedSignInEmail, M as getProductionSlackAdapter, O as requireConversationPendingMessages, Q as ReviewItemActionError, S as appendConversationMessageForViewer, _ as keepQuickQuestionForViewer, a as pinConversation, at as continueConversationInSlack, c as readConversationParticipants, ct as archiveViewerDoneConversations, d as readConversationTreeMetricsFromSql, dt as setConversationAutoArchive, f as conversationVersionQuery, ft as updateUserAutoArchiveSettings, g as forkConversationForViewer, gt as readHealthReport, h as reportConversationRead, i as readConversationFeed, it as canContinueInSlack, k as resolveMentions, l as readConversationAuxiliaryCostsFromSql, lt as readUserAutoArchiveSettings, m as markConversationUnread, n as steerConversationPendingMessagesForViewer, o as reorderPinnedConversations, p as readConversationDetailEtag, r as conversationFeedVersionQuery, s as readConversationDetail, st as DEFAULT_AUTO_ARCHIVE_SETTINGS, t as stopConversationTurnForViewer, tt as readReviewItemForUser, u as childAgentTotalsReport, v as readConversationEvents, x as readFirstHumanMessageTexts, y as conversationSummaryFromStoredConversation } from "./stop-BQU4u7la.js";
24
+ import { a as startConnection, n as isConnectableProvider, r as listConnections, s as htmlCallbackResponse, t as disconnectConnection } from "./connections-C3VmH3cf.js";
25
+ import { A as actorDirectoryReportSchema, At as reorderPinnedConversationsResponseSchema, B as activityHours$1, C as startServiceAccountSignInResponseSchema, Ct as conversationSubscriptionBodySchema, Dt as pinConversationBodySchema, E as personalTokenListSchema, Et as conversationDeliveryResponseSchema, G as pushSubscriptionDeleteBodySchema, I as locationDetailReportSchema, J as connectionParamsSchema, K as testNotificationResponseSchema, L as locationDirectoryReportSchema, M as avatarParamsSchema, Mt as conversationCatchUpSchema, N as personParamsSchema, O as personalTokenParamsSchema, Ot as pinConversationResponseSchema, P as personalSpendReportSchema, R as locationParamsSchema, St as markConversationUnreadBodySchema, T as createdPersonalTokenSchema, Tt as conversationDeliveryBodySchema, U as notificationSettingsSchema, V as activitySixHours$1, W as pushSubscriptionBodySchema, X as disconnectConnectionResponseSchema, Z as startConnectionResponseSchema, _ as reviewItemSchema, _t as archiveConversationBodySchema, b as serviceAccountListSchema, bt as conversationAutoArchiveSchema, c as workspaceListSchema, ct as conversationWatchesReportSchema, d as workspaceSchema, dt as continueConversationInSlackBodySchema, f as reviewItemActionSchema, ft as continueConversationInSlackResponseSchema, g as reviewItemParamsSchema, gt as conversationOutlineSchema, h as reviewItemListSchema, i as statsReportSchema, it as codeRepositoryReportSchema, j as actorProfileReportSchema, jt as conversationCatchUpBodySchema, k as revokePersonalTokenResponseSchema, kt as reorderPinnedConversationsBodySchema, l as workspaceParamsSchema, m as reviewItemListQuerySchema, mt as conversationStatsReportSchema, n as versionsSchema, nt as codePersonReportSchema, o as deleteWorkspaceResponseSchema, ot as boardReportSchema, p as reviewItemCountSchema, pt as stopConversationTurnResponseSchema, q as connectionListSchema, rt as codeRepositoryParamsSchema, s as workspaceBodySchema, t as versionsQuerySchema, tt as codeOverviewReportSchema, ut as conversationChildAgentsReportSchema, v as reviewItemWaitingConversationsSchema, vt as archiveConversationResponseSchema, w as createPersonalTokenBodySchema, wt as conversationSubscriptionResponseSchema, x as serviceAccountParamsSchema, xt as conversationUnreadSchema, y as disconnectServiceAccountResponseSchema, yt as archiveDoneConversationsResponseSchema, z as activityDays$1 } from "./schema-Bptz19Ja.js";
25
26
  import { Hono } from "hono";
26
27
  import path from "node:path";
27
28
  import { createHash, randomBytes, randomUUID } from "node:crypto";
28
29
  import * as z from "zod";
29
- import { and, asc, desc, eq, gt, gte, isNull, lte, notExists, or, sql } from "drizzle-orm";
30
- import { pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
30
+ import { and, arrayOverlaps, asc, desc, eq, gt, gte, inArray, isNull, like, lte, or, sql } from "drizzle-orm";
31
+ import { conversationAnnotationInputSchema, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
31
32
  import { alias } from "drizzle-orm/pg-core";
32
33
  import { readFileSync } from "node:fs";
33
34
  import { HTTPException } from "hono/http-exception";
@@ -68,7 +69,7 @@ Rules:
68
69
  - Use only facts in the input. Do not invent names, ids, numbers, outcomes, or links.
69
70
  - Do not repeat what the Brief already says unless it changed.
70
71
  - Never say that a code change was merged, closed, deployed, or released unless a row says so.
71
- - Ignore Junior runtime mechanics, context tags, and markers such as [[NO_REPLY]].
72
+ - Ignore Junior runtime mechanics and context tags.
72
73
  - Address the reader as "you".
73
74
  - When a row asks the reader a question, asks them to review, approve, or decide something, or waits on them, add one last line that starts with "Needs you:" and says what. Otherwise, do not add that line.
74
75
  - Plain text only. No headings, lists, or Markdown.`;
@@ -195,6 +196,20 @@ async function catchUpOnConversation(viewer, conversationId, range) {
195
196
  ...conversation.title ? { title: conversation.title } : void 0
196
197
  });
197
198
  }
199
+ // src/api/conversations/delivery.ts
200
+ /**
201
+ * Detach a root from its Location, or attach it again. Only a participant
202
+ * can change it, the same as rename. A mention in the Location attaches it
203
+ * again too.
204
+ */
205
+ async function setConversationDeliveryForViewer(viewer, conversationId, body) {
206
+ const conversation = (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId)?.isParticipant ? await getConversationStore().get({ conversationId }) : void 0;
207
+ if (!conversation) throwApiError(404, "Conversation not found.");
208
+ if (!canPauseConversationDelivery(conversation)) throwApiError(409, "Only a conversation with a Slack thread can detach.");
209
+ if (body.paused) await pauseConversationDelivery(conversationId);
210
+ else await resumeConversationDelivery(conversationId);
211
+ return { paused: body.paused };
212
+ }
198
213
  // src/chat/conversations/sql/title.ts
199
214
  /**
200
215
  * Replace one Conversation's title. Returns the stored title, or undefined
@@ -266,6 +281,47 @@ async function requireConversationChildAgents(conversationId, options = {}) {
266
281
  conversationId
267
282
  });
268
283
  }
284
+ // src/api/conversations/continue-in-slack.ts
285
+ async function readSlackChannelLocation(locationId) {
286
+ const [row] = await getDb().select({
287
+ channelId: juniorDestinations.providerDestinationId,
288
+ displayName: juniorDestinations.displayName,
289
+ teamId: juniorDestinations.providerTenantId
290
+ }).from(juniorDestinations).where(and(eq(juniorDestinations.id, locationId), eq(juniorDestinations.provider, "slack"), eq(juniorDestinations.kind, "channel")));
291
+ const channelId = parseSlackChannelId(row?.channelId);
292
+ const teamId = parseSlackTeamId(row?.teamId);
293
+ if (!row || !channelId || !teamId) return void 0;
294
+ return {
295
+ channelId,
296
+ ...row.displayName ? { channelName: row.displayName } : void 0,
297
+ teamId
298
+ };
299
+ }
300
+ /** Move a participant's public dashboard Conversation to a new Slack thread. */
301
+ async function continueConversationInSlackForViewer(viewer, conversationId, body) {
302
+ const conversation = await getConversationStore().get({ conversationId });
303
+ const access = conversation ? (await readConversationAccessFromSql(getDb(), [conversationId], viewer)).get(conversationId) : void 0;
304
+ if (!conversation || !access?.canViewPrivateContent) throwApiError(404, "Conversation not found.");
305
+ if (!access.isParticipant) throwApiError(403, "Only conversation participants can move it to Slack.");
306
+ if (!canContinueInSlack(conversation, access)) throwApiError(409, "Only a public dashboard conversation can move to Slack, once.");
307
+ const channel = await readSlackChannelLocation(body.locationId);
308
+ if (!channel) throwApiError(404, "Channel not found.");
309
+ const result = await runWithSlackInstallation({
310
+ adapter: getProductionSlackAdapter(),
311
+ installation: { teamId: channel.teamId },
312
+ task: () => continueConversationInSlack({
313
+ actorName: viewer.displayName ?? viewer.email,
314
+ channel,
315
+ conversation
316
+ })
317
+ });
318
+ if (result.status === "refused") throwApiError(409, result.message);
319
+ return {
320
+ conversationId,
321
+ ...result.channelName ? { channelName: result.channelName } : void 0,
322
+ ...result.locationUrl ? { locationUrl: result.locationUrl } : void 0
323
+ };
324
+ }
269
325
  // src/api/conversations/attachments.ts
270
326
  const INLINE_TYPES = [...INPUT_IMAGE_TYPES, ...INLINE_VIDEO_TYPES];
271
327
  function contentDisposition(filename, contentType) {
@@ -345,6 +401,50 @@ async function conversationAttachmentResponse(args) {
345
401
  function notFound() {
346
402
  throwApiError(404, "Attachment not found.");
347
403
  }
404
+ // src/api/conversations/outline.ts
405
+ const payload = juniorConversationEvents.payload;
406
+ /**
407
+ * List the person messages of a whole Conversation for the dashboard
408
+ * outline. The dashboard transcript loads only the latest pages, so the
409
+ * outline cannot build its items from the loaded rows alone.
410
+ *
411
+ * It uses the same rules as the transcript: Event messages are not person
412
+ * messages, and a message that does not mention Junior is thread context.
413
+ * The `message_role_idx` index reads only this Conversation's user
414
+ * messages, so the cost grows with the person messages, not all events.
415
+ */
416
+ async function readConversationOutline(conversationId, options = {}) {
417
+ const access = (await readConversationAccessFromSql(getDb(), [conversationId], options.viewer)).get(conversationId);
418
+ if (!access) return void 0;
419
+ if (!access.canViewPrivateContent) return { items: [] };
420
+ const items = (await getDb().select({
421
+ seq: juniorConversationEvents.seq,
422
+ text: sql`left(${payload}->>'text', ${200})`
423
+ }).from(juniorConversationEvents).where(and(eq(juniorConversationEvents.conversationId, conversationId), sql`${juniorConversationEvents.type} = 'message'`, sql`${payload}->>'role' = 'user'`, sql`${payload}->'meta'->>'eventType' is null`, sql`coalesce(${payload}->'meta'->>'explicitMention', 'true') <> 'false'`)).orderBy(asc(juniorConversationEvents.seq))).flatMap((row) => {
424
+ const text = withoutCutToken(row.text).trim();
425
+ return text ? [{
426
+ seq: row.seq,
427
+ text
428
+ }] : [];
429
+ });
430
+ const tenantId = (await loadConversationSlackTenantIds(getSqlExecutor(), [conversationId])).get(conversationId);
431
+ const mentions = await resolveMentions(getSqlExecutor(), items.map((item) => ({
432
+ tenantId,
433
+ texts: [item.text]
434
+ })));
435
+ return { items: items.map((item, index) => mentions[index].length > 0 ? {
436
+ ...item,
437
+ mentions: mentions[index]
438
+ } : item) };
439
+ }
440
+ /**
441
+ * Repair a Slack token that the length cut split. A cut mention, such as
442
+ * `<@U12`, cannot resolve, so it is dropped. A cut link keeps its URL text,
443
+ * so a message that is only a long link still has a title.
444
+ */
445
+ function withoutCutToken(text) {
446
+ return text.length < 200 ? text : text.replace(/<([^<>]*)$/, (_, token) => /^[@#!]/.test(token) ? "" : token.split("|")[0]);
447
+ }
348
448
  // src/api/conversations/metric-buckets.ts
349
449
  /** Sum all Conversation metrics into UTC day or hour buckets. */
350
450
  async function readConversationMetricBuckets(db, options) {
@@ -792,6 +892,7 @@ function createConversationRoutes(options) {
792
892
  return jsonResponse(archiveConversationResponseSchema, await archiveConversation(viewer, conversationId, body));
793
893
  });
794
894
  app.patch("/:conversationId/pin", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", pinConversationBodySchema, "Invalid request body."), async (context) => jsonResponse(pinConversationResponseSchema, await pinConversation(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
895
+ app.patch("/:conversationId/delivery", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationDeliveryBodySchema, "Invalid request body."), async (context) => jsonResponse(conversationDeliveryResponseSchema, await setConversationDeliveryForViewer(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
795
896
  app.patch("/:conversationId/subscription", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationSubscriptionBodySchema, "Invalid request body."), async (context) => jsonResponse(conversationSubscriptionResponseSchema, await setConversationSubscription(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
796
897
  app.patch("/:conversationId/unread", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", markConversationUnreadBodySchema, "Invalid request body."), async (context) => jsonResponse(conversationUnreadSchema, await markConversationUnread(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
797
898
  app.patch("/:conversationId/title", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", renameConversationBodySchema, "Invalid request body."), async (context) => jsonResponse(renameConversationResponseSchema, await renameConversation(context.get("viewer"), context.req.valid("param").conversationId, context.req.valid("json"))));
@@ -821,6 +922,13 @@ function createConversationRoutes(options) {
821
922
  if (!report) throwApiError(404, "Conversation not found.");
822
923
  return jsonResponse(conversationEventPageSchema, report);
823
924
  });
925
+ app.get("/:conversationId/outline", validateRequest("param", conversationParamsSchema, "Invalid route parameters."), async (context) => {
926
+ const { conversationId } = context.req.valid("param");
927
+ const viewer = context.get("viewer");
928
+ const outline = await readConversationOutline(conversationId, viewer ? { viewer } : void 0);
929
+ if (!outline) throwApiError(404, "Conversation not found.");
930
+ return jsonResponse(conversationOutlineSchema, outline);
931
+ });
824
932
  app.get("/:conversationId/agents", validateRequest("param", conversationParamsSchema, "Invalid route parameters."), async (context) => {
825
933
  const { conversationId } = context.req.valid("param");
826
934
  const viewer = context.get("viewer");
@@ -890,7 +998,10 @@ function createConversationRoutes(options) {
890
998
  });
891
999
  const report = await readConversationDetail(conversationId, {
892
1000
  ...query,
893
- ...version ? { state: version.state } : void 0,
1001
+ ...version ? { stored: {
1002
+ record: version.record,
1003
+ state: version.state
1004
+ } } : void 0,
894
1005
  ...viewerOptions
895
1006
  });
896
1007
  if (!report) throwApiError(404, "Conversation not found.");
@@ -902,6 +1013,239 @@ function createConversationRoutes(options) {
902
1013
  });
903
1014
  return app;
904
1015
  }
1016
+ // src/api/board/columns.ts
1017
+ const DONE_WINDOW_MS = 216e5;
1018
+ /** Choose the column of a code change that Junior created. */
1019
+ function codeChangeColumn(args) {
1020
+ if (args.state === "merged") return args.mergedAtMs !== void 0 && args.nowMs - args.mergedAtMs <= DONE_WINDOW_MS ? "done" : void 0;
1021
+ if (args.state === "closed") return void 0;
1022
+ return args.hasReadyNotice ? "ready" : "in_progress";
1023
+ }
1024
+ /** Choose the column of a ticket linked to a Conversation. */
1025
+ function ticketColumn(args) {
1026
+ if (args.status === "closed") return args.nowMs - args.updatedAtMs <= DONE_WINDOW_MS ? "done" : void 0;
1027
+ if (args.status !== "open") return void 0;
1028
+ return args.working ? "in_progress" : "planned";
1029
+ }
1030
+ // src/api/board/read.ts
1031
+ /** Root Conversations with activity in this window feed the Board. */
1032
+ const ACTIVE_WINDOW_MS = 12096e5;
1033
+ /** Bound the Board to the viewer's most recent root Conversations. */
1034
+ const ROOT_LIMIT = 200;
1035
+ function parentOf(nodes, node) {
1036
+ return node.parentConversationId ? nodes.get(node.parentConversationId) : void 0;
1037
+ }
1038
+ /**
1039
+ * A card belongs to the nearest root or Thread. People do not message a
1040
+ * Task, so its work shows on its parent. A row from an older deploy has no
1041
+ * kind; a child without a kind is treated as a Task. A Conversation shows
1042
+ * only while it and every ancestor are unarchived.
1043
+ */
1044
+ function homeId(nodes, conversationId) {
1045
+ const start = nodes.get(conversationId);
1046
+ for (let node = start; node; node = parentOf(nodes, node)) if (node.archived) return void 0;
1047
+ let node = start;
1048
+ while (node && (node.kind === "task" || !node.kind && node.parentConversationId)) node = parentOf(nodes, node);
1049
+ return node?.conversationId;
1050
+ }
1051
+ function rootOf(nodes, node) {
1052
+ let current = node;
1053
+ for (let parent = parentOf(nodes, current); parent; parent = parentOf(nodes, parent)) current = parent;
1054
+ return current;
1055
+ }
1056
+ async function readViewerTrees(userId, nowMs) {
1057
+ const db = getDb();
1058
+ const rootIds = (await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(conversationIsMemberRoot({ userId }), isNull(juniorConversations.parentConversationId), isNull(juniorConversations.archivedAt), isNull(juniorConversations.quickQuestionAt), gte(juniorConversations.lastActivityAt, /* @__PURE__ */ new Date(nowMs - ACTIVE_WINDOW_MS)))).orderBy(desc(juniorConversations.lastActivityAt)).limit(ROOT_LIMIT)).map((row) => row.conversationId);
1059
+ if (rootIds.length === 0) return {
1060
+ nodes: /* @__PURE__ */ new Map(),
1061
+ rootIds
1062
+ };
1063
+ const rows = await db.select({
1064
+ archivedAt: juniorConversations.archivedAt,
1065
+ conversationId: juniorConversations.conversationId,
1066
+ createdAt: juniorConversations.createdAt,
1067
+ kind: juniorConversations.kind,
1068
+ parentConversationId: juniorConversations.parentConversationId,
1069
+ status: juniorConversations.executionStatus,
1070
+ title: juniorConversations.title
1071
+ }).from(juniorConversations).where(or(inArray(juniorConversations.conversationId, rootIds), inArray(juniorConversations.rootConversationId, rootIds)));
1072
+ return {
1073
+ nodes: new Map(rows.map((row) => [row.conversationId, {
1074
+ archived: row.archivedAt !== null,
1075
+ conversationId: row.conversationId,
1076
+ createdAtMs: row.createdAt.getTime(),
1077
+ kind: row.kind,
1078
+ parentConversationId: row.parentConversationId,
1079
+ status: row.status,
1080
+ title: row.title
1081
+ }])),
1082
+ rootIds
1083
+ };
1084
+ }
1085
+ /**
1086
+ * Read the viewer's Board: the code changes and tickets of their recent
1087
+ * Conversations, each in one column. See `./columns` for the column rules.
1088
+ */
1089
+ async function readBoard(args) {
1090
+ const db = getDb();
1091
+ const { nodes, rootIds } = await readViewerTrees(args.userId, args.nowMs);
1092
+ const treeIds = [...nodes.keys()];
1093
+ if (treeIds.length === 0) return {
1094
+ cards: [],
1095
+ doneWindowHours: 6
1096
+ };
1097
+ const doneSince = /* @__PURE__ */ new Date(args.nowMs - 216e5);
1098
+ const [codeChanges, ticketRows, needsViewerRows, participants] = await Promise.all([
1099
+ db.select({
1100
+ conversationIds: juniorCodeChanges.conversationIds,
1101
+ id: juniorCodeChanges.id,
1102
+ mergedAt: juniorCodeChanges.mergedAt,
1103
+ number: juniorCodeChanges.number,
1104
+ repository: juniorCodeRepositories.name,
1105
+ state: juniorCodeChanges.state,
1106
+ title: juniorCodeChanges.title,
1107
+ updatedAt: juniorCodeChanges.updatedAt,
1108
+ url: juniorCodeChanges.url
1109
+ }).from(juniorCodeChanges).innerJoin(juniorCodeRepositories, eq(juniorCodeRepositories.id, juniorCodeChanges.repositoryId)).where(and(or(eq(juniorCodeChanges.state, "open"), and(eq(juniorCodeChanges.state, "merged"), gte(juniorCodeChanges.mergedAt, doneSince))), arrayOverlaps(juniorCodeChanges.conversationIds, treeIds))),
1110
+ db.select({
1111
+ annotation: juniorConversationAnnotations.annotation,
1112
+ conversationId: juniorConversationAnnotations.conversationId,
1113
+ key: juniorConversationAnnotations.key,
1114
+ plugin: juniorConversationAnnotations.plugin,
1115
+ updatedAt: juniorConversationAnnotations.updatedAt
1116
+ }).from(juniorConversationAnnotations).where(and(inArray(juniorConversationAnnotations.conversationId, treeIds), sql`${juniorConversationAnnotations.annotation}->>'objectType' = 'task'`)),
1117
+ db.selectDistinct({ conversationId: juniorReviewItemConversations.conversationId }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).where(and(inArray(juniorReviewItemConversations.conversationId, treeIds), reviewItemNeedsUser(args.userId))),
1118
+ readConversationParticipants(db, rootIds)
1119
+ ]);
1120
+ const codeChangeUrls = codeChanges.flatMap((change) => change.state === "open" && change.url ? [change.url] : []);
1121
+ const readyUrls = new Set(codeChangeUrls.length === 0 ? [] : (await db.select({ subjectId: juniorReviewItems.subjectId }).from(juniorReviewItems).where(and(eq(juniorReviewItems.status, "open"), eq(juniorReviewItems.kind, "notice"), like(juniorReviewItems.dedupeKey, `${PLUGIN_REVIEW_ITEM_KEY_PREFIX}%`), inArray(juniorReviewItems.subjectId, codeChangeUrls)))).flatMap((row) => row.subjectId ? [row.subjectId] : []));
1122
+ const homes = /* @__PURE__ */ new Map();
1123
+ const workingHomes = /* @__PURE__ */ new Set();
1124
+ const needsViewerHomes = /* @__PURE__ */ new Set();
1125
+ for (const node of nodes.values()) {
1126
+ if (node.status !== "running" && node.status !== "pending") continue;
1127
+ const home = homeId(nodes, node.conversationId);
1128
+ if (home) workingHomes.add(home);
1129
+ }
1130
+ for (const row of needsViewerRows) {
1131
+ const home = homeId(nodes, row.conversationId);
1132
+ if (home) needsViewerHomes.add(home);
1133
+ }
1134
+ const homeFor = (conversationIds) => {
1135
+ let node;
1136
+ for (const conversationId of conversationIds) {
1137
+ const candidateId = homeId(nodes, conversationId);
1138
+ const candidate = candidateId ? nodes.get(candidateId) : void 0;
1139
+ if (!candidate) continue;
1140
+ if (!node || candidate.createdAtMs < node.createdAtMs || candidate.createdAtMs === node.createdAtMs && candidate.conversationId < node.conversationId) node = candidate;
1141
+ }
1142
+ if (!node) return void 0;
1143
+ const id = node.conversationId;
1144
+ const cached = homes.get(id);
1145
+ if (cached) return cached;
1146
+ const root = rootOf(nodes, node);
1147
+ const home = {
1148
+ conversation: {
1149
+ conversationId: id,
1150
+ ...node.title ? { title: node.title } : void 0,
1151
+ ...root !== node && root.title ? { rootTitle: root.title } : void 0
1152
+ },
1153
+ needsViewer: needsViewerHomes.has(id),
1154
+ participants: participants.get(root.conversationId) ?? [],
1155
+ working: workingHomes.has(id)
1156
+ };
1157
+ homes.set(id, home);
1158
+ return home;
1159
+ };
1160
+ const cards = [];
1161
+ for (const change of codeChanges) {
1162
+ const home = homeFor(change.conversationIds);
1163
+ if (!home) continue;
1164
+ const mergedAtMs = change.mergedAt?.getTime();
1165
+ const column = codeChangeColumn({
1166
+ hasReadyNotice: Boolean(change.url && readyUrls.has(change.url)),
1167
+ ...mergedAtMs !== void 0 ? { mergedAtMs } : void 0,
1168
+ nowMs: args.nowMs,
1169
+ state: change.state
1170
+ });
1171
+ if (!column) continue;
1172
+ const label = `${change.repository}#${change.number}`;
1173
+ cards.push({
1174
+ column,
1175
+ conversation: home.conversation,
1176
+ key: `code_change:${change.id}`,
1177
+ label,
1178
+ needsViewer: home.needsViewer,
1179
+ objectType: "code_change",
1180
+ participants: home.participants,
1181
+ status: change.state,
1182
+ title: change.title ?? label,
1183
+ updatedAt: (change.mergedAt ?? change.updatedAt).toISOString(),
1184
+ ...change.url ? { url: change.url } : void 0,
1185
+ working: home.working
1186
+ });
1187
+ }
1188
+ const tickets = /* @__PURE__ */ new Map();
1189
+ for (const row of ticketRows) {
1190
+ const key = `${row.plugin}:${row.key}`;
1191
+ const current = tickets.get(key);
1192
+ if (!current) {
1193
+ tickets.set(key, {
1194
+ conversationIds: /* @__PURE__ */ new Set([row.conversationId]),
1195
+ latest: row
1196
+ });
1197
+ continue;
1198
+ }
1199
+ current.conversationIds.add(row.conversationId);
1200
+ if (row.updatedAt > current.latest.updatedAt) current.latest = row;
1201
+ }
1202
+ for (const [key, ticket] of tickets) {
1203
+ const parsed = conversationAnnotationInputSchema.safeParse(ticket.latest.annotation);
1204
+ if (!parsed.success) continue;
1205
+ const annotation = parsed.data;
1206
+ const status = annotation.status;
1207
+ if (!status) continue;
1208
+ const home = homeFor(ticket.conversationIds);
1209
+ if (!home) continue;
1210
+ const column = ticketColumn({
1211
+ nowMs: args.nowMs,
1212
+ status,
1213
+ updatedAtMs: ticket.latest.updatedAt.getTime(),
1214
+ working: home.working
1215
+ });
1216
+ if (!column) continue;
1217
+ const title = annotation.kind === "object" ? annotation.title : annotation.description ?? annotation.label;
1218
+ cards.push({
1219
+ column,
1220
+ conversation: home.conversation,
1221
+ key: `ticket:${key}`,
1222
+ label: annotation.label,
1223
+ needsViewer: home.needsViewer,
1224
+ objectType: "task",
1225
+ participants: home.participants,
1226
+ status,
1227
+ title,
1228
+ updatedAt: ticket.latest.updatedAt.toISOString(),
1229
+ ...annotation.url ? { url: annotation.url } : void 0,
1230
+ working: home.working
1231
+ });
1232
+ }
1233
+ cards.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
1234
+ return {
1235
+ cards,
1236
+ doneWindowHours: 6
1237
+ };
1238
+ }
1239
+ // src/api/board/routes.ts
1240
+ /** Create the viewer's Board API. */
1241
+ function createBoardRoutes() {
1242
+ const app = new Hono();
1243
+ app.get("/", requireViewer, async (context) => jsonResponse(boardReportSchema, await readBoard({
1244
+ nowMs: Date.now(),
1245
+ userId: context.get("viewer").id
1246
+ }), { headers: { "cache-control": "private, no-store" } }));
1247
+ return app;
1248
+ }
905
1249
  // src/api/code/overview.ts
906
1250
  const DAY_MS = 864e5;
907
1251
  const WINDOW_DAYS = 30;
@@ -1409,17 +1753,22 @@ async function readSettings(userId) {
1409
1753
  const db = getDb();
1410
1754
  const nowMs = Date.now();
1411
1755
  const schedule = await readNotificationSchedule(db, userId);
1412
- const [{ source, timezone }, subscriptions] = await Promise.all([resolveNotificationTimezone({
1413
- db,
1414
- nowMs,
1415
- schedule,
1416
- userId
1417
- }), listPushSubscriptions(db, userId)]);
1756
+ const [{ source, timezone }, subscriptions, slackPausedNow] = await Promise.all([
1757
+ resolveNotificationTimezone({
1758
+ db,
1759
+ nowMs,
1760
+ schedule,
1761
+ userId
1762
+ }),
1763
+ listPushSubscriptions(db, userId),
1764
+ isPausedBySlack(db, userId, nowMs)
1765
+ ]);
1418
1766
  const config = readWebPushConfig();
1419
1767
  return notificationSettingsSchema.parse({
1420
1768
  ...config ? { publicKey: config.publicKey } : void 0,
1421
1769
  deviceCount: subscriptions.length,
1422
1770
  schedule,
1771
+ slackPausedNow,
1423
1772
  timezone,
1424
1773
  timezoneSource: source
1425
1774
  });
@@ -1428,7 +1777,7 @@ async function settingsResponse(userId) {
1428
1777
  return jsonResponse(notificationSettingsSchema, await readSettings(userId));
1429
1778
  }
1430
1779
  /**
1431
- * Create authenticated routes for the viewer's phone notifications: browser
1780
+ * Create authenticated routes for the viewer's push notifications: browser
1432
1781
  * subscriptions, notification hours, and a test notification.
1433
1782
  */
1434
1783
  function createNotificationRoutes() {
@@ -1440,7 +1789,7 @@ function createNotificationRoutes() {
1440
1789
  return await settingsResponse(viewer.id);
1441
1790
  });
1442
1791
  app.post("/subscriptions", requireViewer, validateRequest("json", pushSubscriptionBodySchema, "Invalid subscription."), async (context) => {
1443
- if (!readWebPushConfig()) throwApiError(503, "Phone notifications are not configured.");
1792
+ if (!readWebPushConfig()) throwApiError(503, "Push notifications are not configured.");
1444
1793
  const viewer = context.get("viewer");
1445
1794
  const { endpoint, keys } = context.req.valid("json");
1446
1795
  await savePushSubscription(getDb(), viewer.id, {
@@ -1458,7 +1807,7 @@ function createNotificationRoutes() {
1458
1807
  });
1459
1808
  app.post("/test", requireViewer, async (context) => {
1460
1809
  const config = readWebPushConfig();
1461
- if (!config) throwApiError(503, "Phone notifications are not configured.");
1810
+ if (!config) throwApiError(503, "Push notifications are not configured.");
1462
1811
  const result = await sendPushNotificationToUser({
1463
1812
  config,
1464
1813
  db: getDb(),
@@ -1907,22 +2256,94 @@ async function readPeopleCode(email) {
1907
2256
  }
1908
2257
  return await readPersonCodeOverview({ userId: subject.id });
1909
2258
  }
1910
- const peopleTreeConversation = alias(juniorConversations, "people_tree_conversation");
1911
- const peopleRootConversation = alias(juniorConversations, "people_root_conversation");
1912
- const peopleRootIdentity = alias(juniorIdentities, "people_root_identity");
1913
- const peopleTreeAggregateColumns = conversationAggregateColumns({
1914
- metrics: peopleTreeConversation,
1915
- roots: juniorConversations
1916
- });
2259
+ function turnMetricSum(metric) {
2260
+ return sql`SUM(${juniorConversationMetrics.value}) FILTER (
2261
+ WHERE ${juniorConversationMetrics.metric} = ${metric}
2262
+ )`;
2263
+ }
2264
+ /** Sum the spend of Turn metric rows read straight from their table. */
2265
+ const turnMetricColumns = { costUsd: sql`${turnMetricSum("cost_usd")}::double precision` };
2266
+ /** Root Conversation of a person's Turn, for status, location, and surface. */
2267
+ const turnRoot = alias(juniorConversations, "person_turn_root");
1917
2268
  /**
1918
- * Roll metrics through roots without counting a same-actor child twice.
2269
+ * Read one row per Turn metric of each verified person, with the root
2270
+ * Conversation of the Turn.
1919
2271
  *
1920
- * A child contributes its own metrics only when its owning root belongs to a
1921
- * different actor.
2272
+ * People counts and spend come only from Turns. The Actor that started a
2273
+ * Conversation does not matter here.
1922
2274
  */
1923
- function peopleTreeMetricsJoin() {
1924
- const rootOwnedByActor = getDb().select({ conversationId: peopleRootConversation.conversationId }).from(peopleRootConversation).innerJoin(peopleRootIdentity, eq(peopleRootIdentity.id, peopleRootConversation.actorIdentityId)).where(and(eq(peopleRootConversation.conversationId, juniorConversations.rootConversationId), isNull(peopleRootConversation.parentConversationId), eq(peopleRootConversation.rootConversationId, peopleRootConversation.conversationId), eq(peopleRootIdentity.emailNormalized, juniorUsers.primaryEmailNormalized), eq(peopleRootIdentity.emailVerified, true)));
1925
- return and(eq(peopleTreeConversation.rootConversationId, juniorConversations.rootConversationId), or(eq(juniorConversations.rootConversationId, juniorConversations.conversationId), and(eq(peopleTreeConversation.conversationId, juniorConversations.conversationId), notExists(rootOwnedByActor))));
2275
+ function personTurns(email) {
2276
+ return getDb().select({
2277
+ conversationId: sql`${juniorConversationMetrics.conversationId}`.as("turn_conversation_id"),
2278
+ email: sql`${juniorUsers.primaryEmailNormalized}`.as("email"),
2279
+ fullName: juniorUsers.displayName,
2280
+ metric: juniorConversationMetrics.metric,
2281
+ occurredAt: juniorConversationMetrics.occurredAt,
2282
+ rootConversationId: sql`coalesce(
2283
+ ${juniorConversations.rootConversationId},
2284
+ ${juniorConversations.conversationId}
2285
+ )`.as("turn_root_conversation_id"),
2286
+ lastRootTurnAt: sql`max(${juniorConversationMetrics.occurredAt}) OVER (
2287
+ PARTITION BY ${juniorUsers.id}, coalesce(
2288
+ ${juniorConversations.rootConversationId},
2289
+ ${juniorConversations.conversationId}
2290
+ )
2291
+ )`.as("last_root_turn_at"),
2292
+ slackUserId: sql`CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.providerSubjectId} END`.as("slack_user_id"),
2293
+ slackUserName: sql`CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.handle} END`.as("slack_user_name"),
2294
+ userId: sql`${juniorUsers.id}`.as("user_id"),
2295
+ value: juniorConversationMetrics.value
2296
+ }).from(juniorConversationMetrics).innerJoin(juniorConversations, eq(juniorConversations.conversationId, juniorConversationMetrics.conversationId)).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationMetrics.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(verifiedActorWhere(email)).as("person_turns");
2297
+ }
2298
+ /** Join a person's Turn rows to the root Conversation of each Turn. */
2299
+ function turnRootJoin(turns) {
2300
+ return eq(turnRoot.conversationId, turns.rootConversationId);
2301
+ }
2302
+ function turnSum(turns, metric) {
2303
+ return sql`SUM(${turns.value}) FILTER (WHERE ${turns.metric} = ${metric})`;
2304
+ }
2305
+ /**
2306
+ * Aggregate a person's Turn rows. A Conversation counts once for each person
2307
+ * who ran a Turn in it. Child Conversation Turns count for the root.
2308
+ *
2309
+ * Active and failed read the root's current status. They count only in the
2310
+ * bucket of the person's last Turn in that root, so a status change does not
2311
+ * mark every past day.
2312
+ */
2313
+ function turnAggregateColumns(turns) {
2314
+ const roots = sql`COUNT(DISTINCT ${turns.rootConversationId})`;
2315
+ const lastTurn = sql`${turns.occurredAt} = ${turns.lastRootTurnAt}`;
2316
+ return {
2317
+ active: sql`${roots} FILTER (
2318
+ WHERE ${lastTurn} AND ${turnRoot.executionStatus} NOT IN ('idle', 'failed')
2319
+ )::integer`,
2320
+ conversations: sql`${roots}::integer`,
2321
+ costUsd: sql`${turnSum(turns, "cost_usd")}::double precision`,
2322
+ durationMs: sql`COALESCE(${turnSum(turns, "duration_ms")}, 0)::double precision`,
2323
+ failed: sql`${roots} FILTER (
2324
+ WHERE ${lastTurn}
2325
+ AND ${turnRoot.executionStatus} = 'failed'
2326
+ AND ${turnRoot.stoppedAt} IS NULL
2327
+ )::integer`,
2328
+ tokens: sql`${turnSum(turns, "total_tokens")}::double precision`
2329
+ };
2330
+ }
2331
+ /** Format the UTC day or hour of a person's Turn rows for activity buckets. */
2332
+ function turnBucket(turns, unit) {
2333
+ const format = unit === "day" ? "YYYY-MM-DD" : "YYYY-MM-DD\"T\"HH24";
2334
+ return sql`TO_CHAR(${turns.occurredAt} AT TIME ZONE 'UTC', ${sql.raw(`'${format}'`)})`;
2335
+ }
2336
+ /** Select the identity fields and Turn range of a grouped person row. */
2337
+ function turnPersonColumns(turns) {
2338
+ return {
2339
+ activeDays: sql`COUNT(DISTINCT (${turns.occurredAt} AT TIME ZONE 'UTC')::date)::integer`,
2340
+ email: turns.email,
2341
+ firstSeenAt: sql`MIN(${turns.occurredAt})`.mapWith(juniorConversationMetrics.occurredAt),
2342
+ fullName: turns.fullName,
2343
+ lastSeenAt: sql`MAX(${turns.occurredAt})`.mapWith(juniorConversationMetrics.occurredAt),
2344
+ slackUserId: sql`MAX(${turns.slackUserId})`,
2345
+ slackUserName: sql`MAX(${turns.slackUserName})`
2346
+ };
1926
2347
  }
1927
2348
  /** Normalize emails before matching people API rows. */
1928
2349
  function normalizeEmail$1(email) {
@@ -1996,20 +2417,13 @@ function verifiedActorWhere(email) {
1996
2417
  const normalizedEmail = normalizeEmail$1(email);
1997
2418
  return and(eq(juniorIdentities.kind, "user"), eq(juniorIdentities.emailVerified, true), sql`${juniorUsers.primaryEmailNormalized} IS NOT NULL`, normalizedEmail ? eq(juniorUsers.primaryEmailNormalized, normalizedEmail) : void 0);
1998
2419
  }
1999
- /**
2000
- * Read the Slack user fields for a grouped person row.
2001
- *
2002
- * Web identities use the email as the provider subject, so only Slack
2003
- * identities can supply these fields.
2004
- */
2005
- function slackActorColumns() {
2006
- return {
2007
- slackUserId: sql`MAX(CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.providerSubjectId} END)`,
2008
- slackUserName: sql`MAX(CASE WHEN ${juniorIdentities.provider} = 'slack' THEN ${juniorIdentities.handle} END)`
2009
- };
2010
- }
2011
- /** Read only the recent conversation rows required by a People profile. */
2420
+ /** Read the Conversations where a person ran a Turn, by their last Turn. */
2012
2421
  async function recentActorRows(email) {
2422
+ const turns = personTurns(email);
2423
+ const lastTurns = getDb().select({
2424
+ conversationId: turns.conversationId,
2425
+ lastTurnAt: sql`max(${turns.occurredAt})`.as("last_turn_at")
2426
+ }).from(turns).groupBy(turns.conversationId).as("person_last_turns");
2013
2427
  return getDb().select({
2014
2428
  channelName: juniorConversations.channelName,
2015
2429
  conversationId: juniorConversations.conversationId,
@@ -2031,7 +2445,7 @@ async function recentActorRows(email) {
2031
2445
  title: juniorConversations.title,
2032
2446
  updatedAt: juniorConversations.updatedAt,
2033
2447
  usage: juniorConversations.usage
2034
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(verifiedActorWhere(email)).orderBy(desc(juniorConversations.lastActivityAt), asc(juniorConversations.conversationId)).limit(25);
2448
+ }).from(lastTurns).innerJoin(juniorConversations, eq(juniorConversations.conversationId, lastTurns.conversationId)).leftJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).leftJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).orderBy(desc(lastTurns.lastTurnAt), asc(juniorConversations.conversationId)).limit(25);
2035
2449
  }
2036
2450
  // src/api/people/list.query.ts
2037
2451
  const DIRECTORY_ACTIVITY_DAYS = 90;
@@ -2048,7 +2462,6 @@ function emptyDirectoryDay(date) {
2048
2462
  }
2049
2463
  function emptyBucket() {
2050
2464
  return {
2051
- conversations: 0,
2052
2465
  costUsd: 0,
2053
2466
  durationMs: 0
2054
2467
  };
@@ -2084,13 +2497,12 @@ function sumBuckets(buckets, startMs, endMs, keyFor, stepMs) {
2084
2497
  for (let cursor = startMs; cursor <= endMs; cursor += stepMs) {
2085
2498
  const bucket = buckets.get(keyFor(cursor));
2086
2499
  if (!bucket) continue;
2087
- total.conversations += bucket.conversations;
2088
2500
  total.costUsd = addUsd$1(total.costUsd, bucket.costUsd);
2089
2501
  total.durationMs += bucket.durationMs;
2090
2502
  }
2091
2503
  return total;
2092
2504
  }
2093
- function rangeWindow(buckets, nowMs, range) {
2505
+ function rangeWindow(buckets, nowMs, range, conversations) {
2094
2506
  if (range === 1) {
2095
2507
  const current = trailingUtcHourWindow(nowMs, 24);
2096
2508
  const priorEndMs = current.start.getTime() - HOUR_MS$1;
@@ -2098,7 +2510,7 @@ function rangeWindow(buckets, nowMs, range) {
2098
2510
  const currentTotals = sumBuckets(buckets, current.start.getTime(), current.end.getTime(), utcHourKey, HOUR_MS$1);
2099
2511
  const priorTotals = sumBuckets(buckets, priorStartMs, priorEndMs, utcHourKey, HOUR_MS$1);
2100
2512
  return {
2101
- conversations: currentTotals.conversations,
2513
+ conversations,
2102
2514
  costUsd: currentTotals.costUsd,
2103
2515
  durationMs: currentTotals.durationMs,
2104
2516
  priorCostUsd: priorTotals.costUsd
@@ -2110,101 +2522,94 @@ function rangeWindow(buckets, nowMs, range) {
2110
2522
  const currentTotals = sumBuckets(buckets, current.start.getTime(), current.end.getTime(), utcDayKey, DAY_MS$1);
2111
2523
  const priorTotals = sumBuckets(buckets, priorStartMs, priorEndMs, utcDayKey, DAY_MS$1);
2112
2524
  return {
2113
- conversations: currentTotals.conversations,
2525
+ conversations,
2114
2526
  costUsd: currentTotals.costUsd,
2115
2527
  durationMs: currentTotals.durationMs,
2116
2528
  priorCostUsd: priorTotals.costUsd
2117
2529
  };
2118
2530
  }
2119
2531
  function buildActorWindows(args) {
2532
+ const { conversations, dayBuckets, hourBuckets, nowMs } = args;
2120
2533
  return {
2121
- 1: rangeWindow(args.hourBuckets, args.nowMs, 1),
2122
- 7: rangeWindow(args.dayBuckets, args.nowMs, 7),
2123
- 30: rangeWindow(args.dayBuckets, args.nowMs, 30),
2124
- 90: rangeWindow(args.dayBuckets, args.nowMs, 90)
2534
+ 1: rangeWindow(hourBuckets, nowMs, 1, conversations[1]),
2535
+ 7: rangeWindow(dayBuckets, nowMs, 7, conversations[7]),
2536
+ 30: rangeWindow(dayBuckets, nowMs, 30, conversations[30]),
2537
+ 90: rangeWindow(dayBuckets, nowMs, 90, conversations[90])
2125
2538
  };
2126
2539
  }
2127
- /** Load the complete People directory with grouping and metrics owned by SQL. */
2540
+ /** Start of the current period of each directory range. */
2541
+ function rangeStart(nowMs, range) {
2542
+ return range === 1 ? trailingUtcHourWindow(nowMs, 24).start : trailingUtcDayWindow(nowMs, range).start;
2543
+ }
2544
+ function metricBuckets(rows) {
2545
+ const byEmail = /* @__PURE__ */ new Map();
2546
+ for (const row of rows) {
2547
+ const buckets = byEmail.get(row.email) ?? /* @__PURE__ */ new Map();
2548
+ byEmail.set(row.email, buckets);
2549
+ buckets.set(row.date, {
2550
+ costUsd: row.costUsd ?? 0,
2551
+ durationMs: row.durationMs
2552
+ });
2553
+ }
2554
+ return byEmail;
2555
+ }
2556
+ /**
2557
+ * Load the complete People directory with grouping and metrics owned by SQL.
2558
+ *
2559
+ * Every count and total comes from Turns. A person counts a Conversation when
2560
+ * they ran a Turn in it, whoever started it.
2561
+ */
2128
2562
  async function readPeopleListFromSql() {
2129
2563
  const nowMs = Date.now();
2130
2564
  const { end, start } = trailingUtcDayWindow(nowMs, DIRECTORY_ACTIVITY_DAYS);
2131
- const activityDate = sql`TO_CHAR(
2132
- ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
2133
- 'YYYY-MM-DD'
2134
- )`;
2135
- const activityHour = sql`TO_CHAR(
2136
- ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
2137
- 'YYYY-MM-DD"T"HH24'
2138
- )`;
2139
2565
  const hourWindow = trailingUtcHourWindow(nowMs, 168);
2140
2566
  const sixHourWindow = trailingUtcSixHourWindow(nowMs);
2141
2567
  const dayMetricStart = trailingUtcDayWindow(nowMs, DAY_METRIC_LOOKBACK).start;
2142
2568
  const hourMetricStart = trailingUtcHourWindow(nowMs, HOUR_METRIC_LOOKBACK).start;
2143
- const metricsJoin = peopleTreeMetricsJoin();
2144
- const activitySixHour = sql`TO_CHAR(
2145
- date_trunc('day', ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC')
2146
- + (FLOOR(EXTRACT(HOUR FROM ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC') / 6) * INTERVAL '6 hours'),
2569
+ const turns = personTurns();
2570
+ const { active, conversations, costUsd, durationMs, failed, tokens } = turnAggregateColumns(turns);
2571
+ const day = turnBucket(turns, "day");
2572
+ const hour = turnBucket(turns, "hour");
2573
+ const sixHour = sql`TO_CHAR(
2574
+ date_trunc('day', ${turns.occurredAt} AT TIME ZONE 'UTC')
2575
+ + (FLOOR(EXTRACT(HOUR FROM ${turns.occurredAt} AT TIME ZONE 'UTC') / 6) * INTERVAL '6 hours'),
2147
2576
  'YYYY-MM-DD"T"HH24'
2148
2577
  )`;
2149
- const [rows, activityRows, activityHourRows, activitySixHourRows, dayMetricRows, hourMetricRows] = await Promise.all([
2150
- getDb().select({
2151
- email: juniorUsers.primaryEmailNormalized,
2152
- fullName: juniorUsers.displayName,
2153
- ...slackActorColumns(),
2154
- activeDays: conversationActiveDaysColumn(),
2155
- ...peopleTreeAggregateColumns,
2156
- ...conversationRangeColumns()
2157
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(verifiedActorWhere()).groupBy(juniorUsers.primaryEmailNormalized, juniorUsers.displayName),
2158
- getDb().select({
2159
- activePeople: sql`COUNT(DISTINCT ${juniorUsers.id})::int`,
2160
- conversations: sql`COUNT(*)::int`,
2161
- date: activityDate
2162
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(verifiedActorWhere(), gte(juniorConversations.lastActivityAt, start))).groupBy(activityDate),
2163
- getDb().select({
2164
- activePeople: sql`COUNT(DISTINCT ${juniorUsers.id})::int`,
2165
- conversations: sql`COUNT(*)::int`,
2166
- date: activityHour
2167
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(verifiedActorWhere(), gte(juniorConversations.lastActivityAt, hourWindow.start))).groupBy(activityHour),
2168
- getDb().select({
2169
- activePeople: sql`COUNT(DISTINCT ${juniorUsers.id})::int`,
2170
- conversations: sql`COUNT(*)::int`,
2171
- date: activitySixHour
2172
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(and(verifiedActorWhere(), gte(juniorConversations.lastActivityAt, sixHourWindow.start))).groupBy(activitySixHour),
2578
+ const rangeConversations = (range) => sql`COUNT(DISTINCT ${turns.rootConversationId}) FILTER (
2579
+ WHERE ${turns.occurredAt} >= ${rangeStart(nowMs, range).toISOString()}::timestamptz
2580
+ )::integer`;
2581
+ const spendRows = (since, bucket) => getDb().select({
2582
+ email: turns.email,
2583
+ date: bucket,
2584
+ costUsd,
2585
+ durationMs
2586
+ }).from(turns).where(gte(turns.occurredAt, since)).groupBy(turns.email, bucket);
2587
+ const activityRows = (since, bucket) => getDb().select({
2588
+ activePeople: sql`COUNT(DISTINCT ${turns.userId})::int`,
2589
+ conversations,
2590
+ date: bucket
2591
+ }).from(turns).where(gte(turns.occurredAt, since)).groupBy(bucket);
2592
+ const [rows, activityDayRows, activityHourRows, activitySixHourRows, daySpendRows, hourSpendRows] = await Promise.all([
2173
2593
  getDb().select({
2174
- email: juniorUsers.primaryEmailNormalized,
2175
- date: activityDate,
2176
- conversations: peopleTreeAggregateColumns.conversations,
2177
- costUsd: peopleTreeAggregateColumns.costUsd,
2178
- durationMs: peopleTreeAggregateColumns.durationMs
2179
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(and(verifiedActorWhere(), gte(juniorConversations.lastActivityAt, dayMetricStart))).groupBy(juniorUsers.primaryEmailNormalized, activityDate),
2180
- getDb().select({
2181
- email: juniorUsers.primaryEmailNormalized,
2182
- date: activityHour,
2183
- conversations: peopleTreeAggregateColumns.conversations,
2184
- costUsd: peopleTreeAggregateColumns.costUsd,
2185
- durationMs: peopleTreeAggregateColumns.durationMs
2186
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(and(verifiedActorWhere(), gte(juniorConversations.lastActivityAt, hourMetricStart))).groupBy(juniorUsers.primaryEmailNormalized, activityHour)
2594
+ ...turnPersonColumns(turns),
2595
+ active,
2596
+ conversations,
2597
+ durationMs,
2598
+ failed,
2599
+ tokens,
2600
+ conversations1: rangeConversations(1),
2601
+ conversations7: rangeConversations(7),
2602
+ conversations30: rangeConversations(30),
2603
+ conversations90: rangeConversations(90)
2604
+ }).from(turns).innerJoin(turnRoot, turnRootJoin(turns)).groupBy(turns.email, turns.fullName),
2605
+ activityRows(start, day),
2606
+ activityRows(hourWindow.start, hour),
2607
+ activityRows(sixHourWindow.start, sixHour),
2608
+ spendRows(dayMetricStart, day),
2609
+ spendRows(hourMetricStart, hour)
2187
2610
  ]);
2188
- const dayBucketsByEmail = /* @__PURE__ */ new Map();
2189
- for (const row of dayMetricRows) {
2190
- const buckets = dayBucketsByEmail.get(row.email) ?? /* @__PURE__ */ new Map();
2191
- buckets.set(row.date, {
2192
- conversations: row.conversations,
2193
- costUsd: row.costUsd ?? 0,
2194
- durationMs: row.durationMs
2195
- });
2196
- dayBucketsByEmail.set(row.email, buckets);
2197
- }
2198
- const hourBucketsByEmail = /* @__PURE__ */ new Map();
2199
- for (const row of hourMetricRows) {
2200
- const buckets = hourBucketsByEmail.get(row.email) ?? /* @__PURE__ */ new Map();
2201
- buckets.set(row.date, {
2202
- conversations: row.conversations,
2203
- costUsd: row.costUsd ?? 0,
2204
- durationMs: row.durationMs
2205
- });
2206
- hourBucketsByEmail.set(row.email, buckets);
2207
- }
2611
+ const dayBucketsByEmail = metricBuckets(daySpendRows);
2612
+ const hourBucketsByEmail = metricBuckets(hourSpendRows);
2208
2613
  const people = rows.map((row) => {
2209
2614
  const actor = {
2210
2615
  email: row.email,
@@ -2222,6 +2627,12 @@ async function readPeopleListFromSql() {
2222
2627
  lastSeenAt: row.lastSeenAt.toISOString(),
2223
2628
  actor,
2224
2629
  windows: buildActorWindows({
2630
+ conversations: {
2631
+ 1: row.conversations1,
2632
+ 7: row.conversations7,
2633
+ 30: row.conversations30,
2634
+ 90: row.conversations90
2635
+ },
2225
2636
  dayBuckets: dayBucketsByEmail.get(row.email) ?? /* @__PURE__ */ new Map(),
2226
2637
  hourBuckets: hourBucketsByEmail.get(row.email) ?? /* @__PURE__ */ new Map(),
2227
2638
  nowMs
@@ -2230,7 +2641,7 @@ async function readPeopleListFromSql() {
2230
2641
  };
2231
2642
  });
2232
2643
  return {
2233
- activityDays: directoryActivityDays(activityRows, nowMs),
2644
+ activityDays: directoryActivityDays(activityDayRows, nowMs),
2234
2645
  activityHours: directoryActivityHours(activityHourRows, nowMs),
2235
2646
  activitySixHours: directoryActivitySixHours(activitySixHourRows, nowMs),
2236
2647
  generatedAt: new Date(nowMs).toISOString(),
@@ -2255,7 +2666,7 @@ async function readPeoplePluginReports(args) {
2255
2666
  reports: [],
2256
2667
  source: "plugins"
2257
2668
  });
2258
- const { getPluginProfileReports } = await import("./projection-CL_YWeGf.js").then((n) => n.Un);
2669
+ const { getPluginProfileReports } = await import("./projection-BFJG58TG.js").then((n) => n.jn);
2259
2670
  return pluginOperationalReportFeedSchema.parse({
2260
2671
  generatedAt: new Date(nowMs).toISOString(),
2261
2672
  reports: await getPluginProfileReports({
@@ -2302,18 +2713,21 @@ function addAggregate(map, label, row) {
2302
2713
  if (row.tokens !== null) item.tokens = (item.tokens ?? 0) + row.tokens;
2303
2714
  map.set(label, item);
2304
2715
  }
2305
- function surfaceExpression() {
2716
+ function surfaceExpression(table) {
2306
2717
  return sql`CASE
2307
- WHEN ${juniorConversations.source} IN ('api', 'scheduler', 'slack')
2308
- THEN ${juniorConversations.source}
2718
+ WHEN ${table.source} IN ('api', 'scheduler', 'slack')
2719
+ THEN ${table.source}
2309
2720
  -- Dashboard web conversations share the product api surface label.
2310
- WHEN ${juniorConversations.source} = 'web' THEN 'api'
2311
- WHEN ${juniorConversations.conversationId} LIKE 'slack:%' THEN 'slack'
2312
- WHEN ${juniorConversations.conversationId} LIKE 'scheduler:%' THEN 'scheduler'
2313
- WHEN ${juniorConversations.conversationId} LIKE 'api:%' THEN 'api'
2721
+ WHEN ${table.source} = 'web' THEN 'api'
2722
+ WHEN ${table.conversationId} LIKE 'slack:%' THEN 'slack'
2723
+ WHEN ${table.conversationId} LIKE 'scheduler:%' THEN 'scheduler'
2724
+ WHEN ${table.conversationId} LIKE 'api:%' THEN 'api'
2314
2725
  ELSE 'internal'
2315
2726
  END`;
2316
2727
  }
2728
+ function channelExpression(table) {
2729
+ return sql`SPLIT_PART(${table.conversationId}, ':', 2)`;
2730
+ }
2317
2731
  function locationLabel(row) {
2318
2732
  if (row.surface !== "slack") return surfaceLabel(row.surface);
2319
2733
  if (row.destinationVisibility !== "public") return "Private Conversation";
@@ -2322,6 +2736,14 @@ function locationLabel(row) {
2322
2736
  channelName: row.channelName ?? void 0
2323
2737
  }) ?? "Conversation";
2324
2738
  }
2739
+ function activityBuckets(rows) {
2740
+ return new Map(rows.map(({ costUsd, tokens, ...row }) => [row.date, {
2741
+ ...emptyActivityDay(row.date),
2742
+ ...row,
2743
+ ...costUsd !== null ? { costUsd } : void 0,
2744
+ ...tokens !== null ? { tokens } : void 0
2745
+ }]));
2746
+ }
2325
2747
  /** Load one complete person profile while bounding only its recent-conversation list. */
2326
2748
  async function readPeopleProfileFromSql(email, options = {}) {
2327
2749
  const nowMs = Date.now();
@@ -2331,76 +2753,49 @@ async function readPeopleProfileFromSql(email, options = {}) {
2331
2753
  end.setUTCHours(0, 0, 0, 0);
2332
2754
  const start = new Date(end);
2333
2755
  start.setUTCDate(start.getUTCDate() - 364);
2334
- const where = verifiedActorWhere(normalizedEmail);
2335
- const metricsJoin = peopleTreeMetricsJoin();
2336
- const surface = surfaceExpression();
2337
- const activityDate = sql`TO_CHAR(
2338
- ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
2339
- 'YYYY-MM-DD'
2340
- )`;
2341
- const activityHour = sql`TO_CHAR(
2342
- ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
2343
- 'YYYY-MM-DD"T"HH24'
2344
- )`;
2345
- const channel = sql`SPLIT_PART(${juniorConversations.conversationId}, ':', 2)`;
2756
+ const turns = personTurns(normalizedEmail);
2757
+ const aggregate = turnAggregateColumns(turns);
2758
+ const surface = surfaceExpression(turnRoot);
2759
+ const channel = channelExpression(turnRoot);
2760
+ const day = turnBucket(turns, "day");
2761
+ const hour = turnBucket(turns, "hour");
2346
2762
  const hourWindow = trailingUtcHourWindow(nowMs, 168);
2347
2763
  const [totalsRows, dayRows, hourRows, locationRows, surfaceRows, recentRows] = await Promise.all([
2348
2764
  getDb().select({
2349
- email: juniorUsers.primaryEmailNormalized,
2350
- fullName: juniorUsers.displayName,
2351
- ...slackActorColumns(),
2352
- activeDays: conversationActiveDaysColumn(),
2353
- ...peopleTreeAggregateColumns
2354
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(where).groupBy(juniorUsers.primaryEmailNormalized, juniorUsers.displayName),
2765
+ ...turnPersonColumns(turns),
2766
+ ...aggregate
2767
+ }).from(turns).innerJoin(turnRoot, turnRootJoin(turns)).groupBy(turns.email, turns.fullName),
2355
2768
  getDb().select({
2356
- date: activityDate,
2357
- ...peopleTreeAggregateColumns
2358
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(and(where, gte(juniorConversations.lastActivityAt, start))).groupBy(activityDate),
2769
+ date: day,
2770
+ ...aggregate
2771
+ }).from(turns).innerJoin(turnRoot, turnRootJoin(turns)).where(gte(turns.occurredAt, start)).groupBy(day),
2359
2772
  getDb().select({
2360
- date: activityHour,
2361
- ...peopleTreeAggregateColumns
2362
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(and(where, gte(juniorConversations.lastActivityAt, hourWindow.start))).groupBy(activityHour),
2773
+ date: hour,
2774
+ ...aggregate
2775
+ }).from(turns).innerJoin(turnRoot, turnRootJoin(turns)).where(gte(turns.occurredAt, hourWindow.start)).groupBy(hour),
2363
2776
  getDb().select({
2364
2777
  channel,
2365
- channelName: juniorConversations.channelName,
2778
+ channelName: turnRoot.channelName,
2366
2779
  destinationVisibility: juniorDestinations.visibility,
2367
2780
  surface,
2368
- ...peopleTreeAggregateColumns
2369
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).leftJoin(juniorDestinations, eq(juniorDestinations.id, juniorConversations.destinationId)).where(where).groupBy(channel, juniorConversations.channelName, juniorDestinations.visibility, surface),
2781
+ ...aggregate
2782
+ }).from(turns).innerJoin(turnRoot, turnRootJoin(turns)).leftJoin(juniorDestinations, eq(juniorDestinations.id, turnRoot.destinationId)).groupBy(channel, turnRoot.channelName, juniorDestinations.visibility, surface),
2370
2783
  getDb().select({
2371
2784
  surface,
2372
- ...peopleTreeAggregateColumns
2373
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, metricsJoin).where(where).groupBy(surface),
2785
+ ...aggregate
2786
+ }).from(turns).innerJoin(turnRoot, turnRootJoin(turns)).groupBy(surface),
2374
2787
  recentActorRows(normalizedEmail)
2375
2788
  ]);
2376
- const totalsRow = totalsRows[0];
2377
- if (!totalsRow) return emptyProfile(normalizedEmail, nowMs);
2789
+ const person = totalsRows[0];
2790
+ if (!person) return emptyProfile(normalizedEmail, nowMs);
2378
2791
  const actor = {
2379
- email: totalsRow.email,
2380
- ...totalsRow.fullName ? { fullName: totalsRow.fullName } : void 0,
2381
- ...totalsRow.slackUserId ? { slackUserId: totalsRow.slackUserId } : void 0,
2382
- ...totalsRow.slackUserName ? { slackUserName: totalsRow.slackUserName } : void 0
2792
+ email: person.email,
2793
+ ...person.fullName ? { fullName: person.fullName } : void 0,
2794
+ ...person.slackUserId ? { slackUserId: person.slackUserId } : void 0,
2795
+ ...person.slackUserName ? { slackUserName: person.slackUserName } : void 0
2383
2796
  };
2384
- const days = /* @__PURE__ */ new Map();
2385
- for (const row of dayRows) days.set(row.date, {
2386
- active: row.active,
2387
- conversations: row.conversations,
2388
- ...row.costUsd !== null ? { costUsd: row.costUsd } : void 0,
2389
- date: row.date,
2390
- durationMs: row.durationMs,
2391
- failed: row.failed,
2392
- ...row.tokens !== null ? { tokens: row.tokens } : void 0
2393
- });
2394
- const hours = /* @__PURE__ */ new Map();
2395
- for (const row of hourRows) hours.set(row.date, {
2396
- active: row.active,
2397
- conversations: row.conversations,
2398
- ...row.costUsd !== null ? { costUsd: row.costUsd } : void 0,
2399
- date: row.date,
2400
- durationMs: row.durationMs,
2401
- failed: row.failed,
2402
- ...row.tokens !== null ? { tokens: row.tokens } : void 0
2403
- });
2797
+ const days = activityBuckets(dayRows);
2798
+ const hours = activityBuckets(hourRows);
2404
2799
  const locations = /* @__PURE__ */ new Map();
2405
2800
  for (const row of locationRows) addAggregate(locations, locationLabel(row), row);
2406
2801
  const surfaces = /* @__PURE__ */ new Map();
@@ -2428,12 +2823,12 @@ async function readPeopleProfileFromSql(email, options = {}) {
2428
2823
  source: "conversation_index",
2429
2824
  surfaces: statsItems(surfaces),
2430
2825
  totals: {
2431
- active: totalsRow.active,
2432
- activeDays: totalsRow.activeDays,
2433
- conversations: totalsRow.conversations,
2434
- durationMs: totalsRow.durationMs,
2435
- failed: totalsRow.failed,
2436
- ...totalsRow.tokens !== null ? { tokens: totalsRow.tokens } : void 0
2826
+ active: person.active,
2827
+ activeDays: person.activeDays,
2828
+ conversations: person.conversations,
2829
+ durationMs: person.durationMs,
2830
+ failed: person.failed,
2831
+ ...person.tokens !== null ? { tokens: person.tokens } : void 0
2437
2832
  },
2438
2833
  windowEnd: end.toISOString(),
2439
2834
  windowStart: start.toISOString()
@@ -2464,48 +2859,42 @@ function spendWindow(nowMs) {
2464
2859
  thirtyDayStart
2465
2860
  };
2466
2861
  }
2467
- /** Match the viewer's own Conversations with activity in the spend window. */
2862
+ /** Match the viewer's own Turn metric rows in the spend window. */
2468
2863
  function viewerWindowWhere(email, nowMs) {
2469
2864
  const normalizedEmail = normalizeEmail$1(email);
2470
2865
  const { end, thirtyDayStart } = spendWindow(nowMs);
2471
- return normalizedEmail ? and(verifiedActorWhere(normalizedEmail), gte(juniorConversations.lastActivityAt, thirtyDayStart), lte(juniorConversations.lastActivityAt, end)) : sql`false`;
2866
+ return normalizedEmail ? and(verifiedActorWhere(normalizedEmail), gte(juniorConversationMetrics.occurredAt, thirtyDayStart), lte(juniorConversationMetrics.occurredAt, end)) : sql`false`;
2472
2867
  }
2473
2868
  /** Return a query for one viewer's model spend for each UTC day in the window. */
2474
- function personalSpendDaysQuery(db, email, nowMs) {
2475
- const activityDate = sql`TO_CHAR(
2476
- ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
2869
+ function personalSpendDaysQuery(email, nowMs) {
2870
+ const date = sql`TO_CHAR(
2871
+ ${juniorConversationMetrics.occurredAt} AT TIME ZONE 'UTC',
2477
2872
  'YYYY-MM-DD'
2478
2873
  )`;
2479
- return db.select({
2480
- costUsd: peopleTreeAggregateColumns.costUsd,
2481
- date: activityDate
2482
- }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).leftJoin(peopleTreeConversation, peopleTreeMetricsJoin()).where(viewerWindowWhere(email, nowMs)).groupBy(activityDate);
2874
+ return getDb().select({
2875
+ costUsd: turnMetricColumns.costUsd,
2876
+ date
2877
+ }).from(juniorConversationMetrics).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationMetrics.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(viewerWindowWhere(email, nowMs)).groupBy(date);
2483
2878
  }
2484
2879
  /**
2485
2880
  * Return a query for a change marker of one viewer's spend window.
2486
2881
  *
2487
- * It reads only the viewer's own rows, without the tree join of the spend
2488
- * read, so it costs about as much as a count. It sums each row's own cost
2489
- * and the UTC day of its last activity, so a recorded cost, or a
2490
- * Conversation that moves to a new day, moves it. Other writes do not. A
2491
- * Task that another person's Turn started under the viewer's root is not
2492
- * the viewer's row, so its cost shows on the next spend read: a page load,
2493
- * a tab focus, or the viewer's next own cost. The window start moves it at
2494
- * UTC midnight.
2882
+ * It reads the same Turn metric rows as the spend read. A new or replaced
2883
+ * row moves it, and the window start moves it at UTC midnight.
2495
2884
  */
2496
2885
  function personalSpendVersionQuery(db, email, nowMs) {
2497
2886
  const { thirtyDayStart } = spendWindow(nowMs);
2498
2887
  return db.select({ version: sql`concat_ws(':',
2499
2888
  ${thirtyDayStart.toISOString().slice(0, 10)}::text,
2500
2889
  count(*),
2501
- sum(${conversationUsageCostExpr(juniorConversations.usage)}),
2502
- sum(extract(epoch from date_trunc('day', ${juniorConversations.lastActivityAt} at time zone 'UTC')))
2503
- )` }).from(juniorConversations).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversations.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(viewerWindowWhere(email, nowMs));
2890
+ sum(${juniorConversationMetrics.value}),
2891
+ max(${juniorConversationMetrics.updatedAt})
2892
+ )` }).from(juniorConversationMetrics).innerJoin(juniorIdentities, eq(juniorIdentities.id, juniorConversationMetrics.actorIdentityId)).innerJoin(juniorUsers, eq(juniorUsers.id, juniorIdentities.userId)).where(viewerWindowWhere(email, nowMs));
2504
2893
  }
2505
2894
  /** Read one viewer's rolling model spend with one bounded aggregate query. */
2506
2895
  async function readPersonalSpendFromSql(email, nowMs = Date.now()) {
2507
2896
  const { end, sevenDayStart, thirtyDayStart } = spendWindow(nowMs);
2508
- const rows = await personalSpendDaysQuery(getDb(), email, nowMs);
2897
+ const rows = await personalSpendDaysQuery(email, nowMs);
2509
2898
  const sevenDayStartDate = sevenDayStart.toISOString().slice(0, 10);
2510
2899
  let sevenDaysUsd = 0;
2511
2900
  let thirtyDaysUsd = 0;
@@ -3077,7 +3466,7 @@ function createReviewItemRoutes(services) {
3077
3466
  const after = query.cursor ? decodeCursor(query.cursor, filters) : void 0;
3078
3467
  if (query.cursor && !after) return jsonResponse(apiErrorSchema, { error: "Invalid review item cursor." }, { status: 400 });
3079
3468
  const db = getDb();
3080
- const reader = reviewItemReaderForUser(viewer);
3469
+ const reader = filters.conversationId ? await reviewItemReaderForUserInConversation(viewer, filters.conversationId) : reviewItemReaderForUser(viewer);
3081
3470
  const open = await searchReviewItems(db, reader, {
3082
3471
  ...filters,
3083
3472
  limit: query.limit + 1,
@@ -3284,7 +3673,7 @@ function readDescriptionText(home) {
3284
3673
  }
3285
3674
  /** Read discovered skill names for authenticated runtime diagnostics. */
3286
3675
  async function readSkillReports() {
3287
- const { discoverSkills } = await import("./skills-CD5aJdzg.js").then((n) => n.o);
3676
+ const { discoverSkills } = await import("./skills-CcAJBquq.js").then((n) => n.o);
3288
3677
  const skills = await discoverSkills();
3289
3678
  return skillReportsSchema.parse(skills.map((skill) => ({
3290
3679
  name: skill.name,
@@ -3293,7 +3682,7 @@ async function readSkillReports() {
3293
3682
  }
3294
3683
  /** Read safe configured plugin metadata for authenticated runtime diagnostics. */
3295
3684
  async function readPlugins() {
3296
- const { pluginCatalogRuntime } = await import("./catalog-runtime-BCIuBe4d.js").then((n) => n.t);
3685
+ const { pluginCatalogRuntime } = await import("./catalog-runtime-BNK4uJVZ.js").then((n) => n.t);
3297
3686
  return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
3298
3687
  configKeys: plugin.manifest.configKeys ?? [],
3299
3688
  description: plugin.manifest.description,
@@ -3305,7 +3694,7 @@ async function readPlugins() {
3305
3694
  async function readRuntimeInfoReport() {
3306
3695
  const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
3307
3696
  import("./package-discovery-DJhGdS4c.js").then((n) => n.r),
3308
- import("./catalog-runtime-BCIuBe4d.js").then((n) => n.t),
3697
+ import("./catalog-runtime-BNK4uJVZ.js").then((n) => n.t),
3309
3698
  readPlugins(),
3310
3699
  readSkillReports()
3311
3700
  ]);
@@ -3322,7 +3711,7 @@ async function readRuntimeInfoReport() {
3322
3711
  /** Read sanitized operational summaries contributed by plugins. */
3323
3712
  async function readPluginOperationalReportFeed() {
3324
3713
  const nowMs = Date.now();
3325
- const { getPluginOperationalReports } = await import("./projection-CL_YWeGf.js").then((n) => n.Un);
3714
+ const { getPluginOperationalReports } = await import("./projection-BFJG58TG.js").then((n) => n.jn);
3326
3715
  return pluginOperationalReportFeedSchema.parse({
3327
3716
  source: "plugins",
3328
3717
  generatedAt: new Date(nowMs).toISOString(),
@@ -3349,6 +3738,7 @@ function createJuniorApi(options = {}) {
3349
3738
  queue,
3350
3739
  show: createSlackReviewItemShow(getProductionSlackAdapter)
3351
3740
  } }));
3741
+ app.route("/api/board", createBoardRoutes());
3352
3742
  app.route("/api/code", createCodeRoutes());
3353
3743
  app.route("/api/connections", createConnectionRoutes());
3354
3744
  app.route("/api/notifications", createNotificationRoutes());