@sentry/junior 0.295.0 → 0.296.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 (62) hide show
  1. package/dist/{admin-ifgjyfpF.js → admin-z_lgDi-z.js} +2 -2
  2. package/dist/{agent-runner-DjMTPWEO.js → agent-runner-HoQiUKLL.js} +194 -132
  3. package/dist/api/schema.d.ts +1 -1
  4. package/dist/api/schema.js +1 -1
  5. package/dist/api.d.ts +1 -1
  6. package/dist/api.js +294 -328
  7. package/dist/{app-uiTzRbvq.d.ts → app-C75Ft-A_.d.ts} +2 -2
  8. package/dist/app.d.ts +1 -1
  9. package/dist/app.js +26 -26
  10. package/dist/{background-compaction-queue-DUkHZjmL.js → background-compaction-queue-Cre1wFt9.js} +4 -4
  11. package/dist/{briefs-CbNYM-q2.js → briefs-BXECHduJ.js} +2 -2
  12. package/dist/{catalog-runtime-DgouZKZm.js → catalog-runtime-CpCmlD9L.js} +1 -1
  13. package/dist/cli/chat.js +14 -14
  14. package/dist/cli/check.js +3 -3
  15. package/dist/cli/main.js +3 -3
  16. package/dist/cli/plugins.js +4 -4
  17. package/dist/cli/snapshot-create.js +4 -4
  18. package/dist/cli/upgrade.d.ts +1 -1
  19. package/dist/cli/upgrade.js +3 -3
  20. package/dist/{config-DvnTPCfp.js → config-CCPHvTqx.js} +18 -2
  21. package/dist/{connections-CWaIVl_1.js → connections-B5pWh8e2.js} +6 -6
  22. package/dist/{conversation-privacy-DPjv4SnA.js → conversation-privacy-CZD5soDW.js} +1 -1
  23. package/dist/{credential-sync-BhbaZfmO.js → credential-sync-DwLkIvXI.js} +13 -13
  24. package/dist/{db-CCUqQe0E.d.ts → db-B3iyr_Or.d.ts} +1 -1
  25. package/dist/{db-Dts2XvLu.js → db-C1M1y-bh.js} +17 -23
  26. package/dist/{executor-Ck73J0wP.js → executor-DUSEwXaO.js} +10 -4
  27. package/dist/instrumentation.js +19 -2
  28. package/dist/{logging-9OAq-fdg.js → logging-D0svFM8r.js} +1 -1
  29. package/dist/{message-CtaPzC7m.js → message-BFnIwKpx.js} +9 -9
  30. package/dist/nitro.d.ts +1 -1
  31. package/dist/nitro.js +2 -2
  32. package/dist/{oauth-callback-server-C_LXY1d4.js → oauth-callback-server-BXRtD6Fk.js} +2 -2
  33. package/dist/{projection-BzJQncZV.js → projection-B6VS7kbo.js} +156 -49
  34. package/dist/{prompt-Cbq5b4SO.js → prompt-CD11tfG8.js} +3 -3
  35. package/dist/{registry-cbpOxO4M.js → registry-CHewwYEo.js} +1 -1
  36. package/dist/{resolve-t-pmRdwS.js → resolve-1owMH4qo.js} +3 -3
  37. package/dist/{result-DhgjR3nQ.js → result-CEqQFrEf.js} +8 -8
  38. package/dist/{runner-CHv9X9TH.js → runner-BtWvJslp.js} +7 -7
  39. package/dist/{sandbox-egress-signals-Yy3fSCbg.js → sandbox-egress-signals-ByftwJVt.js} +1 -1
  40. package/dist/{schema-TSEisVJR.d.ts → schema-Ct1Zf2xy.d.ts} +16 -0
  41. package/dist/{schema-BhneuGYv.js → schema-D2iGyYIp.js} +11 -0
  42. package/dist/{service-account-C4rBP8ne.js → service-account-BZEuMKdo.js} +3 -3
  43. package/dist/{service-account-DjPIwCMj.js → service-account-DLoeoHww.js} +3 -3
  44. package/dist/{session-stop-DkxI5vc3.js → session-stop-hYNTNpVf.js} +14 -14
  45. package/dist/{skills-BZE2DP8I.js → skills-DXgd5Inh.js} +3 -3
  46. package/dist/{spawn-BvULxIiu.js → spawn-YeqlNDv8.js} +5 -5
  47. package/dist/{state-CO9ETDzk.js → state-C3CbtD_m.js} +2 -2
  48. package/dist/{stop-CL-rdtQb.js → stop-Cze_pEL8.js} +288 -246
  49. package/dist/{store-DgD78_NK.js → store-CZ9vqR4P.js} +3 -3
  50. package/dist/{task-runner-CKOj6xla.js → task-runner-CMiNGsER.js} +274 -250
  51. package/dist/{turn-failure-response-BTSo6SMJ.js → turn-failure-response-pXhZ2wMK.js} +11 -8
  52. package/dist/{validation-CXeYgBzq.js → validation-Du7NdkOR.js} +1 -1
  53. package/dist/{version-AQa7Fr2H.js → version-EN3Wnq-R.js} +1 -1
  54. package/dist/version.js +1 -1
  55. package/dist/{viewer-Bqkb678l.js → viewer-Agxi_o5c.js} +3 -3
  56. package/dist/{warmup-h6u1e9n0.js → warmup-CY2ArYag.js} +251 -103
  57. package/dist/{work-yN_GAuXY.js → work-EA98F0ia.js} +11 -11
  58. package/dist/{worker-Hl7N292I.js → worker-BALVdWbv.js} +6 -6
  59. package/migrations/0101_drop_legacy_columns.sql +12 -0
  60. package/migrations/meta/0101_snapshot.json +4496 -0
  61. package/migrations/meta/_journal.json +7 -0
  62. package/package.json +5 -4
