@sentry/junior 0.295.0 → 0.297.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 (84) hide show
  1. package/dist/{admin-ifgjyfpF.js → admin-tmGIw4KS.js} +2 -2
  2. package/dist/{agent-runner-DjMTPWEO.js → agent-runner-CneTquAE.js} +468 -1947
  3. package/dist/api/schema.d.ts +2 -2
  4. package/dist/api/schema.js +7 -7
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +306 -569
  7. package/dist/{app-uiTzRbvq.d.ts → app-BJojZ7HL.d.ts} +7 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +64 -44
  10. package/dist/attempt-selection-ClP3MMPr.js +61 -0
  11. package/dist/{automation-yJX3C7i3.js → automation-BrP6ImrC.js} +1 -1
  12. package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-CwfJy3Cd.js} +4 -88
  13. package/dist/{briefs-CbNYM-q2.js → briefs-uFTuhMqA.js} +3 -3
  14. package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-0kuQqYL4.js} +1 -1
  15. package/dist/cli/chat.js +19 -15
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/main.js +3 -3
  18. package/dist/cli/plugins.js +4 -4
  19. package/dist/cli/snapshot-create.js +4 -4
  20. package/dist/cli/upgrade.d.ts +1 -1
  21. package/dist/cli/upgrade.js +3 -3
  22. package/dist/{config-DvnTPCfp.js → config-Dj9M_nqB.js} +18 -2
  23. package/dist/{connections-CWaIVl_1.js → connections-B96JUM5o.js} +6 -6
  24. package/dist/{conversation-CMkSmi02.js → conversation-CvcBU1z2.js} +2 -16
  25. package/dist/{conversation-feed-BVAOga0H.js → conversation-feed-BSMlGZnS.js} +1 -1
  26. package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-DI29jbZV.js} +1 -1
  27. package/dist/conversation-turn-CZWBr091.js +805 -0
  28. package/dist/{credential-sync-BhbaZfmO.js → credential-sync-Blhx4_xf.js} +14 -13
  29. package/dist/{db-Dts2XvLu.js → db-Br0tfAo7.js} +54 -32
  30. package/dist/{db-CCUqQe0E.d.ts → db-CrtyFRz7.d.ts} +13 -1
  31. package/dist/{executor-Ck73J0wP.js → executor-BMPipFVA.js} +19 -5
  32. package/dist/instrumentation.js +19 -2
  33. package/dist/{logging-9OAq-fdg.js → logging-CQjlDQYX.js} +1 -1
  34. package/dist/{message-CtaPzC7m.js → message-BOZEIuxy.js} +15 -13
  35. package/dist/nitro.d.ts +1 -1
  36. package/dist/nitro.js +3 -2
  37. package/dist/{session-stop-DkxI5vc3.js → notification-gusCgdQ6.js} +14 -933
  38. package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-V_DuMuNX.js} +2 -2
  39. package/dist/{projection-BzJQncZV.js → projection-B08mfi0u.js} +479 -145
  40. package/dist/{prompt-Cbq5b4SO.js → prompt-BlutWLNt.js} +4 -4
  41. package/dist/prompt-input-Dxn8cDC0.js +1424 -0
  42. package/dist/{registry-cbpOxO4M.js → registry-BDWgCJDf.js} +1 -1
  43. package/dist/reporting-window-DopzcOHh.js +137 -0
  44. package/dist/{resolve-t-pmRdwS.js → resolve-2Z_o_SsI.js} +3 -3
  45. package/dist/result-CAujiaci.js +463 -0
  46. package/dist/{runner-CHv9X9TH.js → runner-D2Chc02N.js} +9 -8
  47. package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-CFoJduFj.js} +1 -1
  48. package/dist/{schema-BhneuGYv.js → schema-Bqa5NbcP.js} +22 -48
  49. package/dist/{schema-TSEisVJR.d.ts → schema-Ce2XCS7O.d.ts} +24 -107
  50. package/dist/{service-account-DjPIwCMj.js → service-account-C9kRQEb_.js} +3 -3
  51. package/dist/{service-account-C4rBP8ne.js → service-account-CERfXEVU.js} +3 -3
  52. package/dist/session-stop-B-I1rAS1.js +181 -0
  53. package/dist/{skills-BZE2DP8I.js → skills-B0m1nZ_j.js} +3 -3
  54. package/dist/{spawn-BvULxIiu.js → spawn-CwMjRRtn.js} +6 -5
  55. package/dist/{state-CO9ETDzk.js → state-DFnmLmfn.js} +2 -2
  56. package/dist/{stop-CL-rdtQb.js → stop-BCH9VNGf.js} +329 -382
  57. package/dist/{store-DgD78_NK.js → store-B59rOYbS.js} +11 -4
  58. package/dist/{task-runner-CKOj6xla.js → store-m5bmdmsP.js} +929 -1559
  59. package/dist/task-queue-N0kuCknH.js +89 -0
  60. package/dist/task-runner-COOwR8qm.js +291 -0
  61. package/dist/thread-context-Cd44z_W5.js +248 -0
  62. package/dist/turn-cancel-DDu8TOwt.js +201 -0
  63. package/dist/turn-session-routing-BlCtVFRN.js +380 -0
  64. package/dist/{turn-failure-response-BTSo6SMJ.js → turn-user-message-ygLG3ylQ.js} +183 -358
  65. package/dist/turn-wake-DmQec4AG.js +161 -0
  66. package/dist/{reporting-window-B3Ze-Qnt.js → user-input-request-CXNIov9n.js} +24 -143
  67. package/dist/{validation-CXeYgBzq.js → validation-Ba2OcUse.js} +1 -1
  68. package/dist/{version-AQa7Fr2H.js → version-KNDzIAh6.js} +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/{viewer-Bqkb678l.js → viewer-BPpuN2f9.js} +3 -3
  71. package/dist/warmup-Bskrwmk1.js +2697 -0
  72. package/dist/{worker-Hl7N292I.js → worker-B1skZlit.js} +20 -8
  73. package/migrations/0101_drop_legacy_columns.sql +12 -0
  74. package/migrations/0102_code_change_last_activity.sql +1 -0
  75. package/migrations/0103_agent_invocation_fork.sql +8 -0
  76. package/migrations/meta/0101_snapshot.json +4496 -0
  77. package/migrations/meta/0102_snapshot.json +4502 -0
  78. package/migrations/meta/0103_snapshot.json +4509 -0
  79. package/migrations/meta/_journal.json +21 -0
  80. package/package.json +5 -4
  81. package/dist/result-DhgjR3nQ.js +0 -305
  82. package/dist/result-event-type-DD6BAgT7.js +0 -11
  83. package/dist/warmup-h6u1e9n0.js +0 -1869
  84. package/dist/work-yN_GAuXY.js +0 -768
package/dist/api.js CHANGED
@@ -1,35 +1,39 @@
1
- import { $a as createConversationAccessReader, $n as savePushSubscription, Bn as getPlugins, Dr as reviewItemReaderForUserInConversation, Ei as hash, En as createUserTokenStore, Er as reviewItemReaderForUser, Jn as resolveNotificationTimezone, Kn as readWebPushConfig, Pa as workspaceRepoCheckoutPath, Po as createPluginCache, Qn as saveNotificationSchedule, Ti as create, Tr as reviewItemNeedsUser, Xa as createPluginLogger, Xn as listPushSubscriptions, Yn as deletePushSubscription, Zn as readNotificationSchedule, _i as listWorkspaces, bi as WorkspaceValidationError, br as isOnlyAssignee, co as readConversationBriefThrough, dr as reviewItemsNeedingUserVersionQuery, eo as readConversationAccessFromSql, er as isPausedBySlack, fr as searchReviewItems, gr as canActOnReviewItem, hi as getWorkspace, hr as PLUGIN_REVIEW_ITEM_KEY_PREFIX, ir as countReviewItemsNeedingUser, ja as SANDBOX_RUNTIME, mi as deleteWorkspace, no as conversationIsMemberRoot, oi as getDashboardSettingsLink, pi as createWorkspace, qn as sendPushNotificationToUser, uo as readConversationEventPage, ur as listWaitingConversations, vi as listWorkspacesByRepository, yi as updateWorkspace } from "./projection-BzJQncZV.js";
2
- import { L as escapeXml, Y as getAttachmentStorage, n as botConfig } from "./config-DvnTPCfp.js";
3
- import { m as logInfo, p as logException } from "./logging-9OAq-fdg.js";
1
+ import { Ai as deleteWorkspace, Dr as reviewItemsNeedingUserVersionQuery, Eo as readConversationEventPage, Er as listWaitingConversations, Fi as updateWorkspace, Hi as hash, Hn as createUserTokenStore, Hr as reviewItemReaderForUserInConversation, Ii as WorkspaceValidationError, Ir as isOnlyAssignee, Mr as canActOnReviewItem, Ni as listWorkspaces, Or as searchReviewItems, Pi as listWorkspacesByRepository, Si as getDashboardSettingsLink, Vi as create, Vr as reviewItemReaderForUser, Xa as workspaceRepoCheckoutPath, Zo as createPluginCache, br as countReviewItemsNeedingUser, cr as readWebPushConfig, dr as deletePushSubscription, fo as createPluginLogger, fr as listPushSubscriptions, go as readConversationAccessFromSql, gr as isPausedBySlack, ho as createConversationAccessReader, hr as savePushSubscription, ji as getWorkspace, ki as createWorkspace, lr as sendPushNotificationToUser, mr as saveNotificationSchedule, nr as getPlugins, pr as readNotificationSchedule, qa as SANDBOX_RUNTIME, ur as resolveNotificationTimezone, wo as readConversationBriefThrough } from "./projection-B08mfi0u.js";
2
+ import { L as escapeXml, Y as getAttachmentStorage, n as botConfig } from "./config-Dj9M_nqB.js";
3
+ import { m as logInfo, p as logException } from "./logging-CQjlDQYX.js";
4
4
  import { f as parseSlackTeamId, u as parseSlackChannelId } from "./actor-6jsm_v96.js";
