@sentry/junior 0.317.0 → 0.319.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 (95) hide show
  1. package/dist/adapter-8_S6Birm.js +1833 -0
  2. package/dist/{admin-CAugg87B.js → admin-EsbUON1j.js} +1 -1
  3. package/dist/{agent-runner-AjrEV6Qe.js → agent-CtzMl32d.js} +19953 -6727
  4. package/dist/{agent-status-BA5x3Xtp.js → agent-status-Bq_AIpyp.js} +105 -1
  5. package/dist/{agent-update-delivery-B_YIZcgf.js → agent-update-delivery-pAvsbuGL.js} +4 -5
  6. package/dist/api/schema.d.ts +85 -51
  7. package/dist/api/schema.js +4 -4
  8. package/dist/api.js +81 -94
  9. package/dist/{app-MoNAsVV5.d.ts → app-tACXxJPI.d.ts} +8 -13
  10. package/dist/app.d.ts +2 -2
  11. package/dist/app.js +246 -153
  12. package/dist/{change-record-BzJgLsv7.d.ts → change-record-K-KsqNhT.d.ts} +9 -5
  13. package/dist/{channel-access-j-YAVYK4.js → channel-access-DET5hzZM.js} +1 -1
  14. package/dist/{chat-core-engine-aH85nEHv.js → chat-core-engine-DpM3tMVi.js} +7 -7
  15. package/dist/cli/chat.d.ts +1 -1
  16. package/dist/cli/chat.js +38 -30
  17. package/dist/cli/check.js +5 -5
  18. package/dist/cli/main.js +2 -2
  19. package/dist/cli/plugins.d.ts +1 -1
  20. package/dist/cli/plugins.js +8 -8
  21. package/dist/cli/snapshot-create.js +5 -6
  22. package/dist/cli/upgrade.d.ts +1 -1
  23. package/dist/cli/upgrade.js +3 -4
  24. package/dist/{continue-in-slack-D-FZ8Fin.js → continue-in-slack-CFzDyxkH.js} +3 -2
  25. package/dist/{conversation-feed--9S0_PXL.js → conversation-feed-DEUdD7mb.js} +2 -106
  26. package/dist/{conversation-privacy-B1uXn5sf.js → conversation-privacy-C2vYK55O.js} +1 -1
  27. package/dist/{create-DoDIYgtZ.js → create-Ta3SEIB5.js} +124 -16
  28. package/dist/{credential-sync-BJOqGnjV.js → credential-sync-DyRqDmY4.js} +17 -20
  29. package/dist/{db-BFmyYZtJ.js → db-BCaNWl9p.js} +6536 -1920
  30. package/dist/{deployment-DXq9ZLU4.js → deployment-CfOew1Tm.js} +3 -3
  31. package/dist/{engine-context-CgQ7mlHt.js → engine-context-CiExoy1B.js} +181 -155
  32. package/dist/{html-B3VKTGbJ.js → html-Bb2Si1bR.js} +6 -8
  33. package/dist/instrumentation.js +7 -23
  34. package/dist/list-wwDcROh9.js +5007 -0
  35. package/dist/{logging--smS7XRK.js → logging-BRPTXAdf.js} +10 -81
  36. package/dist/{mailbox-turn-uSXhUFc9.js → markers-9QoqW5ov.js} +1875 -1458
  37. package/dist/nitro.d.ts +2 -2
  38. package/dist/nitro.js +7 -8
  39. package/dist/{oauth-callback-server-CE4soEIY.js → oauth-callback-server-vhL9b-PZ.js} +2 -2
  40. package/dist/{oauth-relay-C36gX1gH.js → oauth-relay-CH2v7WiB.js} +1 -1
  41. package/dist/{plugins-fBrz8PCV.d.ts → plugins-DhGXZjlu.d.ts} +1 -0
  42. package/dist/{profile-BQ-iBDsZ.js → profile-D9LdwmZi.js} +17 -19
  43. package/dist/{prompt-Dv7gkpD6.js → prompt-3TqxEOtc.js} +10 -10
  44. package/dist/{reports-WKHfGTsU.js → reports-K-tbtEyx.js} +2 -2
  45. package/dist/{resolve-tony4ibz.js → resolve-BBV2qf8A.js} +5 -5
  46. package/dist/{result-Bta_dlWa.js → result-5IdGJP4M.js} +24 -13
  47. package/dist/{runner-BstDRbD9.js → runner-BK_joPlM.js} +9 -18
  48. package/dist/{sandbox-egress-signals-oSJMJOnn.js → sandbox-egress-signals-DXgWXXmm.js} +1 -1
  49. package/dist/{schema-DfqrHACA.js → schema-zWGG6VC1.js} +13 -7
  50. package/dist/{service-account-CTV_jaNu.js → service-account-CateFyhw.js} +4 -5
  51. package/dist/{skills-BCEU41zM.js → skills-Ccjw8h2P.js} +10 -9
  52. package/dist/{slack-conversation-unfurl-DxVmhbGP.js → slack-conversation-unfurl-ZC_TSpc4.js} +7 -7
  53. package/dist/storage-C9U7R5rM.js +273 -0
  54. package/dist/{system-prompt-table-CiXy0eNR.js → system-prompt-table-YBTHIFlP.js} +26 -84
  55. package/dist/topic-B2EWKKBT.js +6 -0
  56. package/dist/{package-discovery-DD9vencX.js → topics-DxuKurCX.js} +21 -1
  57. package/dist/{types-C4iC-IMC.js → types-BNHkJrOP.js} +79 -59
  58. package/dist/{users-ByG5RCEJ.js → users-CCRAqYb_.js} +1 -1
  59. package/dist/{validation-8gjfR91V.js → validation-BCUpJa8K.js} +4 -4
  60. package/dist/{version-BeZhWWBE.js → version-BNm0JYj3.js} +1 -1
  61. package/dist/version.js +1 -1
  62. package/dist/{worker-BqMQQNRk.js → worker-BhgpZ7_b.js} +5 -5
  63. package/migrations/20261127002500_turn_discarded_usage/migration.sql +2 -0
  64. package/migrations/20261127002500_turn_discarded_usage/snapshot.json +73 -0
  65. package/migrations/20261127052408_space_name_nullable/migration.sql +5 -0
  66. package/migrations/20261127052408_space_name_nullable/snapshot.json +29 -0
  67. package/migrations/20261127060000_annotation_object_id_index/migration.sql +1 -0
  68. package/migrations/20261127060000_annotation_object_id_index/snapshot.json +69 -0
  69. package/migrations/20261127060001_annotation_subjects/migration.sql +78 -0
  70. package/migrations/20261127060001_annotation_subjects/snapshot.json +104 -0
  71. package/migrations/20261127060002_annotation_subject_index/migration.sql +1 -0
  72. package/migrations/20261127060002_annotation_subject_index/snapshot.json +70 -0
  73. package/migrations/20261127060003_annotation_title_url/migration.sql +84 -0
  74. package/migrations/20261127060003_annotation_title_url/snapshot.json +73 -0
  75. package/package.json +9 -7
  76. package/dist/catalog-runtime-DfSpJZdY.js +0 -6
  77. package/dist/child-message-DHjQLEd1.js +0 -19
  78. package/dist/config-CHQ8X251.js +0 -2422
  79. package/dist/conversation-turn-BUE_7xaN.js +0 -1157
  80. package/dist/job-runner-A1lCkybD.js +0 -1506
  81. package/dist/lineage-Bktb0UcV.js +0 -36
  82. package/dist/list-Bxvg5wXf.js +0 -12623
  83. package/dist/message-BNenhsmB.js +0 -154
  84. package/dist/model-input-BReSnwHp.js +0 -82
  85. package/dist/parent-result-Ck1rFYRQ.js +0 -310
  86. package/dist/registry-iXMT5Jmh.js +0 -3279
  87. package/dist/run-conversation-DL6ru7iW.js +0 -336
  88. package/dist/sender-actors-CPglLd5R.js +0 -83
  89. package/dist/spawn-frczVPIr.js +0 -48
  90. package/dist/task-runner-C9Yc2_ae.js +0 -1526
  91. package/dist/thread-context-CqZDKErp.js +0 -166
  92. package/dist/topic-CRYYBYp-.js +0 -7
  93. package/dist/topics-SRN7IVX-.js +0 -24
  94. package/dist/turn-membership-CENFf3kI.js +0 -856
  95. package/dist/turn-wake-BhloiI2h.js +0 -151