package/dist/api.js CHANGED
@@ -1,34 +1,34 @@
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 { $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-B6VS7kbo.js";
2
+ import { L as escapeXml, Y as getAttachmentStorage, n as botConfig } from "./config-CCPHvTqx.js";
3
+ import { m as logInfo, p as logException } from "./logging-D0svFM8r.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, o as getDb, s as getSqlExecutor, tt as nextDetailVersion, v as loadConversationSlackTenantIds } from "./db-C1M1y-bh.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, b as juniorConversationBriefs, j as juniorIdentities, l as juniorReviewItems, s as juniorReviewItemConversations, w as juniorConversationEvents } from "./executor-DUSEwXaO.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-CpCmlD9L.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-HoQiUKLL.js";
10
+ import { n as briefEntriesFromReportEvents, u as completeText } from "./prompt-CD11tfG8.js";
11
+ import { c as readViewerAvatarUrl, d as updateViewerDisplayName, l as resolveViewerUser, m as readAvatarImage, t as findUserByEmail } from "./viewer-Agxi_o5c.js";
12
+ import { a as getStateAdapter } from "./state-C3CbtD_m.js";
13
13
  import { r as notificationScheduleSchema } from "./schedule-cP0AACm1.js";
14
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";
15
+ import { a as segmentGapsKey, h as gapHistogramReport, u as GAP_SEGMENTS } from "./warmup-CY2ArYag.js";
16
+ import { g as getVercelConversationWorkQueue } from "./background-compaction-queue-Cre1wFt9.js";
17
+ import { O as getEventCatalog, et as readUserCustomization, rt as isExperimentalFeatureEnabled, tt as saveUserCustomization } from "./session-stop-hYNTNpVf.js";
18
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";
19
+ import { s as getSandboxResources, t as getCachedSnapshot } from "./resolve-1owMH4qo.js";
20
+ import { _t as conversationRangeColumns, bt as automationEventCatalog, gt as conversationAggregateColumns, mt as readAutomationTitlesByConversationId, rt as AutomationConflictError, vt as conversationUsageCostExpr } from "./task-runner-CMiNGsER.js";
21
+ import { n as finishServiceAccountSignIn, o as serviceAccountPlugins, r as getServiceAccountStatus, s as startServiceAccountSignIn, t as disconnectServiceAccount } from "./service-account-DLoeoHww.js";
22
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
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";
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, b as conversationSummaryFromStoredConversation, 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 } from "./stop-Cze_pEL8.js";
25
+ import { a as startConnection, n as isConnectableProvider, r as listConnections, s as htmlCallbackResponse, t as disconnectConnection } from "./connections-B5pWh8e2.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-D2iGyYIp.js";
27
27
  import { Hono } from "hono";
28
28
  import path from "node:path";
29
29
  import { createHash, randomBytes, randomUUID } from "node:crypto";
30
30
  import * as z from "zod";