5
- import { O as conversationKindFromRow, S as withConversationMutationLock, a as getConversationStore, o as getDb, s as getSqlExecutor, tt as nextDetailVersion, v as loadConversationSlackTenantIds } from "./db-Dts2XvLu.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-Ck73J0wP.js";
5
+ import { O as conversationKindFromRow, S as withConversationMutationLock, a as getConversationStore, et as nextDetailVersion, o as getDb, s as getSqlExecutor, v as loadConversationSlackTenantIds } from "./db-Br0tfAo7.js";
6
+ import { A as juniorConversations, D as juniorCodeChanges, M as juniorUsers, N as juniorDestinations, O as juniorCodeRepositories, S as juniorConversationMetrics, T as juniorApiTokens, b as juniorConversationBriefs, j as juniorIdentities, w as juniorConversationEvents } from "./executor-BMPipFVA.js";
7
7
  import { n as INPUT_IMAGE_TYPES, t as INLINE_VIDEO_TYPES } from "./media-BepyEUNm.js";
8
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DgouZKZm.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 listedConversation, q as readViewerAutomationEdit, sn as listChildAgents, tt as readViewerAutomations, v as setConversationSubscription, wt as jsonResponse } from "./agent-runner-DjMTPWEO.js";
10
- import { n as briefEntriesFromReportEvents, u as completeText } from "./prompt-Cbq5b4SO.js";
11
- import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarImage, t as findUserByEmail } from "./viewer-Bqkb678l.js";
12
- import { a as getStateAdapter } from "./state-CO9ETDzk.js";
8
+ import { n as pluginCatalogRuntime } from "./catalog-runtime-0kuQqYL4.js";
9
+ import { $ as readViewerAutomationRuns, C as createSlackReviewItemShow, Dt as jsonResponse, Et as emptyResponse, G as activateViewerAutomationVersion, J as readViewerAutomationEdit, K as changeViewerAutomationLifecycle, Ot as throwApiError, Q as readViewerAutomationExecutions, St as archiveConversation, Tt as reportConversationRead, X as ViewerTaskNotFoundError, Y as updateViewerAutomation, at as listOwnedWatches, et as readViewerAutomationSummary, h as readStats, ht as webActorFromUser, j as runWithSlackInstallation, nt as readViewerAutomations, q as deleteViewerTask, rt as AutomationEditError, tt as readViewerAutomationVersions, y as setConversationSubscription, yt as readLiveAttachment } from "./agent-runner-CneTquAE.js";
10
+ import { n as briefEntriesFromReportEvents, u as completeText } from "./prompt-BlutWLNt.js";
11
+ import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarImage, t as findUserByEmail } from "./viewer-BPpuN2f9.js";
12
+ import { a as getStateAdapter } from "./state-DFnmLmfn.js";
13
13
  import { r as notificationScheduleSchema } from "./schedule-cP0AACm1.js";