@@ -1,5 +1,24 @@
1
1
  import * as z from "zod";
2
- import { actorSchema, actorUserIdSchema, conversationAnnotationInputSchema, conversationEventPresentationSchema, conversationSidebarAnnotationSchema, destinationVisibilitySchema, eventMatchFieldsSchema, eventMatchSchema, eventReachSchema, eventTypeSchema, objectFactFields, objectTypeSchema, pluginEventTypeSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
2
+ import { actorSchema, actorUserIdSchema, conversationEventPresentationSchema, conversationSidebarAnnotationSchema, destinationVisibilitySchema, eventMatchFieldsSchema, eventMatchSchema, eventReachSchema, eventTypeSchema, liveAnnotationSchema, objectFactFields, objectTypeSchema, pluginEventTypeSchema, slackDestinationSchema, taskOutcomeSchema } from "@sentry/junior-plugin-api";
3
+ // src/usage-schema.ts
4
+ const usageCostSchema = z.object({
5
+ input: z.number().finite().nonnegative().optional(),
6
+ output: z.number().finite().nonnegative().optional(),
7
+ cacheRead: z.number().finite().nonnegative().optional(),
8
+ cacheWrite: z.number().finite().nonnegative().optional(),
9
+ total: z.number().finite().nonnegative().optional()
10
+ }).strict();
11
+ const usageSchema = z.object({
12
+ inputTokens: z.number().int().nonnegative().optional(),
13
+ outputTokens: z.number().int().nonnegative().optional(),
14
+ cachedInputTokens: z.number().int().nonnegative().optional(),
15
+ cacheCreationTokens: z.number().int().nonnegative().optional(),
16
+ reasoningTokens: z.number().int().nonnegative().optional(),
17
+ totalTokens: z.number().int().nonnegative().optional(),
18
+ cost: usageCostSchema.optional()
19
+ }).strict();
20
+ /** The token counts of a usage record, without its cost. */
21
+ const usageTokensSchema = usageSchema.omit({ cost: true });
3
22
  // src/chat/gateway-providers/rule.ts
4
23
  /**
5
24
  * The routing rule of the "Enabled providers" admin setting.
@@ -19,23 +38,31 @@ function gatewayOnlyProviders(enabled, served) {
19
38
  const only = served.filter((provider) => enabled.includes(provider));
20
39
  return only.length > 0 && only.length < served.length ? only : void 0;
21
40
  }
22
- // src/usage-schema.ts
23
- const usageCostSchema = z.object({
24
- input: z.number().finite().nonnegative().optional(),
25
- output: z.number().finite().nonnegative().optional(),
26
- cacheRead: z.number().finite().nonnegative().optional(),
27
- cacheWrite: z.number().finite().nonnegative().optional(),
28
- total: z.number().finite().nonnegative().optional()
29
- }).strict();
30
- const usageSchema = z.object({
31
- inputTokens: z.number().int().nonnegative().optional(),
32
- outputTokens: z.number().int().nonnegative().optional(),
33
- cachedInputTokens: z.number().int().nonnegative().optional(),
34
- cacheCreationTokens: z.number().int().nonnegative().optional(),
35
- reasoningTokens: z.number().int().nonnegative().optional(),
36
- totalTokens: z.number().int().nonnegative().optional(),
37
- cost: usageCostSchema.optional()
38
- }).strict();
41
+ // src/chat/child-agents/result-event-type.ts
42
+ const LEGACY_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
43
+ /** True when an Event type names a child result that an earlier release wrote. */
44
+ function isLegacyResultEventType(eventType) {
45
+ return eventType.startsWith(LEGACY_RESULT_EVENT_TYPE_PREFIX);
46
+ }
47
+ /**
48
+ * Event type of an agent update: what a Conversation reports when a Turn
49
+ * ends, it waits on a person, or it stops. A parent gets it from its child
50
+ * agents, and a Watch on the Conversation gets the same Event.
51
+ */
52
+ const AGENT_UPDATE_EVENT_TYPE = "agent.update";
53
+ const LEGACY_AGENT_REPLY_EVENT_TYPE = "agent.reply";
54
+ /** True when an Event type names an agent update. */
55
+ function isAgentUpdateEventType(eventType) {
56
+ return eventType === "agent.update" || eventType === LEGACY_AGENT_REPLY_EVENT_TYPE;
57
+ }
58
+ /** Event type of a message that a child agent sends to its parent. */
59
+ const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
60
+ /** Event type of a message from another top-level agent. */
61
+ const TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE = "agent.top_level_message";
62
+ /** True when an Event type names a message that another agent sent. */
63
+ function isAgentMessageEventType(eventType) {
64
+ return eventType === "agent.message" || eventType === "agent.top_level_message";
65
+ }
39
66
  // src/api/schema/response.ts
40
67
  /** Stable error body returned by Junior-owned REST endpoints. */
41
68
  const apiErrorSchema = z.object({ error: z.string().min(1) }).strict();
@@ -437,33 +464,6 @@ function automationTaskColumns(task) {
437
464
  skill: task.skill
438
465
  };
439
466
  }