31
- import { and, arrayOverlaps, asc, desc, eq, gt, gte, inArray, isNull, like, lte, or, sql } from "drizzle-orm";
31
+ import { and, arrayOverlaps, asc, countDistinct, desc, eq, gt, gte, inArray, isNull, like, lte, notExists, or, sql } from "drizzle-orm";
32
32
  import { conversationAnnotationInputSchema, pluginUserPageContentSchema, pluginUserPageCursorSchema, pluginUserPageFilterSchema, pluginUserPageLinksSchema, pluginUserPageQuerySchema } from "@sentry/junior-plugin-api";
33
33
  import { alias } from "drizzle-orm/pg-core";
34
34
  import fs from "node:fs/promises";
@@ -456,6 +456,111 @@ async function readConversationMetricBuckets(db, options) {
456
456
  value: sql`sum(${juniorConversationMetrics.value})::double precision`
457
457
  }).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
458
  }
459
+ // src/api/conversations/outcome-buckets.ts
460
+ const changes = juniorCodeChanges;
461
+ const linked = alias(juniorConversations, "linked");
462
+ const linksChange = sql`${linked.conversationId} = any(${changes.conversationIds})`;
463
+ const linkedRoot = sql`coalesce(${linked.rootConversationId}, ${linked.conversationId})`;
464
+ /**
465
+ * Count outcomes per UTC day or hour, with the conversation cost that
466
+ * produced them. An outcome is one of:
467
+ *
468
+ * - a merged code change, at its merge time. Each root Conversation splits its
469
+ * tree cost evenly across all of its merged code changes, so a long
470
+ * Conversation that merges three changes makes each one cheaper.
471
+ * - a root Conversation with no linked code change whose latest Brief is
472
+ * `done` or `answered`, at its last activity. Its whole tree cost counts.
473
+ *
474
+ * Roots with only open or closed code changes count nothing until a change
475
+ * merges, so one Conversation is never both kinds of outcome. A merged change
476
+ * with no linked Conversation has an unknown cost, not a zero cost, so it is
477
+ * left out instead of making the mean look cheaper.
478
+ */
479
+ async function readOutcomeBuckets(db, options) {
480
+ const [merges, briefRoots] = await Promise.all([readWindowMerges(db, options), readBriefOutcomeRoots(db, options)]);
481
+ const mergeRoots = [...new Set(merges.map((merge) => merge.rootId))];
482
+ const [rootMerges, treeCosts] = await Promise.all([readRootMergeCounts(db, mergeRoots), readTreeCosts$1(db, [...mergeRoots, ...briefRoots.map((root) => root.rootId)])]);
483
+ const dateLength = options.bucket === "day" ? 10 : 13;
484
+ const buckets = /* @__PURE__ */ new Map();
485
+ const bucketAt = (instant) => {
486
+ const date = instant.toISOString().slice(0, dateLength);
487
+ let bucket = buckets.get(date);
488
+ if (!bucket) {
489
+ bucket = {
490
+ date,
491
+ mergedCodeChangeCostUsd: 0,
492
+ mergedCodeChanges: 0,
493
+ outcomeCostUsd: 0,
494
+ outcomes: 0
495
+ };
496
+ buckets.set(date, bucket);
497
+ }
498
+ return bucket;
499
+ };
500
+ const changeCosts = /* @__PURE__ */ new Map();
501
+ for (const merge of merges) {
502
+ const share = (treeCosts.get(merge.rootId) ?? 0) / (rootMerges.get(merge.rootId) ?? 1);
503
+ const change = changeCosts.get(merge.changeId);
504
+ if (change) change.costUsd += share;
505
+ else changeCosts.set(merge.changeId, {
506
+ costUsd: share,
507
+ mergedAt: merge.mergedAt
508
+ });
509
+ }
510
+ for (const change of changeCosts.values()) {
511
+ const bucket = bucketAt(change.mergedAt);
512
+ bucket.mergedCodeChanges += 1;
513
+ bucket.mergedCodeChangeCostUsd += change.costUsd;
514
+ bucket.outcomes += 1;
515
+ bucket.outcomeCostUsd += change.costUsd;
516
+ }
517
+ for (const root of briefRoots) {
518
+ const bucket = bucketAt(root.lastActivityAt);
519
+ bucket.outcomes += 1;
520
+ bucket.outcomeCostUsd += treeCosts.get(root.rootId) ?? 0;
521
+ }
522
+ return [...buckets.values()];
523
+ }
524
+ async function readWindowMerges(db, options) {
525
+ return (await db.selectDistinct({
526
+ changeId: changes.id,
527
+ mergedAt: changes.mergedAt,
528
+ rootId: linkedRoot
529
+ }).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 ? [{
530
+ changeId,
531
+ mergedAt,
532
+ rootId
533
+ }] : []);
534
+ }
535
+ async function readBriefOutcomeRoots(db, options) {
536
+ const roots = juniorConversations;
537
+ const briefs = juniorConversationBriefs;
538
+ 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");
539
+ return await db.select({
540
+ lastActivityAt: roots.lastActivityAt,
541
+ rootId: roots.conversationId
542
+ }).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)))));
543
+ }
544
+ /** Merged code changes of all time per root, so each merge gets its share. */
545
+ async function readRootMergeCounts(db, rootIds) {
546
+ if (!rootIds.length) return /* @__PURE__ */ new Map();
547
+ const rows = await db.select({
548
+ merged: countDistinct(changes.id),
549
+ rootId: linkedRoot
550
+ }).from(changes).innerJoin(linked, linksChange).where(and(eq(changes.state, "merged"), inArray(linkedRoot, [...rootIds]))).groupBy(linkedRoot);
551
+ return new Map(rows.flatMap((row) => row.rootId ? [[row.rootId, row.merged]] : []));
552
+ }
553
+ async function readTreeCosts$1(db, rootIds) {
554
+ if (!rootIds.length) return /* @__PURE__ */ new Map();
555
+ const conversations = juniorConversations;
556
+ const ids = [...new Set(rootIds)];
557
+ const treeRoot = sql`coalesce(${conversations.rootConversationId}, ${conversations.conversationId})`;
558
+ const rows = await db.select({
559
+ costUsd: sql`coalesce(sum(${conversationUsageCostExpr(conversations.usage)}), 0)::double precision`,
560
+ rootId: treeRoot
561
+ }).from(conversations).where(or(inArray(conversations.rootConversationId, ids), inArray(conversations.conversationId, ids))).groupBy(treeRoot);
562
+ return new Map(rows.flatMap((row) => row.rootId ? [[row.rootId, row.costUsd]] : []));
563
+ }
459
564
  // src/api/conversations/stats.query.ts