14
- import { A as renameConversationResponseSchema, C as createConversationMessageBodySchema, M as conversationReadReportSchema, S as createConversationBodySchema, T as forkConversationResponseSchema, c as conversationDetailQuerySchema, d as conversationEventPageSchema, f as conversationEventsQuerySchema, j as conversationReadPositionSchema, k as renameConversationBodySchema, l as conversationDetailReportSchema, m as conversationParamsSchema, n as CONVERSATION_VERSION_HEADER, o as conversationAttachmentParamsSchema, p as conversationFeedQuerySchema, r as acceptedConversationMessageSchema, t as CONVERSATION_DETAIL_VERSION_HEADER, w as forkConversationBodySchema } from "./conversation-CMkSmi02.js";
15
- import { a as segmentGapsKey, h as gapHistogramReport, u as GAP_SEGMENTS } from "./warmup-h6u1e9n0.js";
16
- import { g as getVercelConversationWorkQueue } from "./background-compaction-queue-DUkHZjmL.js";
17
- import { O as getEventCatalog, et as readUserCustomization, rt as isExperimentalFeatureEnabled, tt as saveUserCustomization } from "./session-stop-DkxI5vc3.js";
18
- 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";
19
- import { s as getSandboxResources, t as getCachedSnapshot } from "./resolve-t-pmRdwS.js";
20
- import { J as AutomationConflictError, at as readAutomationTitlesByConversationId, ct as conversationRangeColumns, st as conversationAggregateColumns, vt as automationEventCatalog } from "./task-runner-CKOj6xla.js";
21
- import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-DjPIwCMj.js";
22
- import { F as compileScheduleIntent, P as ScheduleIntentError, U as automationTaskText, _ 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-yJX3C7i3.js";
23
- import { C as skillReportsSchema, a as conversationDetailWithMailboxReportSchema, b as runtimeInfoReportSchema, d as steerConversationPendingMessagesBodySchema, f as steerConversationPendingMessagesResponseSchema, i as cancelConversationPendingMessagesResponseSchema, l as conversationPendingMessagesReportSchema, m as pluginOperationalReportFeedSchema, n as conversationFeedSchema, p as healthReportSchema, r as cancelConversationPendingMessagesBodySchema, u as conversationUnchangedDetailWithMailboxSchema, x as skillDetailReportSchema, y as pluginsSchema } from "./conversation-feed-BVAOga0H.js";
24
- 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-CL-rdtQb.js";
25
- import { a as startConnection, n as isConnectableProvider, r as listConnections, s as htmlCallbackResponse, t as disconnectConnection } from "./connections-CWaIVl_1.js";
26
- import { A as revokePersonalTokenResponseSchema, At as reorderPinnedConversationsBodySchema, B as activityDays$1, Ct as markConversationUnreadBodySchema, D as personalTokenListSchema, Dt as conversationDeliveryResponseSchema, E as createdPersonalTokenSchema, Et as conversationDeliveryBodySchema, F as personalSpendReportSchema, G as pushSubscriptionBodySchema, H as activitySixHours$1, J as connectionListSchema, K as pushSubscriptionDeleteBodySchema, L as locationDetailReportSchema, M as actorProfileReportSchema, Mt as conversationCatchUpBodySchema, N as avatarParamsSchema, Nt as conversationCatchUpSchema, Ot as pinConversationBodySchema, P as personParamsSchema, Q as startConnectionResponseSchema, R as locationDirectoryReportSchema, S as serviceAccountParamsSchema, St as conversationUnreadSchema, T as createPersonalTokenBodySchema, Tt as conversationSubscriptionResponseSchema, V as activityHours$1, W as notificationSettingsSchema, Y as connectionParamsSchema, Z as disconnectConnectionResponseSchema, _ as reviewItemParamsSchema, _t as conversationOutlineSchema, a as replyTimeSegmentsReportSchema, at as codeRepositoryReportSchema, b as disconnectServiceAccountResponseSchema, bt as archiveDoneConversationsResponseSchema, c as workspaceBodySchema, dt as conversationChildAgentsReportSchema, f as workspaceSchema, ft as continueConversationInSlackBodySchema, g as reviewItemListSchema, h as reviewItemListQuerySchema, ht as conversationStatsReportSchema, i as statsReportSchema, it as codeRepositoryParamsSchema, j as actorDirectoryReportSchema, jt as reorderPinnedConversationsResponseSchema, k as personalTokenParamsSchema, kt as pinConversationResponseSchema, l as workspaceListSchema, lt as conversationWatchesReportSchema, m as reviewItemCountSchema, mt as stopConversationTurnResponseSchema, n as versionsSchema, nt as codeOverviewReportSchema, p as reviewItemActionSchema, pt as continueConversationInSlackResponseSchema, q as testNotificationResponseSchema, rt as codePersonReportSchema, s as deleteWorkspaceResponseSchema, st as boardReportSchema, t as versionsQuerySchema, u as workspaceParamsSchema, v as reviewItemSchema, vt as archiveConversationBodySchema, w as startServiceAccountSignInResponseSchema, wt as conversationSubscriptionBodySchema, x as serviceAccountListSchema, xt as conversationAutoArchiveSchema, y as reviewItemWaitingConversationsSchema, yt as archiveConversationResponseSchema, z as locationParamsSchema } from "./schema-BhneuGYv.js";
14
+ import { A as renameConversationResponseSchema, C as createConversationMessageBodySchema, S as createConversationBodySchema, T as forkConversationResponseSchema, c as conversationDetailQuerySchema, d as conversationEventPageSchema, f as conversationEventsQuerySchema, j as conversationReadPositionSchema, k as renameConversationBodySchema, l as conversationDetailReportSchema, m as conversationParamsSchema, n as CONVERSATION_VERSION_HEADER, o as conversationAttachmentParamsSchema, p as conversationFeedQuerySchema, r as acceptedConversationMessageSchema, t as CONVERSATION_DETAIL_VERSION_HEADER, w as forkConversationBodySchema } from "./conversation-CvcBU1z2.js";
15
+ import { d as saveUserCustomization, p as isExperimentalFeatureEnabled, u as readUserCustomization } from "./prompt-input-Dxn8cDC0.js";
16
+ import { H as gapHistogramReport, L as GAP_SEGMENTS, a as segmentGapsKey, d as listChildAgents } from "./warmup-Bskrwmk1.js";
17
+ import { l as getVercelConversationWorkQueue } from "./background-compaction-queue-CwfJy3Cd.js";
18
+ import { s as getEventCatalog } from "./notification-gusCgdQ6.js";
19
+ import { u as automationEventCatalog } from "./turn-session-routing-BlCtVFRN.js";
20
+ import { l as userCustomizationSchema } from "./user-input-request-CXNIov9n.js";
21
+ import { s as getSandboxResources, t as getCachedSnapshot } from "./resolve-2Z_o_SsI.js";
22
+ import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-C9kRQEb_.js";
23
+ import { 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-DopzcOHh.js";
24
+ import { F as compileScheduleIntent, P as ScheduleIntentError, U as automationTaskText, _ 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-BrP6ImrC.js";
25
+ import { A as conversationRangeColumns, D as readAutomationTitlesByConversationId, at as AutomationConflictError, j as conversationUsageCostExpr, k as conversationAggregateColumns } from "./store-m5bmdmsP.js";
26
+ import { C as skillReportsSchema, a as conversationDetailWithMailboxReportSchema, b as runtimeInfoReportSchema, d as steerConversationPendingMessagesBodySchema, f as steerConversationPendingMessagesResponseSchema, i as cancelConversationPendingMessagesResponseSchema, l as conversationPendingMessagesReportSchema, m as pluginOperationalReportFeedSchema, n as conversationFeedSchema, p as healthReportSchema, r as cancelConversationPendingMessagesBodySchema, u as conversationUnchangedDetailWithMailboxSchema, x as skillDetailReportSchema, y as pluginsSchema } from "./conversation-feed-BSMlGZnS.js";
27
+ import { C as cancelConversationPendingMessagesForViewer, E as resolveMentions, M as isAllowedSignInEmail, Q as readReviewItemForUser, T as requireConversationPendingMessages, X as actOnReviewItem, Y as ReviewItemActionError, _ as conversationSummaryFromStoredConversation, a as pinConversation, at as archiveViewerDoneConversations, b as createConversationForViewer, c as readConversationAuxiliaryCostsFromSql, ct as setConversationAutoArchive, d as conversationVersionQuery, f as readConversationDetailEtag, h as readConversationEvents, i as readConversationFeed, it as DEFAULT_AUTO_ARCHIVE_SETTINGS, k as getProductionSlackAdapter, l as childAgentTotalsReport, lt as updateUserAutoArchiveSettings, m as keepQuickQuestionForViewer, n as steerConversationPendingMessagesForViewer, nt as continueConversationInSlack, o as reorderPinnedConversations, ot as readUserAutoArchiveSettings, p as forkConversationForViewer, pt as readHealthReport, r as conversationFeedVersionQuery, s as readConversationDetail, t as stopConversationTurnForViewer, tt as canContinueInSlack, u as readConversationTreeMetricsFromSql, v as readFirstHumanMessageTexts, y as appendConversationMessageForViewer } from "./stop-BCH9VNGf.js";
28
+ import { a as startConnection, n as isConnectableProvider, r as listConnections, s as htmlCallbackResponse, t as disconnectConnection } from "./connections-B96JUM5o.js";
29
+ import { c as resumeConversationDelivery, o as canPauseConversationDelivery, s as pauseConversationDelivery } from "./conversation-turn-CZWBr091.js";
30
+ import { A as revokePersonalTokenResponseSchema, At as conversationCatchUpSchema, B as activityDays$1, Ct as conversationDeliveryBodySchema, D as personalTokenListSchema, Dt as reorderPinnedConversationsBodySchema, E as createdPersonalTokenSchema, Et as pinConversationResponseSchema, F as personalSpendReportSchema, G as pushSubscriptionBodySchema, H as activitySixHours$1, J as connectionListSchema, K as pushSubscriptionDeleteBodySchema, L as locationDetailReportSchema, M as actorProfileReportSchema, N as avatarParamsSchema, Ot as reorderPinnedConversationsResponseSchema, P as personParamsSchema, Q as startConnectionResponseSchema, R as locationDirectoryReportSchema, S as serviceAccountParamsSchema, St as conversationSubscriptionResponseSchema, T as createPersonalTokenBodySchema, Tt as pinConversationBodySchema, V as activityHours$1, W as notificationSettingsSchema, Y as connectionParamsSchema, Z as disconnectConnectionResponseSchema, _ as reviewItemParamsSchema, _t as archiveConversationBodySchema, a as replyTimeSegmentsReportSchema, at as codeRepositoryReportSchema, b as disconnectServiceAccountResponseSchema, bt as conversationAutoArchiveSchema, c as workspaceBodySchema, ct as conversationWatchesReportSchema, dt as continueConversationInSlackBodySchema, f as workspaceSchema, ft as continueConversationInSlackResponseSchema, g as reviewItemListSchema, gt as conversationOutlineSchema, h as reviewItemListQuerySchema, i as statsReportSchema, it as codeRepositoryParamsSchema, j as actorDirectoryReportSchema, k as personalTokenParamsSchema, kt as conversationCatchUpBodySchema, l as workspaceListSchema, m as reviewItemCountSchema, mt as conversationStatsReportSchema, n as versionsSchema, nt as codeOverviewReportSchema, p as reviewItemActionSchema, pt as stopConversationTurnResponseSchema, q as testNotificationResponseSchema, rt as codePersonReportSchema, s as deleteWorkspaceResponseSchema, t as versionsQuerySchema, u as workspaceParamsSchema, ut as conversationChildAgentsReportSchema, v as reviewItemSchema, vt as archiveConversationResponseSchema, w as startServiceAccountSignInResponseSchema, wt as conversationDeliveryResponseSchema, x as serviceAccountListSchema, xt as conversationSubscriptionBodySchema, y as reviewItemWaitingConversationsSchema, yt as archiveDoneConversationsResponseSchema, z as locationParamsSchema } from "./schema-Bqa5NbcP.js";
27
31
  import { Hono } from "hono";
28
32
  import path from "node:path";
29
33
  import { createHash, randomBytes, randomUUID } from "node:crypto";
30
34
  import * as z from "zod";
31
- import { and, arrayOverlaps, asc, desc, eq, gt, gte, inArray, isNull, like, lte, or, sql } from "drizzle-orm";
32
- import { conversationAnnotationInputSchema, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
35
+ import { and, asc, countDistinct, desc, eq, gt, gte, inArray, isNull, lte, notExists, or, sql } from "drizzle-orm";
36
+ import { pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
33
37
  import { alias } from "drizzle-orm/pg-core";
34
38
  import fs from "node:fs/promises";
35
39
  import { readFileSync } from "node:fs";
@@ -456,6 +460,111 @@ async function readConversationMetricBuckets(db, options) {
456
460
  value: sql`sum(${juniorConversationMetrics.value})::double precision`
457
461
  }).from(juniorConversationMetrics).where(and(gte(juniorConversationMetrics.occurredAt, options.start), lte(juniorConversationMetrics.occurredAt, options.end))).groupBy(date, juniorConversationMetrics.metric).orderBy(asc(date), asc(juniorConversationMetrics.metric));
458
462
  }
463
+ // src/api/conversations/outcome-buckets.ts
464
+ const changes = juniorCodeChanges;
465
+ const linked = alias(juniorConversations, "linked");
466
+ const linksChange = sql`${linked.conversationId} = any(${changes.conversationIds})`;
467
+ const linkedRoot = sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})`;
468
+ /**
469
+ * Count outcomes per UTC day or hour, with the conversation cost that
470
+ * produced them. An outcome is one of:
471
+ *
472
+ * - a merged code change, at its merge time. Each root Conversation splits its
473
+ * tree cost evenly across all of its merged code changes, so a long
474
+ * Conversation that merges three changes makes each one cheaper.
475
+ * - a root Conversation with no linked code change whose latest Brief is
476
+ * `done` or `answered`, at its last activity. Its whole tree cost counts.
477
+ *
478
+ * Roots with only open or closed code changes count nothing until a change
479
+ * merges, so one Conversation is never both kinds of outcome. A merged change
480
+ * with no linked Conversation has an unknown cost, not a zero cost, so it is
481
+ * left out instead of making the mean look cheaper.
482
+ */
483
+ async function readOutcomeBuckets(db, options) {
484
+ const [merges, briefRoots] = await Promise.all([readWindowMerges(db, options), readBriefOutcomeRoots(db, options)]);
485
+ const mergeRoots = [...new Set(merges.map((merge) => merge.rootId))];
486
+ const [rootMerges, treeCosts] = await Promise.all([readRootMergeCounts(db, mergeRoots), readTreeCosts$1(db, [...mergeRoots, ...briefRoots.map((root) => root.rootId)])]);
487
+ const dateLength = options.bucket === "day" ? 10 : 13;
488
+ const buckets = /* @__PURE__ */ new Map();
489
+ const bucketAt = (instant) => {
490
+ const date = instant.toISOString().slice(0, dateLength);
491
+ let bucket = buckets.get(date);
492
+ if (!bucket) {
493
+ bucket = {
494
+ date,
495
+ mergedCodeChangeCostUsd: 0,
496
+ mergedCodeChanges: 0,
497
+ outcomeCostUsd: 0,
498
+ outcomes: 0
499
+ };
500
+ buckets.set(date, bucket);
501
+ }
502
+ return bucket;
503
+ };
504
+ const changeCosts = /* @__PURE__ */ new Map();
505
+ for (const merge of merges) {
506
+ const share = (treeCosts.get(merge.rootId) ?? 0) / (rootMerges.get(merge.rootId) ?? 1);
507
+ const change = changeCosts.get(merge.changeId);
508
+ if (change) change.costUsd += share;
509
+ else changeCosts.set(merge.changeId, {
510
+ costUsd: share,
511
+ mergedAt: merge.mergedAt
512
+ });
513
+ }
514
+ for (const change of changeCosts.values()) {
515
+ const bucket = bucketAt(change.mergedAt);
516
+ bucket.mergedCodeChanges += 1;
517
+ bucket.mergedCodeChangeCostUsd += change.costUsd;
518
+ bucket.outcomes += 1;
519
+ bucket.outcomeCostUsd += change.costUsd;
520
+ }
521
+ for (const root of briefRoots) {
522
+ const bucket = bucketAt(root.lastActivityAt);
523
+ bucket.outcomes += 1;
524
+ bucket.outcomeCostUsd += treeCosts.get(root.rootId) ?? 0;
525
+ }
526
+ return [...buckets.values()];
527
+ }
528
+ async function readWindowMerges(db, options) {
529
+ return (await db.selectDistinct({
530
+ changeId: changes.id,
531
+ mergedAt: changes.mergedAt,
532
+ rootId: linkedRoot
533
+ }).from(changes).innerJoin(linked, linksChange).where(and(eq(changes.state, "merged"), gte(changes.mergedAt, options.start), lte(changes.mergedAt, options.end)))).flatMap(({ changeId, mergedAt, rootId }) => mergedAt && rootId ? [{
534
+ changeId,
535
+ mergedAt,
536
+ rootId
537
+ }] : []);
538
+ }
539
+ async function readBriefOutcomeRoots(db, options) {
540
+ const roots = juniorConversations;
541
+ const briefs = juniorConversationBriefs;
542
+ const latestBrief = db.select({ status: sql`${briefs.content}->'outcome'->>'status'`.as("status") }).from(briefs).where(eq(briefs.conversationId, roots.conversationId)).orderBy(desc(briefs.version)).limit(1).as("latest_brief");
543
+ return await db.select({
544
+ lastActivityAt: roots.lastActivityAt,
545
+ rootId: roots.conversationId
546
+ }).from(roots).innerJoinLateral(latestBrief, sql`true`).where(and(isNull(roots.parentConversationId), gte(roots.lastActivityAt, options.start), lte(roots.lastActivityAt, options.end), inArray(latestBrief.status, ["done", "answered"]), notExists(db.select({ id: changes.id }).from(changes).innerJoin(linked, linksChange).where(eq(linkedRoot, roots.conversationId)))));
547
+ }
548
+ /** Merged code changes of all time per root, so each merge gets its share. */
549
+ async function readRootMergeCounts(db, rootIds) {
550
+ if (!rootIds.length) return /* @__PURE__ */ new Map();
551
+ const rows = await db.select({
552
+ merged: countDistinct(changes.id),
553
+ rootId: linkedRoot
554
+ }).from(changes).innerJoin(linked, linksChange).where(and(eq(changes.state, "merged"), inArray(linkedRoot, [...rootIds]))).groupBy(linkedRoot);
555
+ return new Map(rows.flatMap((row) => row.rootId ? [[row.rootId, row.merged]] : []));
556
+ }
557
+ async function readTreeCosts$1(db, rootIds) {
558
+ if (!rootIds.length) return /* @__PURE__ */ new Map();
559
+ const conversations = juniorConversations;
560
+ const ids = [...new Set(rootIds)];
561
+ const treeRoot = sql`coalesce(${conversations.rootConversationId}, ${conversations.conversationId})`;
562
+ const rows = await db.select({
563
+ costUsd: sql`coalesce(sum(${conversationUsageCostExpr(conversations.usage)}), 0)::double precision`,
564
+ rootId: treeRoot
565
+ }).from(conversations).where(or(inArray(conversations.rootConversationId, ids), inArray(conversations.conversationId, ids))).groupBy(treeRoot);
566
+ return new Map(rows.flatMap((row) => row.rootId ? [[row.rootId, row.costUsd]] : []));
567
+ }
459
568
  // src/api/conversations/stats.query.ts
460
569
  const treeConversation$1 = alias(juniorConversations, "stats_tree_conversation");
461
570
  const treeAggregateColumns$1 = conversationAggregateColumns({
@@ -520,27 +629,37 @@ function statsWindow(nowMs) {
520
629
  const HOUR_MS = 36e5;
521
630
  /** Keep 7d of hours so clients can roll 7d charts into 6h buckets. */
522
631
  const WINDOW_HOURS = 168;
523
- function applyMetricBuckets(rows, metrics) {
524
- const byDate = new Map(rows.map((row) => [row.date, {
525
- ...row,
632
+ function emptyMetricRow(date) {
633
+ return {
526
634
  cachedInputTokens: null,
527
635
  cacheCreationTokens: null,
636
+ conversations: 0,
528
637
  costUsd: null,
638
+ date,
529
639
  durationMs: 0,
530
640
  inputTokens: null,
641
+ mergedCodeChangeCostUsd: null,
642
+ mergedCodeChanges: null,
643
+ outcomeCostUsd: null,
644
+ outcomes: null,
531
645
  tokens: null
646
+ };
647
+ }
648
+ function applyMetricBuckets(rows, metrics, outcomes) {
649
+ const byDate = new Map(rows.map((row) => [row.date, {
650
+ ...emptyMetricRow(row.date),
651
+ conversations: row.conversations
532
652
  }]));
653
+ for (const bucket of outcomes) {
654
+ const row = byDate.get(bucket.date) ?? emptyMetricRow(bucket.date);
655
+ row.mergedCodeChanges = bucket.mergedCodeChanges;
656
+ row.mergedCodeChangeCostUsd = bucket.mergedCodeChangeCostUsd;
657
+ row.outcomes = bucket.outcomes;
658
+ row.outcomeCostUsd = bucket.outcomeCostUsd;
659
+ byDate.set(bucket.date, row);
660
+ }
533
661
  for (const metric of metrics) {
534
- const row = byDate.get(metric.date) ?? {
535
- cachedInputTokens: null,
536
- cacheCreationTokens: null,
537
- conversations: 0,
538
- costUsd: null,
539
- date: metric.date,
540
- durationMs: 0,
541
- inputTokens: null,
542
- tokens: null
543
- };
662
+ const row = byDate.get(metric.date) ?? emptyMetricRow(metric.date);
544
663
  if (metric.metric === "cached_input_tokens") row.cachedInputTokens = metric.value;
545
664
  else if (metric.metric === "cache_creation_tokens") row.cacheCreationTokens = metric.value;
546
665
  else if (metric.metric === "cost_usd") row.costUsd = metric.value;
@@ -560,6 +679,12 @@ function metricPoint(date, row) {
560
679
  ...row?.cacheCreationTokens !== null && row?.cacheCreationTokens !== void 0 ? { cacheCreationTokens: row.cacheCreationTokens } : void 0,
561
680
  ...row?.costUsd !== null && row?.costUsd !== void 0 ? { costUsd: addUsd$2(void 0, row.costUsd) } : void 0,
562
681
  ...row?.inputTokens !== null && row?.inputTokens !== void 0 ? { inputTokens: row.inputTokens } : void 0,
682
+ ...row?.outcomes !== null && row?.outcomes !== void 0 ? {
683
+ mergedCodeChangeCostUsd: addUsd$2(void 0, row.mergedCodeChangeCostUsd ?? 0),
684
+ mergedCodeChanges: row.mergedCodeChanges ?? 0,
685
+ outcomeCostUsd: addUsd$2(void 0, row.outcomeCostUsd ?? 0),
686
+ outcomes: row.outcomes
687
+ } : void 0,
563
688
  ...row?.tokens !== null && row?.tokens !== void 0 ? { tokens: row.tokens } : void 0
564
689
  };
565
690
  }
@@ -679,7 +804,7 @@ async function aggregateStats(db, start, end) {
679
804
  ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
680
805
  'YYYY-MM-DD"T"HH24'
681
806
  )`;
682
- const [totalsRows, actorRows, locationRows, metricRows, metricHourRows, dayMetrics, hourMetrics] = await Promise.all([
807
+ const [totalsRows, actorRows, locationRows, metricRows, metricHourRows, dayMetrics, hourMetrics, dayOutcomes, hourOutcomes] = await Promise.all([
683
808
  db.select(treeAggregateColumns$1).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).where(where),
684
809
  db.select({
685
810
  identityDisplayName: juniorIdentities.displayName,
@@ -716,13 +841,23 @@ async function aggregateStats(db, start, end) {
716
841
  bucket: "hour",
717
842
  start: hourStart,
718
843
  end
844
+ }),
845
+ readOutcomeBuckets(db, {
846
+ bucket: "day",
847
+ start,
848
+ end
849
+ }),
850
+ readOutcomeBuckets(db, {
851
+ bucket: "hour",
852
+ start: hourStart,
853
+ end
719
854
  })
720
855
  ]);
721
856
  return {
722
857
  actorRows,
723
858
  locationRows,
724
- metricHourRows: applyMetricBuckets(metricHourRows, hourMetrics),
725
- metricRows: applyMetricBuckets(metricRows, dayMetrics),
859
+ metricHourRows: applyMetricBuckets(metricHourRows, hourMetrics, hourOutcomes),
860
+ metricRows: applyMetricBuckets(metricRows, dayMetrics, dayOutcomes),
726
861
  totals: totalsRows[0]
727
862
  };
728
863
  }
@@ -895,13 +1030,12 @@ function createConversationRoutes(options) {
895
1030
  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"))));
896
1031
  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"))));
897
1032
  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"))));
898
- 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"))));
899
1033
  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"))));
900
1034
  app.put("/:conversationId/read-position", requireViewer, validateRequest("param", conversationParamsSchema, "Invalid route parameters."), validateRequest("json", conversationReadPositionSchema, "Invalid request body."), async (context) => {
901
1035
  const viewer = context.get("viewer");
902
1036
  const { conversationId } = context.req.valid("param");
903
1037
  const body = context.req.valid("json");
904
- return jsonResponse(conversationReadReportSchema, await reportConversationRead(viewer, conversationId, body));
1038
+ return jsonResponse(conversationReadPositionSchema, await reportConversationRead(viewer, conversationId, body));
905
1039
  });
906
1040
  app.put("/pin-order", requireViewer, validateRequest("json", reorderPinnedConversationsBodySchema, "Invalid request body."), async (context) => jsonResponse(reorderPinnedConversationsResponseSchema, await reorderPinnedConversations(context.get("viewer"), context.req.valid("json"))));
907
1041
  app.post("/archive-done", requireViewer, async (context) => jsonResponse(archiveDoneConversationsResponseSchema, await archiveViewerDoneConversations(context.get("viewer"))));
@@ -1014,239 +1148,6 @@ function createConversationRoutes(options) {
1014
1148
  });
1015
1149
  return app;
1016
1150
  }
1017
- // src/api/board/columns.ts
1018
- const DONE_WINDOW_MS = 216e5;
1019
- /** Choose the column of a code change that Junior created. */
1020
- function codeChangeColumn(args) {
1021
- if (args.state === "merged") return args.mergedAtMs !== void 0 && args.nowMs - args.mergedAtMs <= DONE_WINDOW_MS ? "done" : void 0;
1022
- if (args.state === "closed") return void 0;
1023
- return args.hasReadyNotice ? "ready" : "in_progress";
1024
- }
1025
- /** Choose the column of a ticket linked to a Conversation. */
1026
- function ticketColumn(args) {
1027
- if (args.status === "closed") return args.nowMs - args.updatedAtMs <= DONE_WINDOW_MS ? "done" : void 0;
1028
- if (args.status !== "open") return void 0;
1029
- return args.working ? "in_progress" : "planned";
1030
- }
1031
- // src/api/board/read.ts
1032
- /** Root Conversations with activity in this window feed the Board. */
1033
- const ACTIVE_WINDOW_MS = 12096e5;
1034
- /** Bound the Board to the viewer's most recent root Conversations. */
1035
- const ROOT_LIMIT = 200;
1036
- function parentOf(nodes, node) {
1037
- return node.parentConversationId ? nodes.get(node.parentConversationId) : void 0;
1038
- }
1039
- /**
1040
- * A card belongs to the nearest root or Thread. People do not message a
1041
- * Task, so its work shows on its parent. A row from an older deploy has no
1042
- * kind; a child without a kind is treated as a Task. A Conversation shows
1043
- * only while it and every ancestor are unarchived.
1044
- */
1045
- function homeId(nodes, conversationId) {
1046
- const start = nodes.get(conversationId);
1047
- for (let node = start; node; node = parentOf(nodes, node)) if (node.archived) return void 0;
1048
- let node = start;
1049
- while (node && (node.kind === "task" || !node.kind && node.parentConversationId)) node = parentOf(nodes, node);
1050
- return node?.conversationId;
1051
- }
1052
- function rootOf(nodes, node) {
1053
- let current = node;
1054
- for (let parent = parentOf(nodes, current); parent; parent = parentOf(nodes, parent)) current = parent;
1055
- return current;
1056
- }
1057
- async function readViewerTrees(userId, nowMs) {
1058
- const db = getDb();
1059
- const rootIds = (await db.select({ conversationId: juniorConversations.conversationId }).from(juniorConversations).where(and(conversationIsMemberRoot({ userId }), listedConversation(), isNull(juniorConversations.archivedAt), gte(juniorConversations.lastActivityAt, /* @__PURE__ */ new Date(nowMs - ACTIVE_WINDOW_MS)))).orderBy(desc(juniorConversations.lastActivityAt)).limit(ROOT_LIMIT)).map((row) => row.conversationId);
1060
- if (rootIds.length === 0) return {
1061
- nodes: /* @__PURE__ */ new Map(),
1062
- rootIds
1063
- };
1064
- const rows = await db.select({
1065
- archivedAt: juniorConversations.archivedAt,
1066
- conversationId: juniorConversations.conversationId,
1067
- createdAt: juniorConversations.createdAt,
1068
- kind: juniorConversations.kind,
1069
- parentConversationId: juniorConversations.parentConversationId,
1070
- status: juniorConversations.executionStatus,
1071
- title: juniorConversations.title
1072
- }).from(juniorConversations).where(or(inArray(juniorConversations.conversationId, rootIds), inArray(juniorConversations.rootConversationId, rootIds)));
1073
- return {
1074
- nodes: new Map(rows.map((row) => [row.conversationId, {
1075
- archived: row.archivedAt !== null,
1076
- conversationId: row.conversationId,
1077
- createdAtMs: row.createdAt.getTime(),
1078
- kind: row.kind,
1079
- parentConversationId: row.parentConversationId,
1080
- status: row.status,
1081
- title: row.title
1082
- }])),
1083
- rootIds
1084
- };
1085
- }
1086
- /**
1087
- * Read the viewer's Board: the code changes and tickets of their recent
1088
- * Conversations, each in one column. See `./columns` for the column rules.
1089
- */
1090
- async function readBoard(args) {
1091
- const db = getDb();
1092
- const { nodes, rootIds } = await readViewerTrees(args.userId, args.nowMs);
1093
- const treeIds = [...nodes.keys()];
1094
- if (treeIds.length === 0) return {
1095
- cards: [],
1096
- doneWindowHours: 6
1097
- };
1098
- const doneSince = /* @__PURE__ */ new Date(args.nowMs - 216e5);
1099
- const [codeChanges, ticketRows, needsViewerRows, participants] = await Promise.all([
1100
- db.select({
1101
- conversationIds: juniorCodeChanges.conversationIds,
1102
- id: juniorCodeChanges.id,
1103
- mergedAt: juniorCodeChanges.mergedAt,
1104
- number: juniorCodeChanges.number,
1105
- repository: juniorCodeRepositories.name,
1106
- state: juniorCodeChanges.state,
1107
- title: juniorCodeChanges.title,
1108
- updatedAt: juniorCodeChanges.updatedAt,
1109
- url: juniorCodeChanges.url
1110
- }).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))),
1111
- db.select({
1112
- annotation: juniorConversationAnnotations.annotation,
1113
- conversationId: juniorConversationAnnotations.conversationId,
1114
- key: juniorConversationAnnotations.key,
1115
- plugin: juniorConversationAnnotations.plugin,
1116
- updatedAt: juniorConversationAnnotations.updatedAt
1117
- }).from(juniorConversationAnnotations).where(and(inArray(juniorConversationAnnotations.conversationId, treeIds), sql`${juniorConversationAnnotations.annotation}->>'objectType' = 'task'`)),
1118
- db.selectDistinct({ conversationId: juniorReviewItemConversations.conversationId }).from(juniorReviewItemConversations).innerJoin(juniorReviewItems, eq(juniorReviewItems.id, juniorReviewItemConversations.itemId)).where(and(inArray(juniorReviewItemConversations.conversationId, treeIds), reviewItemNeedsUser(args.userId))),
1119
- readConversationParticipants(db, rootIds)
1120
- ]);
1121
- const codeChangeUrls = codeChanges.flatMap((change) => change.state === "open" && change.url ? [change.url] : []);
1122
- const readyUrls = new Set(codeChangeUrls.length === 0 ? [] : (await db.select({ subjectId: juniorReviewItems.subjectId }).from(juniorReviewItems).where(and(eq(juniorReviewItems.status, "open"), like(juniorReviewItems.dedupeKey, `${PLUGIN_REVIEW_ITEM_KEY_PREFIX}%`), inArray(juniorReviewItems.subjectId, codeChangeUrls)))).flatMap((row) => row.subjectId ? [row.subjectId] : []));
1123
- const homes = /* @__PURE__ */ new Map();
1124
- const workingHomes = /* @__PURE__ */ new Set();
1125
- const needsViewerHomes = /* @__PURE__ */ new Set();
1126
- for (const node of nodes.values()) {
1127
- if (node.status !== "running" && node.status !== "pending") continue;
1128
- const home = homeId(nodes, node.conversationId);
1129
- if (home) workingHomes.add(home);
1130
- }
1131
- for (const row of needsViewerRows) {
1132
- const home = homeId(nodes, row.conversationId);
1133
- if (home) needsViewerHomes.add(home);
1134
- }
1135
- const homeFor = (conversationIds) => {
1136
- let node;
1137
- for (const conversationId of conversationIds) {
1138
- const candidateId = homeId(nodes, conversationId);
1139
- const candidate = candidateId ? nodes.get(candidateId) : void 0;
1140
- if (!candidate) continue;
1141
- if (!node || candidate.createdAtMs < node.createdAtMs || candidate.createdAtMs === node.createdAtMs && candidate.conversationId < node.conversationId) node = candidate;
1142
- }
1143
- if (!node) return void 0;
1144
- const id = node.conversationId;
1145
- const cached = homes.get(id);
1146
- if (cached) return cached;
1147
- const root = rootOf(nodes, node);
1148
- const home = {
1149
- conversation: {
1150
- conversationId: id,
1151
- ...node.title ? { title: node.title } : void 0,
1152
- ...root !== node && root.title ? { rootTitle: root.title } : void 0
1153
- },
1154
- needsViewer: needsViewerHomes.has(id),
1155
- participants: participants.get(root.conversationId) ?? [],
1156
- working: workingHomes.has(id)
1157
- };
1158
- homes.set(id, home);
1159
- return home;
1160
- };
1161
- const cards = [];
1162
- for (const change of codeChanges) {
1163
- const home = homeFor(change.conversationIds);
1164
- if (!home) continue;
1165
- const mergedAtMs = change.mergedAt?.getTime();
1166
- const column = codeChangeColumn({
1167
- hasReadyNotice: Boolean(change.url && readyUrls.has(change.url)),
1168
- ...mergedAtMs !== void 0 ? { mergedAtMs } : void 0,
1169
- nowMs: args.nowMs,
1170
- state: change.state
1171
- });
1172
- if (!column) continue;
1173
- const label = `${change.repository}#${change.number}`;
1174
- cards.push({
1175
- column,
1176
- conversation: home.conversation,
1177
- key: `code_change:${change.id}`,
1178
- label,
1179
- needsViewer: home.needsViewer,
1180
- objectType: "code_change",
1181
- participants: home.participants,
1182
- status: change.state,
1183
- title: change.title ?? label,
1184
- updatedAt: (change.mergedAt ?? change.updatedAt).toISOString(),
1185
- ...change.url ? { url: change.url } : void 0,
1186
- working: home.working
1187
- });
1188
- }
1189
- const tickets = /* @__PURE__ */ new Map();
1190
- for (const row of ticketRows) {
1191
- const key = `${row.plugin}:${row.key}`;
1192
- const current = tickets.get(key);
1193
- if (!current) {
1194
- tickets.set(key, {
1195
- conversationIds: /* @__PURE__ */ new Set([row.conversationId]),
1196
- latest: row
1197
- });
1198
- continue;
1199
- }
1200
- current.conversationIds.add(row.conversationId);
1201
- if (row.updatedAt > current.latest.updatedAt) current.latest = row;
1202
- }
1203
- for (const [key, ticket] of tickets) {
1204
- const parsed = conversationAnnotationInputSchema.safeParse(ticket.latest.annotation);
1205
- if (!parsed.success) continue;
1206
- const annotation = parsed.data;
1207
- const status = annotation.status;
1208
- if (!status) continue;
1209
- const home = homeFor(ticket.conversationIds);
1210
- if (!home) continue;
1211
- const column = ticketColumn({
1212
- nowMs: args.nowMs,
1213
- status,
1214
- updatedAtMs: ticket.latest.updatedAt.getTime(),
1215
- working: home.working
1216
- });
1217
- if (!column) continue;
1218
- const title = annotation.kind === "object" ? annotation.title : annotation.description ?? annotation.label;
1219
- cards.push({
1220
- column,
1221
- conversation: home.conversation,
1222
- key: `ticket:${key}`,
1223
- label: annotation.label,
1224
- needsViewer: home.needsViewer,
1225
- objectType: "task",
1226
- participants: home.participants,
1227
- status,
1228
- title,
1229
- updatedAt: ticket.latest.updatedAt.toISOString(),
1230
- ...annotation.url ? { url: annotation.url } : void 0,
1231
- working: home.working
1232
- });
1233
- }
1234
- cards.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
1235
- return {
1236
- cards,
1237
- doneWindowHours: 6
1238
- };
1239
- }
1240
- // src/api/board/routes.ts
1241
- /** Create the viewer's Board API. */
1242
- function createBoardRoutes() {
1243
- const app = new Hono();
1244
- app.get("/", requireViewer, async (context) => jsonResponse(boardReportSchema, await readBoard({
1245
- nowMs: Date.now(),
1246
- userId: context.get("viewer").id
1247
- }), { headers: { "cache-control": "private, no-store" } }));
1248
- return app;
1249
- }
1250
1151
  // src/api/code/overview.ts