440
- // src/chat/child-agents/result-event-type.ts
441
- /** Event namespace of the messages between a parent and its child agents. */
442
- const AGENT_EVENT_NAMESPACE = "junior";
443
- const LEGACY_RESULT_EVENT_TYPE_PREFIX = "agent_invocation.";
444
- /** True when an Event type names a child result that an earlier release wrote. */
445
- function isLegacyResultEventType(eventType) {
446
- return eventType.startsWith(LEGACY_RESULT_EVENT_TYPE_PREFIX);
447
- }
448
- /**
449
- * Event type of an agent update: what a Conversation reports when a Turn
450
- * ends, it waits on a person, or it stops. A parent gets it from its child
451
- * agents, and a Watch on the Conversation gets the same Event.
452
- */
453
- const AGENT_UPDATE_EVENT_TYPE = "agent.update";
454
- const LEGACY_AGENT_REPLY_EVENT_TYPE = "agent.reply";
455
- /** True when an Event type names an agent update. */
456
- function isAgentUpdateEventType(eventType) {
457
- return eventType === "agent.update" || eventType === LEGACY_AGENT_REPLY_EVENT_TYPE;
458
- }
459
- /** Event type of a message that a child agent sends to its parent. */
460
- const AGENT_MESSAGE_EVENT_TYPE = "agent.message";
461
- /** Event type of a message from another top-level agent. */
462
- const TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE = "agent.top_level_message";
463
- /** True when an Event type names a message that another agent sent. */
464
- function isAgentMessageEventType(eventType) {
465
- return eventType === "agent.message" || eventType === "agent.top_level_message";
466
- }
467
467
  // src/chat/inbox-items/user-input-request.ts
468
468
  const USER_INPUT_LIMITS = {
469
469
  maxButtonOptions: 5,
@@ -1118,6 +1118,20 @@ function automationCardText(card) {
1118
1118
  `Automation ID: ${card.id}`
1119
1119
  ].filter(Boolean).join("\n");
1120
1120
  }
1121
+ /**
1122
+ * Return the status and warning that the card and the Slack details of an
1123
+ * Automation show. The status is the saved status, except that an active
1124
+ * Automation whose trigger cannot work shows as unavailable. Only a block or
1125
+ * a trigger problem gives a warning, like Needs attention in `collection.ts`.
1126
+ */
1127
+ function automationCardStatus(automation) {
1128
+ const problems = automation.triggerProblems ?? [];
1129
+ const warning = [automation.status === "blocked" ? automation.statusReason ?? "This automation is blocked." : void 0, problems.length > 0 ? ["Trigger unavailable.", ...problems].join(" ") : void 0].filter(Boolean).join(" ");
1130
+ return {
1131
+ status: automation.status === "active" && problems.length > 0 ? "unavailable" : automation.status,
1132
+ warning: warning || void 0
1133
+ };
1134
+ }
1121
1135
  // src/chat/conversations/cards.ts
1122
1136
  const storedCardSchema = automationCardSchema.extend({ operation: z.enum([
1123
1137
  "created",
@@ -1163,10 +1177,11 @@ function messageCardRef(card) {
1163
1177
  function readMessageCardRefs(value) {
1164
1178
  return [...storedCardSchema.array().parse(value.cards ?? []).flatMap(({ operation, ...card }) => operation === "deleted" ? [] : [messageCardRef(card)]), ...messageCardRefSchema.strip().array().parse(value.objectCards ?? [])];
1165
1179
  }
1166
- /** Resolve current saved facts without fetching providers or changing history. */
1180
+ /** Match each reference to the Annotation as it was read, in reference order. */
1167
1181
  function resolveMessageCards(refs, annotations) {
1168
1182
  return refs.map((ref) => {
1169
- const annotation = annotations.find((item) => item.kind === ref.kind && item.plugin === ref.plugin && item.key === ref.key);
1183
+ const named = annotations.filter((item) => item.plugin === ref.plugin && item.key === ref.key);
1184
+ const annotation = named.find((item) => item.kind === ref.kind) ?? named.find((item) => item.kind === "resource_link");
1170
1185
  return annotation ? annotationCard(annotation) : {
1171
1186
  ...ref,
1172
1187
  objectType: "item",
@@ -1177,7 +1192,11 @@ function resolveMessageCards(refs, annotations) {
1177
1192
  };
1178
1193
  });
1179
1194
  }
1180
- /** Copy saved annotation facts without storage timestamps for Message delivery. */
1195
+ /**
1196
+ * Return the card of a read Annotation without its timestamps, for Message
1197
+ * delivery. An Annotation that shows only its label gets that label as its
1198
+ * title.
1199
+ */
1181
1200
  function annotationCard(annotation) {
1182
1201
  const { createdAt: _createdAt, updatedAt: _updatedAt, ...value } = annotation;
1183
1202
  return value.kind === "object" ? value : {
@@ -1612,18 +1631,22 @@ const guardianActionReviewedEventDataSchema = z.object({
1612
1631
  "ask",
1613
1632
  "deny"
1614
1633
  ]),
1634
+ /** Set on decisions recorded since Guardian names one rule. */
1635
+ rule: z.string().min(1).optional(),
1636
+ /** Set on decisions recorded since the record keeps why. */
1637
+ reason: z.string().min(1).optional(),
1615
1638
  riskLevel: z.enum([
1616
1639
  "low",
1617
1640
  "medium",
1618
1641
  "high",
1619
1642
  "critical"
1620
- ]),
1643
+ ]).optional(),
1621
1644
  userAuthorization: z.enum([
1622
1645
  "high",
1623
1646
  "medium",
1624
1647
  "low",
1625
1648
  "unknown"
1626
- ])
1649
+ ]).optional()
1627
1650
  }).strict();
1628
1651
  const conversationMessageRoleSchema = z.union([
1629
1652
  z.literal("user"),
@@ -2127,12 +2150,7 @@ const conversationSourceTaskSchema = z.object({
2127
2150
  message: "sourceTask id and label must both be set or both omitted"
2128
2151
  });
2129
2152
  });
2130
- const conversationAnnotationReportSchema = conversationAnnotationInputSchema.and(z.object({
2131
- plugin: z.string().min(1),
2132
- createdAt: z.string().datetime(),
2133
- updatedAt: z.string().datetime(),
2134
- previewImages: z.array(objectPreviewImageSchema).optional()
2135
- }));
2153
+ const conversationAnnotationReportSchema = liveAnnotationSchema.and(z.object({ previewImages: z.array(objectPreviewImageSchema).optional() }));
2136
2154
  const conversationActivityPreviewSchema = z.object({
2137
2155
  createdAt: z.string().datetime(),
2138
2156
  mentions: z.array(actorIdentitySchema).optional(),
@@ -2382,18 +2400,20 @@ const conversationReportGuardianActionReviewedEventDataSchema = z.object({
2382
2400
  "ask",
2383
2401
  "deny"
2384
2402
  ]),
2403
+ rule: z.string().min(1).optional(),
2404
+ reason: z.string().min(1).optional(),
2385
2405
  riskLevel: z.enum([
2386
2406
  "low",
2387
2407
  "medium",
2388
2408
  "high",
2389
2409
  "critical"
2390
- ]),
2410
+ ]).optional(),
2391
2411
  userAuthorization: z.enum([
2392
2412
  "high",
2393
2413
  "medium",
2394
2414
  "low",
2395
2415
  "unknown"
2396
- ])
2416
+ ]).optional()
2397
2417
  }).strict();