460
565
  const treeConversation$1 = alias(juniorConversations, "stats_tree_conversation");
461
566
  const treeAggregateColumns$1 = conversationAggregateColumns({
@@ -520,27 +625,37 @@ function statsWindow(nowMs) {
520
625
  const HOUR_MS = 36e5;
521
626
  /** Keep 7d of hours so clients can roll 7d charts into 6h buckets. */
522
627
  const WINDOW_HOURS = 168;
523
- function applyMetricBuckets(rows, metrics) {
524
- const byDate = new Map(rows.map((row) => [row.date, {
525
- ...row,
628
+ function emptyMetricRow(date) {
629
+ return {
526
630
  cachedInputTokens: null,
527
631
  cacheCreationTokens: null,
632
+ conversations: 0,
528
633
  costUsd: null,
634
+ date,
529
635
  durationMs: 0,
530
636
  inputTokens: null,
637
+ mergedCodeChangeCostUsd: null,
638
+ mergedCodeChanges: null,
639
+ outcomeCostUsd: null,
640
+ outcomes: null,
531
641
  tokens: null
642
+ };
643
+ }
644
+ function applyMetricBuckets(rows, metrics, outcomes) {
645
+ const byDate = new Map(rows.map((row) => [row.date, {
646
+ ...emptyMetricRow(row.date),
647
+ conversations: row.conversations
532
648
  }]));
649
+ for (const bucket of outcomes) {
650
+ const row = byDate.get(bucket.date) ?? emptyMetricRow(bucket.date);
651
+ row.mergedCodeChanges = bucket.mergedCodeChanges;
652
+ row.mergedCodeChangeCostUsd = bucket.mergedCodeChangeCostUsd;
653
+ row.outcomes = bucket.outcomes;
654
+ row.outcomeCostUsd = bucket.outcomeCostUsd;
655
+ byDate.set(bucket.date, row);
656
+ }
533
657
  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
- };
658
+ const row = byDate.get(metric.date) ?? emptyMetricRow(metric.date);
544
659
  if (metric.metric === "cached_input_tokens") row.cachedInputTokens = metric.value;
545
660
  else if (metric.metric === "cache_creation_tokens") row.cacheCreationTokens = metric.value;
546
661
  else if (metric.metric === "cost_usd") row.costUsd = metric.value;
@@ -560,6 +675,12 @@ function metricPoint(date, row) {
560
675
  ...row?.cacheCreationTokens !== null && row?.cacheCreationTokens !== void 0 ? { cacheCreationTokens: row.cacheCreationTokens } : void 0,
561
676
  ...row?.costUsd !== null && row?.costUsd !== void 0 ? { costUsd: addUsd$2(void 0, row.costUsd) } : void 0,
562
677
  ...row?.inputTokens !== null && row?.inputTokens !== void 0 ? { inputTokens: row.inputTokens } : void 0,
678
+ ...row?.outcomes !== null && row?.outcomes !== void 0 ? {
679
+ mergedCodeChangeCostUsd: addUsd$2(void 0, row.mergedCodeChangeCostUsd ?? 0),
680
+ mergedCodeChanges: row.mergedCodeChanges ?? 0,
681
+ outcomeCostUsd: addUsd$2(void 0, row.outcomeCostUsd ?? 0),
682
+ outcomes: row.outcomes
683
+ } : void 0,
563
684
  ...row?.tokens !== null && row?.tokens !== void 0 ? { tokens: row.tokens } : void 0
564
685
  };
565
686
  }
@@ -679,7 +800,7 @@ async function aggregateStats(db, start, end) {
679
800
  ${juniorConversations.lastActivityAt} AT TIME ZONE 'UTC',
680
801
  'YYYY-MM-DD"T"HH24'
681
802
  )`;
682
- const [totalsRows, actorRows, locationRows, metricRows, metricHourRows, dayMetrics, hourMetrics] = await Promise.all([
803
+ const [totalsRows, actorRows, locationRows, metricRows, metricHourRows, dayMetrics, hourMetrics, dayOutcomes, hourOutcomes] = await Promise.all([
683
804
  db.select(treeAggregateColumns$1).from(juniorConversations).innerJoin(treeConversation$1, eq(treeConversation$1.rootConversationId, juniorConversations.conversationId)).where(where),
684
805
  db.select({
685
806
  identityDisplayName: juniorIdentities.displayName,
@@ -716,13 +837,23 @@ async function aggregateStats(db, start, end) {
716
837
  bucket: "hour",
717
838
  start: hourStart,
718
839
  end
840
+ }),
841
+ readOutcomeBuckets(db, {
842
+ bucket: "day",
843
+ start,
844
+ end
845
+ }),
846
+ readOutcomeBuckets(db, {
847
+ bucket: "hour",
848
+ start: hourStart,
849
+ end
719
850
  })
720
851
  ]);
721
852
  return {
722
853
  actorRows,
723
854
  locationRows,
724
- metricHourRows: applyMetricBuckets(metricHourRows, hourMetrics),
725
- metricRows: applyMetricBuckets(metricRows, dayMetrics),
855
+ metricHourRows: applyMetricBuckets(metricHourRows, hourMetrics, hourOutcomes),
856
+ metricRows: applyMetricBuckets(metricRows, dayMetrics, dayOutcomes),
726
857
  totals: totalsRows[0]
727
858
  };
728
859
  }
@@ -1255,44 +1386,6 @@ const WINDOW_DAYS = 30;
1255
1386
  * stale open change is not cut off by newer completed changes.
1256
1387
  */
1257
1388
  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
1389
  function startOfUtcDay(timestampMs) {
1297
1390
  const date = new Date(timestampMs);
1298
1391
  date.setUTCHours(0, 0, 0, 0);
@@ -1302,39 +1395,65 @@ function mergeRate(merged, closed) {
1302
1395
  const completed = merged + closed;
1303
1396
  return completed > 0 ? merged / completed : void 0;
1304
1397
  }
1398
+ function median(values) {
1399
+ if (!values.length) return void 0;
1400
+ const sorted = [...values].sort((a, b) => a - b);
1401
+ const middle = (sorted.length - 1) / 2;
1402
+ return (sorted[Math.floor(middle)] + sorted[Math.ceil(middle)]) / 2;
1403
+ }
1305
1404
  /**
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.
1405
+ * Count created, merged, and closed changes per UTC bucket, from `start`
1406
+ * through `end`. Every bucket is present, so charts get zero gaps.
1309
1407
  */
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
- `;
1408
+ function bucketActivity(changes, range) {
1409
+ const buckets = /* @__PURE__ */ new Map();
1410
+ for (let ms = range.start.getTime(); ms <= range.end.getTime(); ms += range.stepMs) {
1411
+ const date = new Date(ms).toISOString().slice(0, range.keyLength);
1412
+ buckets.set(date, {
1413
+ closed: 0,
1414
+ created: 0,
1415
+ date,
1416
+ merged: 0
1417
+ });
1418
+ }
1419
+ const add = (at, kind) => {
1420
+ if (!at || at < range.start) return;
1421
+ const bucket = buckets.get(at.toISOString().slice(0, range.keyLength));
1422
+ if (bucket) bucket[kind] += 1;
1423
+ };
1424
+ for (const change of changes) {
1425
+ add(change.openedAt, "created");
1426
+ add(change.mergedAt, "merged");
1427
+ if (change.state === "closed") add(change.closedAt, "closed");
1428
+ }
1429
+ return [...buckets.values()];
1430
+ }
1431
+ /**
1432
+ * Read conversation-tree costs for the given linked conversation ids. The
1433
+ * returned function sums each tree once, child Conversations included, so a
1434
+ * change linked to two Conversations of one tree pays for that tree once.
1435
+ */
1436
+ async function readTreeCosts(conversationIds) {
1437
+ const db = getDb();
1438
+ const conversations = juniorConversations;
1439
+ const ids = [...new Set(conversationIds)];
1440
+ const links = ids.length ? await db.select({
1441
+ conversationId: conversations.conversationId,
1442
+ rootId: sql`coalesce(${conversations.rootConversationId}, ${conversations.conversationId})`
1443
+ }).from(conversations).where(inArray(conversations.conversationId, ids)) : [];
1444
+ const rootOf = new Map(links.map((link) => [link.conversationId, link.rootId]));
1445
+ const rootIds = [...new Set(rootOf.values())];
1446
+ const trees = rootIds.length ? await db.select({
1447
+ costUsd: sql`coalesce(sum(${conversationUsageCostExpr(conversations.usage)}), 0)`.mapWith(Number),
1448
+ rootId: conversations.rootConversationId
1449
+ }).from(conversations).where(inArray(conversations.rootConversationId, rootIds)).groupBy(conversations.rootConversationId) : [];
1450
+ const costOf = new Map(trees.map((tree) => [tree.rootId, tree.costUsd]));
1451
+ return (linked) => {
1452
+ let total = 0;
1453
+ const roots = new Set(linked.flatMap((id) => rootOf.get(id) ?? []));
1454
+ for (const root of roots) total += costOf.get(root) ?? 0;
1455
+ return total;
1456
+ };
1338
1457
  }
1339
1458
  /** True when any linked conversation actor belongs to the subject user. */
1340
1459
  function ownedByUserSql(conversationIds, userId) {
@@ -1359,166 +1478,45 @@ async function readCodeWindows(args) {
1359
1478
  const windowStart = /* @__PURE__ */ new Date(args.nowMs - WINDOW_DAYS * DAY_MS);
1360
1479
  const activityStart = startOfUtcDay(args.nowMs - 89 * DAY_MS);
1361
1480
  const changes = juniorCodeChanges;
1362
- const scope = changeScopeFilter(args);
1363
- const conversationTreeCost = conversationTreeCostExpr();
1364
1481
  const activityHourEnd = new Date(args.nowMs);
1365
1482
  activityHourEnd.setUTCMinutes(0, 0, 0);
1366
1483
  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));
1484
+ const rows = await db.select({
1485
+ closedAt: changes.closedAt,
1486
+ conversationIds: changes.conversationIds,
1487
+ mergedAt: changes.mergedAt,
1488
+ openedAt: changes.openedAt,
1489
+ state: changes.state
1490
+ }).from(changes).where(and(changeScopeFilter(args), or(gte(changes.openedAt, activityStart), gte(changes.mergedAt, activityStart), gte(changes.closedAt, activityStart), eq(changes.state, "open"))));
1491
+ const inWindow = (at) => at !== null && at >= windowStart;
1492
+ const created = rows.filter((row) => inWindow(row.openedAt));
1493
+ const merged = rows.filter((row) => inWindow(row.mergedAt));
1494
+ const closed = rows.filter((row) => row.state === "closed" && inWindow(row.closedAt));
1495
+ const createdConversationIds = created.flatMap((row) => row.conversationIds);
1496
+ const treeCost = await readTreeCosts(createdConversationIds);
1497
+ const changeCosts = created.map((row) => treeCost(row.conversationIds));
1498
+ const activityHours = bucketActivity(rows, {
1499
+ end: activityHourEnd,
1500
+ keyLength: 13,
1501
+ start: activityHourStart,
1502
+ stepMs: DAY_MS / 24
1503
+ });
1504
+ const summary = {
1505
+ closed: closed.length,
1506
+ costUsd: treeCost(createdConversationIds),
1507
+ created: created.length,
1508
+ medianCostUsd: median(changeCosts.filter((cost) => cost > 0)),
1509
+ medianMergeTimeMs: median(merged.flatMap((row) => row.state === "merged" && row.mergedAt ? [row.mergedAt.getTime() - row.openedAt.getTime()] : [])),
1510
+ merged: merged.length,
1511
+ open: rows.filter((row) => row.state === "open").length
1512
+ };
1520
1513
  return {
1521
- activityDays: z.array(activityDaySchema).parse(queryRows(activityResult)),
1514
+ activityDays: bucketActivity(rows, {
1515
+ end: startOfUtcDay(args.nowMs),
1516
+ keyLength: 10,
1517
+ start: activityStart,
1518
+ stepMs: DAY_MS
1519
+ }),
1522
1520
  activityHours,
1523
1521
  activitySixHours: sumUtcHoursIntoSixHours({
1524
1522
  empty: (date) => ({
@@ -1568,74 +1566,42 @@ async function readCodeOverview(nowMs = Date.now()) {
1568
1566
  const changes = juniorCodeChanges;
1569
1567
  const repositories = juniorCodeRepositories;
1570
1568
  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)]);
1569
+ const windowStart = windows.windowStart;
1570
+ const created = sql`count(*) filter (where ${changes.openedAt} >= ${windowStart})`.mapWith(Number);
1571
+ const merged = sql`count(*) filter (where ${changes.mergedAt} >= ${windowStart})`.mapWith(Number);
1572
+ const recent = or(gte(changes.openedAt, windowStart), gte(changes.mergedAt, windowStart), gte(changes.closedAt, windowStart), eq(changes.state, "open"));
1573
+ const [repositoryRows, recentChanges] = await Promise.all([db.select({
1574
+ closed: sql`count(*) filter (where ${changes.state} = 'closed' and ${changes.closedAt} >= ${windowStart})`.mapWith(Number),
1575
+ created,
1576
+ id: repositories.id,
1577
+ merged,
1578
+ name: repositories.name,
1579
+ open: sql`count(*) filter (where ${changes.state} = 'open')`.mapWith(Number),
1580
+ provider: repositories.provider,
1581
+ url: repositories.url
1582
+ }).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)]);
1583
+ const repositoryChanges = repositoryRows.length ? await db.select({
1584
+ conversationIds: changes.conversationIds,
1585
+ repositoryId: changes.repositoryId
1586
+ }).from(changes).where(and(gte(changes.openedAt, windowStart), inArray(changes.repositoryId, repositoryRows.map((row) => row.id)))) : [];
1587
+ const treeCost = await readTreeCosts(repositoryChanges.flatMap((change) => change.conversationIds));
1588
+ const repositoryCosts = /* @__PURE__ */ new Map();
1589
+ for (const change of repositoryChanges) {
1590
+ const cost = treeCost(change.conversationIds);
1591
+ if (cost <= 0) continue;
1592
+ const costs = repositoryCosts.get(change.repositoryId) ?? [];
1593
+ costs.push(cost);
1594
+ repositoryCosts.set(change.repositoryId, costs);
1595
+ }
1631
1596
  return codeOverviewReportSchema.parse({
1632
1597
  activityDays: windows.activityDays,
1633
1598
  activityHours: windows.activityHours,
1634
1599
  activitySixHours: windows.activitySixHours,
1635
1600
  changes: recentChanges.map(codeChangeReport),
1636
1601
  generatedAt: windows.windowEnd.toISOString(),
1637
- repositories: z.array(repositoryRowSchema).parse(queryRows(repositoryResult)).map((repository) => ({
1602
+ repositories: repositoryRows.map((repository) => ({
1638
1603
  ...repository,
1604
+ medianCostUsd: median(repositoryCosts.get(repository.id) ?? []),
1639
1605
  mergeRate: mergeRate(repository.merged, repository.closed),
1640
1606
  url: repository.url ?? void 0
1641
1607
  })),
@@ -2667,7 +2633,7 @@ async function readPeoplePluginReports(args) {
2667
2633
  reports: [],
2668
2634
  source: "plugins"
2669
2635
  });
2670
- const { getPluginProfileReports } = await import("./projection-BzJQncZV.js").then((n) => n.jn);
2636
+ const { getPluginProfileReports } = await import("./projection-B6VS7kbo.js").then((n) => n.jn);
2671
2637
  return pluginOperationalReportFeedSchema.parse({
2672
2638
  generatedAt: new Date(nowMs).toISOString(),
2673
2639
  reports: await getPluginProfileReports({
@@ -3696,7 +3662,7 @@ function readDescriptionText(home) {
3696
3662
  }
3697
3663
  /** Read discovered skills for runtime diagnostics and the Automation editor. */
3698
3664
  async function readSkillReports() {
3699
- const { discoverSkills } = await import("./skills-BZE2DP8I.js").then((n) => n.o);
3665
+ const { discoverSkills } = await import("./skills-DXgd5Inh.js").then((n) => n.o);
3700
3666
  const skills = await discoverSkills();
3701
3667
  return skillReportsSchema.parse(skills.map((skill) => ({
3702
3668
  name: skill.name,
@@ -3710,7 +3676,7 @@ async function readSkillReports() {
3710
3676
  * what the skill tells Junior. Returns null when no skill has that name.
3711
3677
  */
3712
3678
  async function readSkillDetailReport(name) {
3713
- const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-BZE2DP8I.js").then((n) => n.o);
3679
+ const { discoverSkills, findSkillByName, parseSkillFile } = await import("./skills-DXgd5Inh.js").then((n) => n.o);
3714
3680
  const skill = findSkillByName(name, await discoverSkills());
3715
3681
  if (!skill) return null;
3716
3682
  const parsed = parseSkillFile(await fs.readFile(path.join(skill.skillPath, "SKILL.md"), "utf8"), skill.name);
@@ -3725,7 +3691,7 @@ async function readSkillDetailReport(name) {
3725
3691
  }
3726
3692
  /** Read safe configured plugin metadata for authenticated runtime diagnostics. */
3727
3693
  async function readPlugins() {
3728
- const { pluginCatalogRuntime } = await import("./catalog-runtime-DgouZKZm.js").then((n) => n.t);
3694
+ const { pluginCatalogRuntime } = await import("./catalog-runtime-CpCmlD9L.js").then((n) => n.t);
3729
3695
  return pluginsSchema.parse(pluginCatalogRuntime.getProviders().map((plugin) => ({
3730
3696
  configKeys: plugin.manifest.configKeys ?? [],
3731
3697
  description: plugin.manifest.description,
@@ -3737,7 +3703,7 @@ async function readPlugins() {
3737
3703
  async function readRuntimeInfoReport() {
3738
3704
  const [{ homeDir }, { pluginCatalogRuntime }, plugins, skills] = await Promise.all([
3739
3705
  import("./package-discovery-DJhGdS4c.js").then((n) => n.r),
3740
- import("./catalog-runtime-DgouZKZm.js").then((n) => n.t),
3706
+ import("./catalog-runtime-CpCmlD9L.js").then((n) => n.t),
3741
3707
  readPlugins(),
3742
3708
  readSkillReports()
3743
3709
  ]);
@@ -3754,7 +3720,7 @@ async function readRuntimeInfoReport() {
3754
3720
  /** Read sanitized operational summaries contributed by plugins. */
3755
3721
  async function readPluginOperationalReportFeed() {
3756
3722
  const nowMs = Date.now();
3757
- const { getPluginOperationalReports } = await import("./projection-BzJQncZV.js").then((n) => n.jn);
3723
+ const { getPluginOperationalReports } = await import("./projection-B6VS7kbo.js").then((n) => n.jn);
3758
3724
  return pluginOperationalReportFeedSchema.parse({
3759
3725
  source: "plugins",
3760
3726
  generatedAt: new Date(nowMs).toISOString(),