1251
1152
  const DAY_MS = 864e5;
1252
1153
  const WINDOW_DAYS = 30;
@@ -1255,44 +1156,6 @@ const WINDOW_DAYS = 30;
1255
1156
  * stale open change is not cut off by newer completed changes.
1256
1157
  */
1257
1158
  const PERSON_CHANGE_LIMIT = 100;
1258
- const summaryRowSchema = z.object({
1259
- closed: z.number().int().nonnegative(),
1260
- costUsd: z.number().nonnegative().nullable(),
1261
- created: z.number().int().nonnegative(),
1262
- medianCostUsd: z.number().nonnegative().nullable(),
1263
- medianMergeTimeMs: z.number().nonnegative().nullable(),
1264
- merged: z.number().int().nonnegative(),
1265
- open: z.number().int().nonnegative()
1266
- }).strict().transform((row) => ({
1267
- ...row,
1268
- costUsd: row.costUsd ?? void 0,
1269
- medianCostUsd: row.medianCostUsd ?? void 0,
1270
- medianMergeTimeMs: row.medianMergeTimeMs ?? void 0
1271
- }));
1272
- const repositoryRowSchema = z.object({
1273
- closed: z.number().int().nonnegative(),
1274
- created: z.number().int().nonnegative(),
1275
- id: z.string().min(1),
1276
- medianCostUsd: z.number().nonnegative().nullable(),
1277
- merged: z.number().int().nonnegative(),
1278
- name: z.string().min(1),
1279
- open: z.number().int().nonnegative(),
1280
- provider: z.string().min(1),
1281
- url: z.string().nullable()
1282
- }).strict().transform((row) => ({
1283
- ...row,
1284
- medianCostUsd: row.medianCostUsd ?? void 0
1285
- }));
1286
- const activityDaySchema = z.object({
1287
- closed: z.number().int().nonnegative(),
1288
- created: z.number().int().nonnegative(),
1289
- date: z.string().regex(/^\d{4}-\d{2}-\d{2}(T\d{2})?$/),
1290
- merged: z.number().int().nonnegative()
1291
- }).strict();
1292
- function queryRows(result) {
1293
- if (typeof result !== "object" || result === null || !("rows" in result) || !Array.isArray(result.rows)) throw new TypeError("Code overview query did not return rows");
1294
- return result.rows;
1295
- }
1296
1159
  function startOfUtcDay(timestampMs) {
1297
1160
  const date = new Date(timestampMs);
1298
1161
  date.setUTCHours(0, 0, 0, 0);
@@ -1302,39 +1165,65 @@ function mergeRate(merged, closed) {
1302
1165
  const completed = merged + closed;
1303
1166
  return completed > 0 ? merged / completed : void 0;
1304
1167
  }
1168
+ function median(values) {
1169
+ if (!values.length) return void 0;
1170
+ const sorted = [...values].sort((a, b) => a - b);
1171
+ const middle = (sorted.length - 1) / 2;
1172
+ return (sorted[Math.floor(middle)] + sorted[Math.ceil(middle)]) / 2;
1173
+ }
1174
+ /**
1175
+ * Count created, merged, and closed changes per UTC bucket, from `start`
1176
+ * through `end`. Every bucket is present, so charts get zero gaps.
1177
+ */
1178
+ function bucketActivity(changes, range) {
1179
+ const buckets = /* @__PURE__ */ new Map();
1180
+ for (let ms = range.start.getTime(); ms <= range.end.getTime(); ms += range.stepMs) {
1181
+ const date = new Date(ms).toISOString().slice(0, range.keyLength);
1182
+ buckets.set(date, {
1183
+ closed: 0,
1184
+ created: 0,
1185
+ date,
1186
+ merged: 0
1187
+ });
1188
+ }
1189
+ const add = (at, kind) => {
1190
+ if (!at || at < range.start) return;
1191
+ const bucket = buckets.get(at.toISOString().slice(0, range.keyLength));
1192
+ if (bucket) bucket[kind] += 1;
1193
+ };
1194
+ for (const change of changes) {
1195
+ add(change.openedAt, "created");
1196
+ add(change.mergedAt, "merged");
1197
+ if (change.state === "closed") add(change.closedAt, "closed");
1198
+ }
1199
+ return [...buckets.values()];
1200
+ }
1305
1201
  /**
1306
- * Sum conversation-tree cost for one set of conversation ids.
1307
- * Resolves each id to its root, then sums usage across that tree so child
1308
- * turns are included exactly once per unique conversation tree.
1202
+ * Read conversation-tree costs for the given linked conversation ids. The
1203
+ * returned function sums each tree once, child Conversations included, so a
1204
+ * change linked to two Conversations of one tree pays for that tree once.
1309
1205
  */
1310
- function conversationTreeCostExpr() {
1311
- return sql`
1312
- coalesce((
1313
- SELECT sum(
1314
- CASE
1315
- WHEN conversations.usage_json->'cost'->>'total' IS NOT NULL
1316
- THEN (conversations.usage_json->'cost'->>'total')::double precision
1317
- WHEN coalesce(
1318
- conversations.usage_json->'cost'->>'input',
1319
- conversations.usage_json->'cost'->>'output',
1320
- conversations.usage_json->'cost'->>'cacheRead',
1321
- conversations.usage_json->'cost'->>'cacheWrite'
1322
- ) IS NOT NULL
1323
- THEN coalesce((conversations.usage_json->'cost'->>'input')::double precision, 0)
1324
- + coalesce((conversations.usage_json->'cost'->>'output')::double precision, 0)
1325
- + coalesce((conversations.usage_json->'cost'->>'cacheRead')::double precision, 0)
1326
- + coalesce((conversations.usage_json->'cost'->>'cacheWrite')::double precision, 0)
1327
- ELSE 0
1328
- END
1329
- )
1330
- FROM junior_conversations AS conversations
1331
- WHERE conversations.root_conversation_id IN (
1332
- SELECT coalesce(roots.root_conversation_id, roots.conversation_id)
1333
- FROM junior_conversations AS roots
1334
- WHERE roots.conversation_id = ANY (conversation_ids.ids)
1335
- )
1336
- ), 0::double precision)
1337
- `;
1206
+ async function readTreeCosts(conversationIds) {
1207
+ const db = getDb();
1208
+ const conversations = juniorConversations;
1209
+ const ids = [...new Set(conversationIds)];
1210
+ const links = ids.length ? await db.select({
1211
+ conversationId: conversations.conversationId,
1212
+ rootId: sql`coalesce(${conversations.rootConversationId}, ${conversations.conversationId})`
1213
+ }).from(conversations).where(inArray(conversations.conversationId, ids)) : [];
1214
+ const rootOf = new Map(links.map((link) => [link.conversationId, link.rootId]));
1215
+ const rootIds = [...new Set(rootOf.values())];
1216
+ const trees = rootIds.length ? await db.select({
1217
+ costUsd: sql`coalesce(sum(${conversationUsageCostExpr(conversations.usage)}), 0)`.mapWith(Number),
1218
+ rootId: conversations.rootConversationId
1219
+ }).from(conversations).where(inArray(conversations.rootConversationId, rootIds)).groupBy(conversations.rootConversationId) : [];
1220
+ const costOf = new Map(trees.map((tree) => [tree.rootId, tree.costUsd]));
1221
+ return (linked) => {
1222
+ let total = 0;
1223
+ const roots = new Set(linked.flatMap((id) => rootOf.get(id) ?? []));
1224
+ for (const root of roots) total += costOf.get(root) ?? 0;
1225
+ return total;
1226
+ };
1338
1227
  }
1339
1228
  /** True when any linked conversation actor belongs to the subject user. */
1340
1229
  function ownedByUserSql(conversationIds, userId) {
@@ -1359,166 +1248,45 @@ async function readCodeWindows(args) {
1359
1248
  const windowStart = /* @__PURE__ */ new Date(args.nowMs - WINDOW_DAYS * DAY_MS);
1360
1249
  const activityStart = startOfUtcDay(args.nowMs - 89 * DAY_MS);
1361
1250
  const changes = juniorCodeChanges;
1362
- const scope = changeScopeFilter(args);
1363
- const conversationTreeCost = conversationTreeCostExpr();
1364
1251
  const activityHourEnd = new Date(args.nowMs);
1365
1252
  activityHourEnd.setUTCMinutes(0, 0, 0);
1366
1253
  const activityHourStart = /* @__PURE__ */ new Date(activityHourEnd.getTime() - 167 * (DAY_MS / 24));
1367
- const [summaryResult, activityResult, activityHourResult] = await Promise.all([
1368
- db.execute(sql`
1369
- WITH recent_changes AS (
1370
- SELECT
1371
- ${changes.id},
1372
- ${changes.openedAt},
1373
- ${changes.mergedAt},
1374
- ${changes.closedAt},
1375
- ${changes.state},
1376
- ${changes.conversationIds} AS conversation_ids
1377
- FROM ${changes}
1378
- ${scope ? sql`WHERE ${scope}` : sql``}
1379
- ), change_costs AS (
1380
- SELECT
1381
- recent_changes.id,
1382
- recent_changes.opened_at,
1383
- conversation_ids.ids AS ids,
1384
- ${conversationTreeCost} AS cost_usd
1385
- FROM recent_changes
1386
- CROSS JOIN LATERAL (
1387
- SELECT recent_changes.conversation_ids AS ids
1388
- ) AS conversation_ids
1389
- WHERE recent_changes.opened_at >= ${windowStart}
1390
- )
1391
- SELECT
1392
- count(*) FILTER (WHERE recent_changes.opened_at >= ${windowStart})::integer AS "created",
1393
- count(*) FILTER (WHERE recent_changes.merged_at >= ${windowStart})::integer AS "merged",
1394
- count(*) FILTER (
1395
- WHERE recent_changes.state = 'closed'
1396
- AND recent_changes.closed_at >= ${windowStart}
1397
- )::integer AS "closed",
1398
- count(*) FILTER (WHERE recent_changes.state = 'open')::integer AS "open",
1399
- (
1400
- percentile_cont(0.5) WITHIN GROUP (
1401
- ORDER BY extract(
1402
- epoch FROM (recent_changes.merged_at - recent_changes.opened_at)
1403
- ) * 1000
1404
- ) FILTER (
1405
- WHERE recent_changes.state = 'merged'
1406
- AND recent_changes.merged_at >= ${windowStart}
1407
- )
1408
- )::double precision AS "medianMergeTimeMs",
1409
- coalesce((
1410
- SELECT ${conversationTreeCost}
1411
- FROM (
1412
- SELECT ARRAY(
1413
- SELECT DISTINCT unnest(change_costs.ids)
1414
- FROM change_costs
1415
- ) AS ids
1416
- ) AS conversation_ids
1417
- ), 0)::double precision AS "costUsd",
1418
- (
1419
- SELECT percentile_cont(0.5) WITHIN GROUP (
1420
- ORDER BY change_costs.cost_usd
1421
- )
1422
- FROM change_costs
1423
- WHERE change_costs.cost_usd > 0
1424
- )::double precision AS "medianCostUsd"
1425
- FROM recent_changes
1426
- `),
1427
- db.execute(sql`
1428
- WITH days AS (
1429
- SELECT generate_series(
1430
- date_trunc('day', ${activityStart}::timestamptz AT TIME ZONE 'UTC'),
1431
- date_trunc('day', ${windowEnd}::timestamptz AT TIME ZONE 'UTC'),
1432
- interval '1 day'
1433
- ) AS day
1434
- ), daily AS (
1435
- SELECT
1436
- date_trunc('day', event_at AT TIME ZONE 'UTC') AS day,
1437
- count(*) FILTER (WHERE kind = 'created')::integer AS created,
1438
- count(*) FILTER (WHERE kind = 'merged')::integer AS merged,
1439
- count(*) FILTER (WHERE kind = 'closed')::integer AS closed
1440
- FROM (
1441
- SELECT ${changes.openedAt} AS event_at, 'created'::text AS kind
1442
- FROM ${changes}
1443
- WHERE ${changes.openedAt} >= ${activityStart}
1444
- ${scope ? sql`AND ${scope}` : sql``}
1445
- UNION ALL
1446
- SELECT ${changes.mergedAt} AS event_at, 'merged'::text AS kind
1447
- FROM ${changes}
1448
- WHERE ${changes.mergedAt} >= ${activityStart}
1449
- ${scope ? sql`AND ${scope}` : sql``}
1450
- UNION ALL
1451
- SELECT ${changes.closedAt} AS event_at, 'closed'::text AS kind
1452
- FROM ${changes}
1453
- WHERE ${changes.state} = 'closed'
1454
- AND ${changes.closedAt} >= ${activityStart}
1455
- ${scope ? sql`AND ${scope}` : sql``}
1456
- ) AS events
1457
- GROUP BY date_trunc('day', event_at AT TIME ZONE 'UTC')
1458
- )
1459
- SELECT
1460
- to_char(days.day, 'YYYY-MM-DD') AS "date",
1461
- coalesce(daily.created, 0)::integer AS "created",
1462
- coalesce(daily.merged, 0)::integer AS "merged",
1463
- coalesce(daily.closed, 0)::integer AS "closed"
1464
- FROM days
1465
- LEFT JOIN daily ON daily.day = days.day
1466
- ORDER BY days.day
1467
- `),
1468
- db.execute(sql`
1469
- WITH hours AS (
1470
- SELECT generate_series(
1471
- date_trunc('hour', ${activityHourStart}::timestamptz AT TIME ZONE 'UTC'),
1472
- date_trunc('hour', ${activityHourEnd}::timestamptz AT TIME ZONE 'UTC'),
1473
- interval '1 hour'
1474
- ) AS hour
1475
- ), hourly AS (
1476
- SELECT
1477
- date_trunc('hour', event_at AT TIME ZONE 'UTC') AS hour,
1478
- count(*) FILTER (WHERE kind = 'created')::integer AS created,
1479
- count(*) FILTER (WHERE kind = 'merged')::integer AS merged,
1480
- count(*) FILTER (WHERE kind = 'closed')::integer AS closed
1481
- FROM (
1482
- SELECT ${changes.openedAt} AS event_at, 'created'::text AS kind
1483
- FROM ${changes}
1484
- WHERE ${changes.openedAt} >= ${activityHourStart}
1485
- ${scope ? sql`AND ${scope}` : sql``}
1486
- UNION ALL
1487
- SELECT ${changes.mergedAt} AS event_at, 'merged'::text AS kind
1488
- FROM ${changes}
1489
- WHERE ${changes.mergedAt} >= ${activityHourStart}
1490
- ${scope ? sql`AND ${scope}` : sql``}
1491
- UNION ALL
1492
- SELECT ${changes.closedAt} AS event_at, 'closed'::text AS kind
1493
- FROM ${changes}
1494
- WHERE ${changes.state} = 'closed'
1495
- AND ${changes.closedAt} >= ${activityHourStart}
1496
- ${scope ? sql`AND ${scope}` : sql``}
1497
- ) AS events
1498
- GROUP BY date_trunc('hour', event_at AT TIME ZONE 'UTC')
1499
- )
1500
- SELECT
1501
- to_char(hours.hour, 'YYYY-MM-DD"T"HH24') AS "date",
1502
- coalesce(hourly.created, 0)::integer AS "created",
1503
- coalesce(hourly.merged, 0)::integer AS "merged",
1504
- coalesce(hourly.closed, 0)::integer AS "closed"
1505
- FROM hours
1506
- LEFT JOIN hourly ON hourly.hour = hours.hour
1507
- ORDER BY hours.hour
1508
- `)
1509
- ]);
1510
- const summary = summaryRowSchema.parse(queryRows(summaryResult)[0] ?? {
1511
- closed: 0,
1512
- costUsd: 0,
1513
- created: 0,
1514
- medianCostUsd: null,
1515
- medianMergeTimeMs: null,
1516
- merged: 0,
1517
- open: 0
1518
- });
1519
- const activityHours = z.array(activityDaySchema).parse(queryRows(activityHourResult));
1254
+ const rows = await db.select({
1255
+ closedAt: changes.closedAt,
1256
+ conversationIds: changes.conversationIds,
1257
+ mergedAt: changes.mergedAt,
1258
+ openedAt: changes.openedAt,
1259
+ state: changes.state
1260
+ }).from(changes).where(and(changeScopeFilter(args), or(gte(changes.openedAt, activityStart), gte(changes.mergedAt, activityStart), gte(changes.closedAt, activityStart), eq(changes.state, "open"))));
1261
+ const inWindow = (at) => at !== null && at >= windowStart;
1262
+ const created = rows.filter((row) => inWindow(row.openedAt));
1263
+ const merged = rows.filter((row) => inWindow(row.mergedAt));
1264
+ const closed = rows.filter((row) => row.state === "closed" && inWindow(row.closedAt));
1265
+ const createdConversationIds = created.flatMap((row) => row.conversationIds);
1266
+ const treeCost = await readTreeCosts(createdConversationIds);
1267
+ const changeCosts = created.map((row) => treeCost(row.conversationIds));
1268
+ const activityHours = bucketActivity(rows, {
1269
+ end: activityHourEnd,
1270
+ keyLength: 13,
1271
+ start: activityHourStart,
1272
+ stepMs: DAY_MS / 24
1273
+ });
1274
+ const summary = {
1275
+ closed: closed.length,
1276
+ costUsd: treeCost(createdConversationIds),
1277
+ created: created.length,
1278
+ medianCostUsd: median(changeCosts.filter((cost) => cost > 0)),
1279
+ medianMergeTimeMs: median(merged.flatMap((row) => row.state === "merged" && row.mergedAt ? [row.mergedAt.getTime() - row.openedAt.getTime()] : [])),
1280
+ merged: merged.length,
1281
+ open: rows.filter((row) => row.state === "open").length
1282
+ };
1520
1283
  return {
1521
- activityDays: z.array(activityDaySchema).parse(queryRows(activityResult)),
1284
+ activityDays: bucketActivity(rows, {
1285
+ end: startOfUtcDay(args.nowMs),
1286
+ keyLength: 10,
1287
+ start: activityStart,
1288
+ stepMs: DAY_MS
1289
+ }),
1522
1290
  activityHours,
1523
1291
  activitySixHours: sumUtcHoursIntoSixHours({
1524
1292
  empty: (date) => ({
@@ -1542,6 +1310,7 @@ async function readCodeWindows(args) {
1542
1310
  const codeChangeReportColumns = {
1543
1311
  closedAt: juniorCodeChanges.closedAt,
1544
1312
  id: juniorCodeChanges.id,
1313
+ lastActivityAt: juniorCodeChanges.lastActivityAt,
1545
1314
  mergedAt: juniorCodeChanges.mergedAt,
1546
1315
  number: juniorCodeChanges.number,
1547
1316
  openedAt: juniorCodeChanges.openedAt,
@@ -1556,6 +1325,7 @@ function codeChangeReport(change) {
1556
1325
  return {
1557
1326
  ...change,
1558
1327
  closedAt: change.closedAt?.toISOString(),
1328
+ lastActivityAt: change.lastActivityAt?.toISOString(),
1559
1329
  mergedAt: change.mergedAt?.toISOString(),
1560
1330
  openedAt: change.openedAt.toISOString(),
1561
1331
  title: change.title ?? void 0,
@@ -1568,74 +1338,42 @@ async function readCodeOverview(nowMs = Date.now()) {
1568
1338
  const changes = juniorCodeChanges;
1569
1339
  const repositories = juniorCodeRepositories;
1570
1340
  const windows = await readCodeWindows({ nowMs });
1571
- const conversationTreeCost = conversationTreeCostExpr();
1572
- const [repositoryResult, recentChanges] = await Promise.all([db.execute(sql`
1573
- WITH recent_changes AS (
1574
- SELECT
1575
- ${changes.id},
1576
- ${changes.repositoryId},
1577
- ${changes.openedAt},
1578
- ${changes.mergedAt},
1579
- ${changes.closedAt},
1580
- ${changes.state},
1581
- ${changes.conversationIds} AS conversation_ids
1582
- FROM ${changes}
1583
- WHERE ${changes.openedAt} >= ${windows.windowStart}
1584
- OR ${changes.mergedAt} >= ${windows.windowStart}
1585
- OR ${changes.closedAt} >= ${windows.windowStart}
1586
- OR ${changes.state} = 'open'
1587
- ), change_costs AS (
1588
- SELECT
1589
- recent_changes.repository_id,
1590
- conversation_ids.ids AS ids,
1591
- ${conversationTreeCost} AS cost_usd
1592
- FROM recent_changes
1593
- CROSS JOIN LATERAL (
1594
- SELECT recent_changes.conversation_ids AS ids
1595
- ) AS conversation_ids
1596
- WHERE recent_changes.opened_at >= ${windows.windowStart}
1597
- )
1598
- SELECT
1599
- ${repositories.id} AS "id",
1600
- ${repositories.name} AS "name",
1601
- ${repositories.provider} AS "provider",
1602
- ${repositories.url} AS "url",
1603
- count(recent_changes.id) FILTER (
1604
- WHERE recent_changes.opened_at >= ${windows.windowStart}
1605
- )::integer AS "created",
1606
- count(recent_changes.id) FILTER (
1607
- WHERE recent_changes.merged_at >= ${windows.windowStart}
1608
- )::integer AS "merged",
1609
- count(recent_changes.id) FILTER (
1610
- WHERE recent_changes.state = 'closed'
1611
- AND recent_changes.closed_at >= ${windows.windowStart}
1612
- )::integer AS "closed",
1613
- count(recent_changes.id) FILTER (
1614
- WHERE recent_changes.state = 'open'
1615
- )::integer AS "open",
1616
- (
1617
- SELECT percentile_cont(0.5) WITHIN GROUP (
1618
- ORDER BY change_costs.cost_usd
1619
- )
1620
- FROM change_costs
1621
- WHERE change_costs.repository_id = ${repositories.id}
1622
- AND change_costs.cost_usd > 0
1623
- )::double precision AS "medianCostUsd"
1624
- FROM ${repositories}
1625
- INNER JOIN recent_changes
1626
- ON recent_changes.repository_id = ${repositories.id}
1627
- GROUP BY ${repositories.id}
1628
- ORDER BY "merged" DESC, "created" DESC, ${repositories.name} ASC
1629
- LIMIT 25
1630
- `), db.select(codeChangeReportColumns).from(changes).innerJoin(repositories, eq(changes.repositoryId, repositories.id)).where(or(gte(changes.openedAt, windows.windowStart), gte(changes.mergedAt, windows.windowStart), gte(changes.closedAt, windows.windowStart), eq(changes.state, "open"))).orderBy(desc(changes.updatedAt)).limit(25)]);
1341
+ const windowStart = windows.windowStart;
1342
+ const created = sql`count(*) filter (where ${changes.openedAt} >= ${windowStart})`.mapWith(Number);
1343
+ const merged = sql`count(*) filter (where ${changes.mergedAt} >= ${windowStart})`.mapWith(Number);
1344
+ const recent = or(gte(changes.openedAt, windowStart), gte(changes.mergedAt, windowStart), gte(changes.closedAt, windowStart), eq(changes.state, "open"));
1345
+ const [repositoryRows, recentChanges] = await Promise.all([db.select({
1346
+ closed: sql`count(*) filter (where ${changes.state} = 'closed' and ${changes.closedAt} >= ${windowStart})`.mapWith(Number),
1347
+ created,
1348
+ id: repositories.id,
1349
+ merged,
1350
+ name: repositories.name,
1351
+ open: sql`count(*) filter (where ${changes.state} = 'open')`.mapWith(Number),
1352
+ provider: repositories.provider,
1353
+ url: repositories.url
1354
+ }).from(repositories).innerJoin(changes, eq(changes.repositoryId, repositories.id)).where(recent).groupBy(repositories.id).orderBy(desc(merged), desc(created), asc(repositories.name)).limit(25), db.select(codeChangeReportColumns).from(changes).innerJoin(repositories, eq(changes.repositoryId, repositories.id)).where(recent).orderBy(desc(changes.updatedAt)).limit(25)]);
1355
+ const repositoryChanges = repositoryRows.length ? await db.select({
1356
+ conversationIds: changes.conversationIds,
1357
+ repositoryId: changes.repositoryId
1358
+ }).from(changes).where(and(gte(changes.openedAt, windowStart), inArray(changes.repositoryId, repositoryRows.map((row) => row.id)))) : [];
1359
+ const treeCost = await readTreeCosts(repositoryChanges.flatMap((change) => change.conversationIds));
1360
+ const repositoryCosts = /* @__PURE__ */ new Map();
1361
+ for (const change of repositoryChanges) {
1362
+ const cost = treeCost(change.conversationIds);
1363
+ if (cost <= 0) continue;
1364
+ const costs = repositoryCosts.get(change.repositoryId) ?? [];
1365
+ costs.push(cost);
1366
+ repositoryCosts.set(change.repositoryId, costs);
1367
+ }
1631
1368
  return codeOverviewReportSchema.parse({
1632
1369
  activityDays: windows.activityDays,
1633
1370
  activityHours: windows.activityHours,
1634
1371
  activitySixHours: windows.activitySixHours,
1635
1372
  changes: recentChanges.map(codeChangeReport),
1636
1373
  generatedAt: windows.windowEnd.toISOString(),
1637
- repositories: z.array(repositoryRowSchema).parse(queryRows(repositoryResult)).map((repository) => ({
1374
+ repositories: repositoryRows.map((repository) => ({
1638
1375
  ...repository,
1376
+ medianCostUsd: median(repositoryCosts.get(repository.id) ?? []),
1639
1377
  mergeRate: mergeRate(repository.merged, repository.closed),
1640
1378
  url: repository.url ?? void 0
1641
1379
  })),
@@ -2667,7 +2405,7 @@ async function readPeoplePluginReports(args) {
2667
2405
  reports: [],
2668
2406
  source: "plugins"
2669
2407
  });
2670
- const { getPluginProfileReports } = await import("./projection-BzJQncZV.js").then((n) => n.jn);
2408
+ const { getPluginProfileReports } = await import("./projection-B08mfi0u.js").then((n) => n.qn);
2671
2409
  return pluginOperationalReportFeedSchema.parse({
2672
2410
  generatedAt: new Date(nowMs).toISOString(),
2673
2411
  reports: await getPluginProfileReports({
@@ -3696,7 +3434,7 @@ function readDescriptionText(home) {
3696
3434
  }
3697
3435
  /** Read discovered skills for runtime diagnostics and the Automation editor. */
3698
3436
  async function readSkillReports() {
3699
- const { discoverSkills } = await import("./skills-BZE2DP8I.js").then((n) => n.o);
3437
+ const { discoverSkills } = await import("./skills-B0m1nZ_j.js").then((n) => n.o);
3700
3438
  const skills = await discoverSkills();
3701
3439
  return skillReportsSchema.parse(skills.map((skill) => ({
3702
3440
  name: skill.name,
@@ -3710,7 +3448,7 @@ async function readSkillReports() {
3710
3448
  * what the skill tells Junior. Returns null when no skill has that name.
3711
3449
  */
3712
3450
  async function readSkillDetailReport(name) {
3713
- const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-BZE2DP8I.js").then((n) => n.o);
3451
+ const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-B0m1nZ_j.js").then((n) => n.o);
3714
3452
  const skill = findSkillByName(name, await discoverSkills());
3715
3453
  if (!skill) return null;
3716
3454
  const parsed = parseSkillFile(await fs.readFile(path.join(skill.skillPath, "SKILL.md"), "utf8"), skill.name);
@@ -3725,7 +3463,7 @@ async function readSkillDetailReport(name) {
3725
3463
  }
3726
3464
  /** Read safe configured plugin metadata for authenticated runtime diagnostics. */
3727
3465
  async function readPlugins() {
3728
- const { pluginCatalogRuntime } = await import("./catalog-runtime-DgouZKZm.js").then((n) => n.t);
3466
+ const { pluginCatalogRuntime } = await import("./catalog-runtime-0kuQqYL4.js").then((n) => n.t);
3729
3467
  return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
3730
3468
  configKeys: plugin.manifest.configKeys ?? [],
3731
3469
  description: plugin.manifest.description,
@@ -3737,7 +3475,7 @@ async function readPlugins() {
3737
3475
  async function readRuntimeInfoReport() {
3738
3476
  const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
3739
3477
  import("./package-discovery-DJhGdS4c.js").then((n) => n.r),
3740
- import("./catalog-runtime-DgouZKZm.js").then((n) => n.t),
3478
+ import("./catalog-runtime-0kuQqYL4.js").then((n) => n.t),
3741
3479
  readPlugins(),
3742
3480
  readSkillReports()
3743
3481
  ]);
@@ -3754,7 +3492,7 @@ async function readRuntimeInfoReport() {
3754
3492
  /** Read sanitized operational summaries contributed by plugins. */
3755
3493
  async function readPluginOperationalReportFeed() {
3756
3494
  const nowMs = Date.now();
3757
- const { getPluginOperationalReports } = await import("./projection-BzJQncZV.js").then((n) => n.jn);
3495
+ const { getPluginOperationalReports } = await import("./projection-B08mfi0u.js").then((n) => n.qn);
3758
3496
  return pluginOperationalReportFeedSchema.parse({
3759
3497
  source: "plugins",
3760
3498
  generatedAt: new Date(nowMs).toISOString(),
@@ -3787,7 +3525,6 @@ function createJuniorApi(options = {}) {
3787
3525
  queue,
3788
3526
  show: createSlackReviewItemShow(getProductionSlackAdapter)
3789
3527
  } }));
3790
- app.route("/api/board", createBoardRoutes());
3791
3528
  app.route("/api/code", createCodeRoutes());
3792
3529
  app.route("/api/connections", createConnectionRoutes());
3793
3530
  app.route("/api/notifications", createNotificationRoutes());