2398
2418
  const conversationReportTurnContextEventDataSchema = z.object({
2399
2419
  type: z.literal("turn_context"),
@@ -3058,4 +3078,4 @@ const TODOS_REGISTRATION_NAME = "todos";
3058
3078
  const UPDATE_TODOS_TOOL_NAME = `${TODOS_REGISTRATION_NAME}_updateTodos`;
3059
3079
  /** Assignee text for the list's own agent, in tool results and blocks. */
3060
3080
  const SELF_TODO_ASSIGNEE = "self";
3061
- export { activityPreviewText as $, automationTitleSchema as $t, automationVersionSchema as A, isLegacyResultEventType as An, spaceListQuerySchema as At, conversationDetailQuerySchema as B, getNextRunAtMs as Bn, annotationCard as Bt, automationScheduleIntentSchema as C, userInputRequestSchema as Cn, instructionActors as Ct, automationVersionActivateSchema as D, TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE as Dn, SPACE_NAME_MAX_CHARS as Dt, automationUpdateSchema as E, AGENT_UPDATE_EVENT_TYPE as En, SPACE_DESCRIPTION_MAX_CHARS as Et, actorIdentitySchema as F, automationTaskText as Fn, spaceVisibilitySchema as Ft, conversationParamsSchema as G, usageSchema as Gn, resolveMessageCards as Gt, conversationEventHistorySchema as H, isValidTimeZone as Hn, messageCardText as Ht, conversationActivityPreviewSchema as I, DEFAULT_NOTIFICATION_SCHEDULE as In, updateSpaceBodySchema as It, conversationReportMessageEventSchema as J, inputFileSchema as Jt, conversationReportEventDataSchema as K, gatewayOnlyProviders as Kn, MAX_ATTACHMENT_BYTES as Kt, conversationAttachmentParamsSchema as L, isWithinNotificationSchedule as Ln, conversationTreeStateSchema as Lt, scheduledAutomationSummarySchema as M, automationTaskColumns as Mn, spaceParamsSchema as Mt, CONVERSATION_DETAIL_VERSION_HEADER as N, automationTaskDescription as Nn, spaceRefSchema as Nt, automationVersionListSchema as O, isAgentMessageEventType as On, archiveSpaceBodySchema as Ot, CONVERSATION_VERSION_HEADER as P, automationTaskSchema as Pn, spaceSchema as Pt, conversationUsageSchema as Q, automationInstructionToolSchema as Qt, conversationAttachmentQuerySchema as R, notificationScheduleSchema as Rn, conversationReadPositionSchema as Rt, automationRunWindowsSchema as S, userInputQuestionSchema as Sn, contextProvenance as St, automationSummarySchema as T, AGENT_MESSAGE_EVENT_TYPE as Tn, sameActorIdentity as Tt, conversationEventPageSchema as U, CONTENT_VERSION_HEADER as Un, readMessageCardRefs as Ut, conversationDetailReportSchema as V, getZonedDateTimeParts as Vn, messageCardRef as Vt, conversationEventsQuerySchema as W, apiErrorSchema as Wn, removedCardSchema as Wt, conversationSummaryReportSchema as X, readMessageAttachments as Xt, conversationReportStatusSchema as Y, messageAttachmentSchema as Yt, conversationSurfaceSchema as Z, automationContextToolSchema as Zt, automationListQuerySchema as _, buttonUserInputField as _n, historyReplacementSchema as _t, UPDATE_TODOS_TOOL_NAME as a, compileScheduleIntent as an, KNOWN_CONVERSATION_EVENT_TYPES as at, automationRunListSchema as b, normalizeUserInputAnswer as bn, piMessageSchema as bt, automationEditSchema as c, weekdaySchema as cn, conversationTurnFailureReasonSchema as ct, automationExecutionSchema as d, inboxItemNoticeRequestSchema as dn, agentHistoryFromRow as dt, taskOutcomeInputSchema as en, conversationChildAgentTotalsSchema as et, automationExecutionStatusDaySchema as f, inboxItemQuestion as fn, encodeAgentHistoryPayload as ft, automationListPageSchema as g, answeredChoices as gn, historyItemFromPiMessage as gt, automationListItemSchema as h, USER_INPUT_NOTE as hn, HISTORY_REPLACEMENT_TYPES as ht, TODO_STATUSES as i, ScheduleIntentError as in, formatAgentTypes as it, eventAutomationSummarySchema as j, automationSkillNameSchema as jn, spaceListSchema as jt, automationVersionParamsSchema as k, isAgentUpdateEventType as kn, createSpaceBodySchema as kt, automationEventCatalogSchema as l, eventAutomationSchema as ln, decodeStoredConversationEvent as lt, automationLifecycleSchema as m, USER_INPUT_LIMITS as mn, AGENT_HISTORY_ITEM_TYPES as mt, SELF_TODO_ASSIGNEE as n, scheduledAutomationSchema as nn, agentTypeInstructions as nt, isOpenTodoStatus as o, scheduleIntentFromTool as on, conversationEventDataSchema as ot, automationExecutionStatusSchema as p, inboxItemRequestSchema as pn, isAgentHistoryData as pt, conversationReportEventSchema as q, MAX_INPUT_ATTACHMENTS as qt, TODOS_REGISTRATION_NAME as r, scheduledRunSchema as rn, agentTypeSchema as rt, automationEditErrorSchema as s, toolScheduleIntentSchema as sn, conversationTurnFailureCodeSchema as st, OPEN_TODO_STATUSES as t, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as tn, AGENT_TYPES as tt, automationExecutionListSchema as u, eventAutomationTriggerSchema as un, newConversationEventSchema as ut, automationListSchema as v, formatUserInputAnswer as vn, isHistoryReplacement as vt, automationSchedulePreviewSchema as w, AGENT_EVENT_NAMESPACE as wn, instructionProvenanceFor as wt, automationRunSchema as x, userInputFieldsSchema as xn, agentInstructionProvenance as xt, automationParamsSchema as y, isEmptyUserInputAnswer as yn, piMessageFromHistoryItem as yt, conversationAuxiliaryCostsSchema as z, getFirstRunAtMs as zn, inboxItemChangeRecordSchema as zt };
3081
+ export { activityPreviewText as $, automationInstructionToolSchema as $t, automationVersionSchema as A, DEFAULT_NOTIFICATION_SCHEDULE as An, spaceListQuerySchema as At, conversationDetailQuerySchema as B, AGENT_UPDATE_EVENT_TYPE as Bn, annotationCard as Bt, automationScheduleIntentSchema as C, userInputQuestionSchema as Cn, instructionActors as Ct, automationVersionActivateSchema as D, automationTaskDescription as Dn, SPACE_NAME_MAX_CHARS as Dt, automationUpdateSchema as E, automationTaskColumns as En, SPACE_DESCRIPTION_MAX_CHARS as Et, actorIdentitySchema as F, getZonedDateTimeParts as Fn, spaceVisibilitySchema as Ft, conversationParamsSchema as G, gatewayOnlyProviders as Gn, resolveMessageCards as Gt, conversationEventHistorySchema as H, isAgentMessageEventType as Hn, messageCardText as Ht, conversationActivityPreviewSchema as I, isValidTimeZone as In, updateSpaceBodySchema as It, conversationReportMessageEventSchema as J, MAX_INPUT_ATTACHMENTS as Jt, conversationReportEventDataSchema as K, usageSchema as Kn, automationCardStatus as Kt, conversationAttachmentParamsSchema as L, CONTENT_VERSION_HEADER as Ln, conversationTreeStateSchema as Lt, scheduledAutomationSummarySchema as M, notificationScheduleSchema as Mn, spaceParamsSchema as Mt, CONVERSATION_DETAIL_VERSION_HEADER as N, getFirstRunAtMs as Nn, spaceRefSchema as Nt, automationVersionListSchema as O, automationTaskSchema as On, archiveSpaceBodySchema as Ot, CONVERSATION_VERSION_HEADER as P, getNextRunAtMs as Pn, spaceSchema as Pt, conversationUsageSchema as Q, automationContextToolSchema as Qt, conversationAttachmentQuerySchema as R, apiErrorSchema as Rn, conversationReadPositionSchema as Rt, automationRunWindowsSchema as S, userInputFieldsSchema as Sn, contextProvenance as St, automationSummarySchema as T, automationSkillNameSchema as Tn, sameActorIdentity as Tt, conversationEventPageSchema as U, isAgentUpdateEventType as Un, readMessageCardRefs as Ut, conversationDetailReportSchema as V, TOP_LEVEL_AGENT_MESSAGE_EVENT_TYPE as Vn, messageCardRef as Vt, conversationEventsQuerySchema as W, isLegacyResultEventType as Wn, removedCardSchema as Wt, conversationSummaryReportSchema as X, messageAttachmentSchema as Xt, conversationReportStatusSchema as Y, inputFileSchema as Yt, conversationSurfaceSchema as Z, readMessageAttachments as Zt, automationListQuerySchema as _, answeredChoices as _n, historyReplacementSchema as _t, UPDATE_TODOS_TOOL_NAME as a, ScheduleIntentError as an, KNOWN_CONVERSATION_EVENT_TYPES as at, automationRunListSchema as b, isEmptyUserInputAnswer as bn, piMessageSchema as bt, automationEditSchema as c, toolScheduleIntentSchema as cn, conversationTurnFailureReasonSchema as ct, automationExecutionSchema as d, eventAutomationTriggerSchema as dn, agentHistoryFromRow as dt, automationTitleSchema as en, conversationChildAgentTotalsSchema as et, automationExecutionStatusDaySchema as f, inboxItemNoticeRequestSchema as fn, encodeAgentHistoryPayload as ft, automationListPageSchema as g, USER_INPUT_NOTE as gn, historyItemFromPiMessage as gt, automationListItemSchema as h, USER_INPUT_LIMITS as hn, HISTORY_REPLACEMENT_TYPES as ht, TODO_STATUSES as i, scheduledRunSchema as in, formatAgentTypes as it, eventAutomationSummarySchema as j, isWithinNotificationSchedule as jn, spaceListSchema as jt, automationVersionParamsSchema as k, automationTaskText as kn, createSpaceBodySchema as kt, automationEventCatalogSchema as l, weekdaySchema as ln, decodeStoredConversationEvent as lt, automationLifecycleSchema as m, inboxItemRequestSchema as mn, AGENT_HISTORY_ITEM_TYPES as mt, SELF_TODO_ASSIGNEE as n, SCHEDULED_AUTOMATION_SYSTEM_ACTOR as nn, agentTypeInstructions as nt, isOpenTodoStatus as o, compileScheduleIntent as on, conversationEventDataSchema as ot, automationExecutionStatusSchema as p, inboxItemQuestion as pn, isAgentHistoryData as pt, conversationReportEventSchema as q, usageTokensSchema as qn, MAX_ATTACHMENT_BYTES as qt, TODOS_REGISTRATION_NAME as r, scheduledAutomationSchema as rn, agentTypeSchema as rt, automationEditErrorSchema as s, scheduleIntentFromTool as sn, conversationTurnFailureCodeSchema as st, OPEN_TODO_STATUSES as t, taskOutcomeInputSchema as tn, AGENT_TYPES as tt, automationExecutionListSchema as u, eventAutomationSchema as un, newConversationEventSchema as ut, automationListSchema as v, buttonUserInputField as vn, isHistoryReplacement as vt, automationSchedulePreviewSchema as w, userInputRequestSchema as wn, instructionProvenanceFor as wt, automationRunSchema as x, normalizeUserInputAnswer as xn, agentInstructionProvenance as xt, automationParamsSchema as y, formatUserInputAnswer as yn, piMessageFromHistoryItem as yt, conversationAuxiliaryCostsSchema as z, AGENT_MESSAGE_EVENT_TYPE as zn, inboxItemChangeRecordSchema as zt };
@@ -1,4 +1,4 @@
1
- import { Fs as SlackActionError, qs as withSlackRetries, zs as getSlackClient } from "./db-BFmyYZtJ.js";
1
+ import { Zs as getSlackClient, ac as withSlackRetries, qs as SlackActionError } from "./db-BCaNWl9p.js";
2
2
  import * as z from "zod";
3
3
  // src/chat/slack/users.ts
4
4
  const profileFieldsSchema = z.object({ fields: z.record(z.string(), z.object({
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { n as pluginCatalogRuntime } from "./catalog-runtime-DfSpJZdY.js";
2
+ import { Fd as getAppContext } from "./db-BCaNWl9p.js";
3
3
  import { isDeepStrictEqual } from "node:util";
4
4
  // src/chat/plugins/validation.ts
5
5
  var validation_exports = /* @__PURE__ */ __exportAll({
@@ -8,18 +8,18 @@ var validation_exports = /* @__PURE__ */ __exportAll({
8
8
  });
9
9
  /** Validate hook registrations against the loaded plugin manifest catalog. */
10
10
  function validatePluginRegistrations(registrations) {
11
- const loadedPlugins = new Map(pluginCatalogRuntime.getProviders().map((plugin) => [plugin.manifest.name, plugin]));
11
+ const loadedPlugins = new Map(getAppContext().catalog.getProviders().map((plugin) => [plugin.manifest.name, plugin]));
12
12
  for (const registration of registrations) {
13
13
  const loadedPlugin = loadedPlugins.get(registration.manifest.name);
14
14
  if (!loadedPlugin) throw new Error(`Plugin registration "${registration.manifest.name}" does not have a matching plugin manifest. Add an inline manifest, packageName, or app-local plugin.yaml with the same name.`);
15
- const effectiveRegistrationManifest = pluginCatalogRuntime.parseConfiguredInlineManifest(registration.manifest, loadedPlugin.dir);
15
+ const effectiveRegistrationManifest = getAppContext().catalog.parseConfiguredInlineManifest(registration.manifest, loadedPlugin.dir);
16
16
  if (!isDeepStrictEqual(effectiveRegistrationManifest, loadedPlugin.manifest)) throw new Error(`Plugin registration "${registration.manifest.name}" manifest does not match the loaded plugin manifest. Use one canonical manifest source for runtime hook plugins.`);
17
17
  }
18
18
  }
19
19
  /** Validate credential hook registrations against the loaded plugin manifests. */
20
20
  function validatePluginEgressCredentialHooks(registrations) {
21
21
  const plugins = new Map(registrations.map((registration) => [registration.manifest.name, registration]));
22
- for (const provider of pluginCatalogRuntime.getProviders()) {
22
+ for (const provider of getAppContext().catalog.getProviders()) {
23
23
  const hooks = plugins.get(provider.manifest.name)?.hooks;
24
24
  const hasGrantHook = Boolean(hooks?.grantForEgress);
25
25
  const hasIssueHook = Boolean(hooks?.issueCredential);
@@ -1,5 +1,5 @@
1
1
  // package.json
2
- var version = "0.317.0";
2
+ var version = "0.319.0";
3
3
  // src/version.ts
4
4
  /** Installed Junior package version, or `unknown` when package metadata is unavailable. */
5
5
  const JUNIOR_VERSION = typeof version === "string" && version.trim() ? version : "unknown";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export { t as JUNIOR_VERSION } from "./version-BeZhWWBE.js";
1
+ export { t as JUNIOR_VERSION } from "./version-BNm0JYj3.js";
@@ -1,8 +1,8 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-BKpuH2hG.js";
2
- import { $t as drainConversationMailbox, An as isAttemptInterrupt, Gt as checkInConversationWork, Ir as nudgeIdempotencyKey, Jt as clearConsumedConversationWake, Kt as claimConversationAttempt, Nr as ConversationQueueMessageRejectedError, Qt as deadLetterAttempt, Sn as isInvalidConversationRecordError, Ut as beginConversationResume, Xt as completeConversationStop, Zt as completeConversationWork, _n as countPendingConversationMessages, cn as releaseConversationWork, cr as getTurnRequestDeadline, dn as startConversationWork, jn as selectAttemptMessages, ln as requestAnotherSlice, on as recordAttemptFailure, ou as ownsLocation, rn as getConversationWorkState, sn as recordConversationRetry, tn as ensureConversationWake, xn as isFinalAttempt, yn as hasConversationStop, zt as ackMessages } from "./db-BFmyYZtJ.js";
3
- import { $ as isProviderRetryError, n as getChatConfig } from "./config-CHQ8X251.js";
4
- import { T as withLogContext, b as setSpanAttributes, h as logWarn, m as logInfo, p as logException } from "./logging--smS7XRK.js";
5
- import { K as saveHeldInput, W as getConversationStoppedAtMs } from "./mailbox-turn-uSXhUFc9.js";
2
+ import { $t as completeConversationStop, Ed as isProviderRetryError, Gr as nudgeIdempotencyKey, Hr as ConversationQueueMessageRejectedError, Ht as ackMessages, Jt as checkInConversationWork, Kt as beginConversationResume, Nn as isAttemptInterrupt, Pn as selectAttemptMessages, Sn as hasConversationStop, Tn as isInvalidConversationRecordError, Yt as claimConversationAttempt, Zt as clearConsumedConversationWake, bn as countPendingConversationMessages, dn as releaseConversationWork, dr as getTurnRequestDeadline, en as completeConversationWork, fn as requestAnotherSlice, in as ensureConversationWake, ln as recordAttemptFailure, mn as startConversationWork, nn as drainConversationMailbox, nu as isTopLevel, on as getConversationWorkState, tn as deadLetterAttempt, un as recordConversationRetry, wn as isFinalAttempt } from "./db-BCaNWl9p.js";
3
+ import { R as getChatConfig } from "./adapter-8_S6Birm.js";
4
+ import { f as logException, m as logWarn, p as logInfo, w as withLogContext, y as setSpanAttributes } from "./logging-BRPTXAdf.js";
5
+ import { A as getConversationStoppedAtMs, M as saveHeldInput } from "./markers-9QoqW5ov.js";
6
6
  // src/chat/task-execution/lost-lease.ts
7
7
  /**
8
8
  * Count a slice that lost its Conversation Lease as a failed attempt, then
@@ -213,7 +213,7 @@ async function processConversationWorkInContext(message, options) {
213
213
  let destination = initial.destination;
214
214
  if (!destination && options.conversationStore) {
215
215
  const stored = await options.conversationStore.get({ conversationId });
216
- if (stored && ownsLocation(stored)) destination = stored.destination;
216
+ if (stored && isTopLevel(stored)) destination = stored.destination;
217
217
  }
218
218
  const lease = await startConversationWork({
219
219
  conversationId,
@@ -0,0 +1,2 @@
1
+ ALTER TABLE "junior_turns" ADD COLUMN "discarded_cost_micro_usd" bigint DEFAULT 0 NOT NULL;--> statement-breakpoint
2
+ ALTER TABLE "junior_turns" ADD COLUMN "discarded_tokens" jsonb;
@@ -0,0 +1,73 @@
1
+ {
2
+ "type": "diff",
3
+ "version": "10",
4
+ "dialect": "postgres",
5
+ "id": "811305d1-7881-43e6-9f0c-280f35526253",
6
+ "prevIds": ["69888e8a-0d59-4095-b43a-c3e1ba2c6cc1"],
7
+ "footprints": [
8
+ {
9
+ "statementType": "add_column",
10
+ "statementTarget": [
11
+ "column",
12
+ "public",
13
+ "junior_turns",
14
+ "discarded_cost_micro_usd"
15
+ ],
16
+ "writes": [
17
+ "s|col|public.junior_turns.discarded_cost_micro_usd",
18
+ "n|col|public.junior_turns.discarded_cost_micro_usd",
19
+ "e|col|public.junior_turns.discarded_cost_micro_usd"
20
+ ],
21
+ "reads": ["n|tbl|public.junior_turns", "n|sch|public"]
22
+ },
23
+ {
24
+ "statementType": "add_column",
25
+ "statementTarget": [
26
+ "column",
27
+ "public",
28
+ "junior_turns",
29
+ "discarded_tokens"
30
+ ],
31
+ "writes": [
32
+ "s|col|public.junior_turns.discarded_tokens",
33
+ "n|col|public.junior_turns.discarded_tokens",
34
+ "e|col|public.junior_turns.discarded_tokens"
35
+ ],
36
+ "reads": ["n|tbl|public.junior_turns", "n|sch|public"]
37
+ }
38
+ ],
39
+ "deltas": [
40
+ {
41
+ "op": "create",
42
+ "row": {
43
+ "schema": "public",
44
+ "table": "junior_turns",
45
+ "name": "discarded_cost_micro_usd",
46
+ "type": "bigint",
47
+ "typeSchema": null,
48
+ "notNull": true,
49
+ "dimensions": 0,
50
+ "default": "0",
51
+ "generated": null,
52
+ "identity": null,
53
+ "entityType": "columns"
54
+ }
55
+ },
56
+ {
57
+ "op": "create",
58
+ "row": {
59
+ "schema": "public",
60
+ "table": "junior_turns",
61
+ "name": "discarded_tokens",
62
+ "type": "jsonb",
63
+ "typeSchema": null,
64
+ "notNull": false,
65
+ "dimensions": 0,
66
+ "default": null,
67
+ "generated": null,
68
+ "identity": null,
69
+ "entityType": "columns"
70
+ }
71
+ }
72
+ ]
73
+ }
@@ -0,0 +1,5 @@
1
+ -- New Spaces keep their name on the Lead only. 0.317.0 and 0.318.0 do not
2
+ -- read junior_spaces.name. A rollback to 0.316.0, which reads it, is no
3
+ -- longer supported.
4
+ -- squawk-ignore ban-drop-not-null -- unused since 0.317.0
5
+ ALTER TABLE "junior_spaces" ALTER COLUMN "name" DROP NOT NULL;
@@ -0,0 +1,29 @@
1
+ {
2
+ "type": "diff",
3
+ "version": "10",
4
+ "dialect": "postgres",
5
+ "id": "770bb17f-6db0-4c09-b900-5a19bce14b7e",
6
+ "prevIds": ["811305d1-7881-43e6-9f0c-280f35526253"],
7
+ "footprints": [
8
+ {
9
+ "statementType": "alter_column",
10
+ "statementTarget": ["column", "public", "junior_spaces", "name"],
11
+ "writes": ["s|colprop|public.junior_spaces.name.notNull"],
12
+ "reads": [
13
+ "n|tbl|public.junior_spaces",
14
+ "n|sch|public",
15
+ "n|col|public.junior_spaces.name"
16
+ ],
17
+ "sqlHash": "729e3a210f86c713"
18
+ }
19
+ ],
20
+ "deltas": [
21
+ {
22
+ "op": "alter",
23
+ "key": "columns\u0000[\"public\",\"junior_spaces\",\"name\"]",
24
+ "set": {
25
+ "notNull": false
26
+ }
27
+ }
28
+ ]
29
+ }
@@ -0,0 +1 @@
1
+ CREATE INDEX CONCURRENTLY IF NOT EXISTS "junior_conversation_annotations_object_id_idx" ON "junior_conversation_annotations" ("plugin",("annotation_json" ->> 'objectId'),"created_at") WHERE "kind" = 'object' and ("annotation_json" ->> 'objectId') is not null;
@@ -0,0 +1,69 @@
1
+ {
2
+ "type": "diff",
3
+ "version": "10",
4
+ "dialect": "postgres",
5
+ "id": "798b04e0-3f09-46d8-8a21-aefeaa9921f9",
6
+ "prevIds": ["770bb17f-6db0-4c09-b900-5a19bce14b7e"],
7
+ "footprints": [
8
+ {
9
+ "statementType": "create_index",
10
+ "statementTarget": [
11
+ "index",
12
+ "public",
13
+ "junior_conversation_annotations",
14
+ "junior_conversation_annotations_object_id_idx"
15
+ ],
16
+ "writes": [
17
+ "s|idx|public.junior_conversation_annotations_object_id_idx",
18
+ "n|idx|public.junior_conversation_annotations_object_id_idx",
19
+ "e|idx|public.junior_conversation_annotations_object_id_idx",
20
+ "n|rel|public.junior_conversation_annotations_object_id_idx"
21
+ ],
22
+ "reads": [
23
+ "n|tbl|public.junior_conversation_annotations",
24
+ "n|sch|public",
25
+ "n|col|public.junior_conversation_annotations.plugin",
26
+ "n|col|public.junior_conversation_annotations.created_at"
27
+ ]
28
+ }
29
+ ],
30
+ "deltas": [
31
+ {
32
+ "op": "create",
33
+ "row": {
34
+ "schema": "public",
35
+ "table": "junior_conversation_annotations",
36
+ "name": "junior_conversation_annotations_object_id_idx",
37
+ "nameExplicit": true,
38
+ "columns": [
39
+ {
40
+ "value": "plugin",
41
+ "isExpression": false,
42
+ "asc": true,
43
+ "nullsFirst": false,
44
+ "opclass": null
45
+ },
46
+ {
47
+ "value": "(\"annotation_json\" ->> 'objectId')",
48
+ "isExpression": true,
49
+ "asc": true,
50
+ "nullsFirst": false,
51
+ "opclass": null
52
+ },
53
+ {
54
+ "value": "created_at",
55
+ "isExpression": false,
56
+ "asc": true,
57
+ "nullsFirst": false,
58
+ "opclass": null
59
+ }
60
+ ],
61
+ "isUnique": false,
62
+ "where": "\"kind\" = 'object' and (\"annotation_json\" ->> 'objectId') is not null",
63
+ "with": "",
64
+ "method": "btree",
65
+ "entityType": "indexes"
66
+ }
67
+ }
68
+ ]
69
+ }
@@ -0,0 +1,78 @@
1
+ ALTER TABLE "junior_conversation_annotations" ADD COLUMN "subject_kind" text;--> statement-breakpoint
2
+ ALTER TABLE "junior_conversation_annotations" ADD COLUMN "subject_id" text;--> statement-breakpoint
3
+ ALTER TABLE "junior_conversation_annotations" ADD COLUMN "action" text;--> statement-breakpoint
4
+ -- Each Annotation names its object by a subject, as an Inbox item does, and
5
+ -- says what the Conversation did to it. New code writes both. Old workers
6
+ -- still write rows without them while this release rolls out, and new code
7
+ -- writes none for an object whose provider id it does not know, so a
8
+ -- trigger fills them from the saved JSON. The backfill below fires the same
9
+ -- trigger.
10
+ --
11
+ -- The subject of a saved object, by its plugin and type:
12
+ -- - An Automation card of core (`junior`) is the core `automation` kind,
13
+ -- with the Automation id.
14
+ -- - A GitHub pull request is `github:pull_request`, with GitHub's id of it,
15
+ -- read from the code change records by the repository and number in the
16
+ -- key. A GitHub issue is `github:issue`, with the `objectId` that new
17
+ -- issue cards saved.
18
+ -- - A Calendar event, a Vercel deployment, and a Linear Ticket keep their
19
+ -- key, which is the provider id (a Ticket's is its identifier).
20
+ -- - Any other object, such as an attached link or a GitHub object whose id
21
+ -- is not known, is the core `link` kind, with its link.
22
+ -- Every saved object was changed: the old JSON does not say which
23
+ -- Conversation created it.
24
+ CREATE OR REPLACE FUNCTION "junior_conversation_annotations_legacy_subject"()
25
+ RETURNS trigger
26
+ LANGUAGE plpgsql
27
+ AS $function$
28
+ DECLARE
29
+ object_type text := NEW."annotation_json"->>'objectType';
30
+ url text := NEW."annotation_json"->>'url';
31
+ github_ref text := CASE
32
+ WHEN NEW."plugin" = 'github' AND NEW."key" ~ '^[^#]+#[0-9]+$' THEN NEW."key"
33
+ END;
34
+ github_pull_request boolean := github_ref IS NOT NULL AND (
35
+ object_type = 'code_change'
36
+ OR (object_type IS NULL AND url ~ '^https://github\.com/[^/]+/[^/]+/pull/[0-9]+')
37
+ );
38
+ kind text;
39
+ id text;
40
+ BEGIN
41
+ IF NEW."plugin" = 'junior' AND object_type = 'automation' THEN
42
+ kind := 'automation';
43
+ id := NEW."key";
44
+ ELSIF github_pull_request THEN
45
+ SELECT c."provider_id" INTO id
46
+ FROM "junior_code_changes" c
47
+ JOIN "junior_code_repositories" r ON r."id" = c."repository_id"
48
+ WHERE c."provider" = 'github'
49
+ AND lower(r."name") = lower(split_part(github_ref, '#', 1))
50
+ AND c."number" = split_part(github_ref, '#', 2)::integer
51
+ LIMIT 1;
52
+ kind := CASE WHEN id IS NOT NULL THEN 'github:pull_request' END;
53
+ ELSIF github_ref IS NOT NULL THEN
54
+ id := NEW."annotation_json"->>'objectId';
55
+ kind := CASE WHEN id IS NOT NULL THEN 'github:issue' END;
56
+ ELSIF NEW."plugin" = 'google' AND object_type = 'calendar_event' THEN
57
+ kind := 'google:calendar_event';
58
+ id := NEW."key";
59
+ ELSIF NEW."plugin" = 'vercel' AND object_type = 'deployment' THEN
60
+ kind := 'vercel:deployment';
61
+ id := NEW."key";
62
+ ELSIF NEW."plugin" = 'linear' AND object_type = 'task' THEN
63
+ kind := 'linear:issue';
64
+ id := NEW."key";
65
+ END IF;
66
+ IF NEW."subject_kind" IS NULL THEN
67
+ NEW."subject_kind" := coalesce(kind, 'link');
68
+ NEW."subject_id" := CASE WHEN kind IS NOT NULL THEN id ELSE coalesce(url, NEW."key") END;
69
+ END IF;
70
+ IF NEW."action" IS NULL THEN
71
+ NEW."action" := 'changed';
72
+ END IF;
73
+ RETURN NEW;
74
+ END;
75
+ $function$;--> statement-breakpoint
76
+ CREATE TRIGGER "junior_conversation_annotations_legacy_subject" BEFORE INSERT OR UPDATE ON "junior_conversation_annotations" FOR EACH ROW WHEN (NEW."subject_kind" IS NULL OR NEW."action" IS NULL) EXECUTE FUNCTION "junior_conversation_annotations_legacy_subject"();--> statement-breakpoint
77
+ -- junior:bounded-backfill: every saved Annotation needs its subject before search and the new primary key use it, so the update runs once over the Annotation table. Each Conversation has only the few objects that it created or changed, and the update writes each row once.
78
+ UPDATE "junior_conversation_annotations" SET "subject_kind" = NULL;