@sentry/junior 0.311.0 → 0.313.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 (120) hide show
  1. package/dist/{adapter-B1wujchl.js → adapter-CYAvJzZS.js} +1 -1
  2. package/dist/{adapter-context-G2M0y6rP.js → adapter-context-CVsHoVSf.js} +2 -2
  3. package/dist/{admin-DCiBhUT1.js → admin-Cyhb4TwZ.js} +1 -1
  4. package/dist/{agent-runner-BVHPUIc8.js → agent-runner-B5y9MsT-.js} +3487 -3493
  5. package/dist/api/schema.d.ts +2 -2
  6. package/dist/api/schema.js +6 -6
  7. package/dist/api.d.ts +2 -2
  8. package/dist/api.js +294 -311
  9. package/dist/{app-Cw5Vy6H6.d.ts → app-DA8-hCMj.d.ts} +2 -9
  10. package/dist/app.d.ts +1 -1
  11. package/dist/app.js +336 -604
  12. package/dist/{background-compaction-queue-CJDnWVOJ.js → background-compaction-queue-iZXadLV3.js} +60 -85
  13. package/dist/{catalog-runtime-DMY3VV-D.js → catalog-runtime-kkE3hvCX.js} +1 -1
  14. package/dist/channel-access-mt7K6dPh.js +221 -0
  15. package/dist/cli/chat.js +18 -19
  16. package/dist/cli/check.js +3 -3
  17. package/dist/cli/init.js +0 -1
  18. package/dist/cli/main.js +3 -7
  19. package/dist/cli/plugins.js +4 -4
  20. package/dist/cli/run.d.ts +1 -2
  21. package/dist/cli/run.js +1 -2
  22. package/dist/cli/snapshot-create.js +5 -5
  23. package/dist/cli/upgrade.d.ts +1 -1
  24. package/dist/cli/upgrade.js +3 -3
  25. package/dist/{config-BrXDQefC.js → config-CWbwKj0j.js} +59 -27
  26. package/dist/{continue-in-slack-DNXSC9So.js → continue-in-slack-CxyFzdlF.js} +7 -8
  27. package/dist/{conversation-feed-DkinDu5o.js → conversation-feed-BEXLD3Me.js} +86 -21
  28. package/dist/{conversation-privacy-DxttrKb9.js → conversation-privacy-BrMiDN61.js} +1 -1
  29. package/dist/{conversation-turn-DWw7Xhdr.js → conversation-turn-B35eu0uz.js} +78 -56
  30. package/dist/{credential-sync-Bk8wGb8Y.js → credential-sync-DWTOEQrm.js} +15 -15
  31. package/dist/{projection-Cns7XwWa.js → credentialed-Dyv8b-lu.js} +16306 -20732
  32. package/dist/{db-7ETESH44.d.ts → db-DYGcXYl3.d.ts} +11 -6
  33. package/dist/{db-DTxzH7u5.js → db-PwSRzWWn.js} +181 -100
  34. package/dist/{executor-DqTiYj9S.js → executor-CgWyWfYz.js} +117 -99
  35. package/dist/{html-B9Sl4Axb.js → html-DidUcRhI.js} +6 -6
  36. package/dist/ingest-B0AggUEC.js +7931 -0
  37. package/dist/{install-Sg4ePfLl.js → install-2urLLXNt.js} +2 -2
  38. package/dist/instrumentation.js +3 -3
  39. package/dist/{lineage-BHAMpNKr.js → lineage-BXplQAVH.js} +2 -2
  40. package/dist/{stop-CYsfc0Ed.js → list-DyIyReSV.js} +709 -475
  41. package/dist/{logging-FjclQsXu.js → logging-DNt-qOIO.js} +1 -1
  42. package/dist/{schedule-BLJ476XQ.js → media-B0pZJ0bG.js} +1058 -11
  43. package/dist/{message-CJ7_RL50.js → message-Z5YKC-Af.js} +35 -28
  44. package/dist/{model-input-CMLh4Cwq.js → model-input-BhPJYdSV.js} +3 -3
  45. package/dist/nitro.d.ts +1 -1
  46. package/dist/nitro.js +4 -3
  47. package/dist/{oauth-callback-server-RVcbiDjL.js → oauth-callback-server-ByvDdcdY.js} +2 -2
  48. package/dist/{oauth-relay-Bu9kkaQu.js → oauth-relay-D-kK0yoN.js} +1 -1
  49. package/dist/{registry-BPwuOP2O.js → registry-POH4bZC4.js} +1 -1
  50. package/dist/reporting-window-C4dbzDiR.js +124 -0
  51. package/dist/request-deadline-BUiRYQYj.js +24 -0
  52. package/dist/{resolve-BK29bBry.js → resolve-CWtBNSKP.js} +3 -3
  53. package/dist/{runner-BcAE-cJm.js → runner-CsZ_VRxp.js} +14 -16
  54. package/dist/{sandbox-egress-signals-C-q0go5b.js → sandbox-egress-signals-FbCk1FkN.js} +1 -1
  55. package/dist/{schema-DYcJeV7d.d.ts → schema-DBf18QPS.d.ts} +2773 -3630
  56. package/dist/{schema-BLgSZXcL.js → schema-DojR2uCL.js} +106 -121
  57. package/dist/{service-account-iJoCtkHR.js → service-account-CDYb9hfX.js} +3 -3
  58. package/dist/{service-account-gN0zqf0S.js → service-account-o15pZWcJ.js} +5 -5
  59. package/dist/{skills-BoZ80epJ.js → skills-B0jP4whm.js} +2 -2
  60. package/dist/{slack-conversation-unfurl-CogYrITA.js → slack-conversation-unfurl-D26t9kBC.js} +9 -9
  61. package/dist/{spawn-Dk92r7mX.js → spawn-BjljgExZ.js} +14 -32
  62. package/dist/start-conversation-DbVujrwO.js +755 -0
  63. package/dist/{state-DH3Cmgp3.js → state-BTawTCme.js} +4 -4
  64. package/dist/statuses-BKwqCPhj.js +69 -0
  65. package/dist/store-CjXrp-Up.js +492 -0
  66. package/dist/task-queue-Cwlatjz3.js +90 -0
  67. package/dist/task-runner--Ke8KSMf.js +1432 -0
  68. package/dist/{thread-context-BW2BsQbH.js → thread-context-B8exINEe.js} +6 -7
  69. package/dist/turn-membership-DTR3SaKD.js +5859 -0
  70. package/dist/{validation-DrJd0nnq.js → validation-Ce0qbMlT.js} +1 -1
  71. package/dist/{task-queue-C_zldF5J.js → vercel-queue-q4z8w5QO.js} +93 -172
  72. package/dist/{version-CNKZ8owc.js → version-DFh4n9nr.js} +1 -1
  73. package/dist/version.js +1 -1
  74. package/dist/{warmup-BWdHew2H.js → warmup-D5hzqTcp.js} +4853 -13605
  75. package/dist/web-message-id-C6P83ans.js +10 -0
  76. package/dist/{worker-t9qpu_Zx.js → worker-CDg9Lbpg.js} +20 -7
  77. package/migrations/0143_todos.sql +14 -0
  78. package/migrations/0144_inbox_items.sql +32 -0
  79. package/migrations/0145_todo_changed_by_agent.sql +1 -0
  80. package/migrations/0146_inbox_item_subject_title_parts.sql +1 -0
  81. package/migrations/0147_inbox_snooze_wake_reason.sql +1 -0
  82. package/migrations/0148_authorization_request_index.sql +1 -0
  83. package/migrations/0149_conversation_metadata.sql +10 -0
  84. package/migrations/0150_conversation_metadata_fill.sql +39 -0
  85. package/migrations/0151_conversation_search_index.sql +1 -0
  86. package/migrations/0152_inbox_item_legacy_automation_keys.sql +21 -0
  87. package/migrations/0153_artifact_expiry.sql +1 -0
  88. package/migrations/0154_artifact_permanent_sha_index.sql +1 -0
  89. package/migrations/0155_artifact_drop_public_sha_index.sql +3 -0
  90. package/migrations/0156_conversation_kind_lead.sql +6 -0
  91. package/migrations/0157_conversation_lead_actor_index.sql +1 -0
  92. package/migrations/0158_keep_legacy_archive_columns.sql +5 -0
  93. package/migrations/0159_conversation_embeddings_fk_validate.sql +5 -0
  94. package/migrations/meta/0143_snapshot.json +6434 -0
  95. package/migrations/meta/0144_snapshot.json +6434 -0
  96. package/migrations/meta/0145_snapshot.json +6440 -0
  97. package/migrations/meta/0146_snapshot.json +6446 -0
  98. package/migrations/meta/0147_snapshot.json +6452 -0
  99. package/migrations/meta/0148_snapshot.json +6474 -0
  100. package/migrations/meta/0149_snapshot.json +6490 -0
  101. package/migrations/meta/0150_snapshot.json +6490 -0
  102. package/migrations/meta/0151_snapshot.json +6505 -0
  103. package/migrations/meta/0152_snapshot.json +6505 -0
  104. package/migrations/meta/0153_snapshot.json +6511 -0
  105. package/migrations/meta/0154_snapshot.json +6533 -0
  106. package/migrations/meta/0155_snapshot.json +6511 -0
  107. package/migrations/meta/0156_snapshot.json +6511 -0
  108. package/migrations/meta/0157_snapshot.json +6527 -0
  109. package/migrations/meta/0158_snapshot.json +6515 -0
  110. package/migrations/meta/0159_snapshot.json +6515 -0
  111. package/migrations/meta/_journal.json +120 -1
  112. package/package.json +6 -6
  113. package/skills/design-automation-skill/SKILL.md +108 -0
  114. package/dist/briefs-BDjnug6Y.js +0 -395
  115. package/dist/conversation-ca__NDQW.js +0 -1063
  116. package/dist/prompt-CDqcsDYC.js +0 -910
  117. package/dist/store-DmmMIrQi.js +0 -335
  118. package/dist/task-runner-C7oCJQIx.js +0 -294
  119. package/dist/turn-session-routing-Xh_2nSQe.js +0 -261
  120. package/dist/web-message-id-Ch5dPq-a.js +0 -306
@@ -1002,6 +1002,125 @@
1002
1002
  "when": 1795201134126,
1003
1003
  "tag": "0142_memory_core_indexes",
1004
1004
  "breakpoints": true
1005
+ },
1006
+ {
1007
+ "idx": 143,
1008
+ "version": "7",
1009
+ "when": 1795218746587,
1010
+ "tag": "0143_todos",
1011
+ "breakpoints": true
1012
+ },
1013
+ {
1014
+ "idx": 144,
1015
+ "version": "7",
1016
+ "when": 1795249396921,
1017
+ "tag": "0144_inbox_items",
1018
+ "breakpoints": true
1019
+ },
1020
+ {
1021
+ "idx": 145,
1022
+ "version": "7",
1023
+ "when": 1795283811414,
1024
+ "tag": "0145_todo_changed_by_agent",
1025
+ "breakpoints": true
1026
+ },
1027
+ {
1028
+ "idx": 146,
1029
+ "version": "7",
1030
+ "when": 1795286127229,
1031
+ "tag": "0146_inbox_item_subject_title_parts",
1032
+ "breakpoints": true
1033
+ },
1034
+ {
1035
+ "idx": 147,
1036
+ "version": "7",
1037
+ "when": 1795290103913,
1038
+ "tag": "0147_inbox_snooze_wake_reason",
1039
+ "breakpoints": true
1040
+ },
1041
+ {
1042
+ "idx": 148,
1043
+ "version": "7",
1044
+ "when": 1795299840612,
1045
+ "tag": "0148_authorization_request_index",
1046
+ "breakpoints": true
1047
+ },
1048
+ {
1049
+ "idx": 149,
1050
+ "version": "7",
1051
+ "when": 1795301948500,
1052
+ "tag": "0149_conversation_metadata",
1053
+ "breakpoints": true
1054
+ },
1055
+ {
1056
+ "idx": 150,
1057
+ "version": "7",
1058
+ "when": 1795301950736,
1059
+ "tag": "0150_conversation_metadata_fill",
1060
+ "breakpoints": true
1061
+ },
1062
+ {
1063
+ "idx": 151,
1064
+ "version": "7",
1065
+ "when": 1795301953076,
1066
+ "tag": "0151_conversation_search_index",
1067
+ "breakpoints": true
1068
+ },
1069
+ {
1070
+ "idx": 152,
1071
+ "version": "7",
1072
+ "when": 1795314540484,
1073
+ "tag": "0152_inbox_item_legacy_automation_keys",
1074
+ "breakpoints": true
1075
+ },
1076
+ {
1077
+ "idx": 153,
1078
+ "version": "7",
1079
+ "when": 1795315494234,
1080
+ "tag": "0153_artifact_expiry",
1081
+ "breakpoints": true
1082
+ },
1083
+ {
1084
+ "idx": 154,
1085
+ "version": "7",
1086
+ "when": 1795315495798,
1087
+ "tag": "0154_artifact_permanent_sha_index",
1088
+ "breakpoints": true
1089
+ },
1090
+ {
1091
+ "idx": 155,
1092
+ "version": "7",
1093
+ "when": 1795315497375,
1094
+ "tag": "0155_artifact_drop_public_sha_index",
1095
+ "breakpoints": true
1096
+ },
1097
+ {
1098
+ "idx": 156,
1099
+ "version": "7",
1100
+ "when": 1795315498375,
1101
+ "tag": "0156_conversation_kind_lead",
1102
+ "breakpoints": true
1103
+ },
1104
+ {
1105
+ "idx": 157,
1106
+ "version": "7",
1107
+ "when": 1795315499375,
1108
+ "tag": "0157_conversation_lead_actor_index",
1109
+ "breakpoints": true
1110
+ },
1111
+ {
1112
+ "idx": 158,
1113
+ "version": "7",
1114
+ "when": 1795331749525,
1115
+ "tag": "0158_keep_legacy_archive_columns",
1116
+ "breakpoints": true
1117
+ },
1118
+ {
1119
+ "idx": 159,
1120
+ "version": "7",
1121
+ "when": 1795374840076,
1122
+ "tag": "0159_conversation_embeddings_fk_validate",
1123
+ "breakpoints": true
1005
1124
  }
1006
1125
  ]
1007
- }
1126
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sentry/junior",
3
- "version": "0.311.0",
3
+ "version": "0.313.0",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -65,7 +65,7 @@
65
65
  "@modelcontextprotocol/sdk": "1.32.0",
66
66
  "@neondatabase/serverless": "^1.1.0",
67
67
  "@sentry/api": "2.16.0",
68
- "@sentry/junior-plugin-api": "0.311.0",
68
+ "@sentry/junior-plugin-api": "0.313.0",
69
69
  "@sentry/nitro": "11.14.0",
70
70
  "@sentry/node": "11.14.0",
71
71
  "@sentry/server-utils": "11.14.0",
@@ -90,7 +90,7 @@
90
90
  "jose": "^6.2.3",
91
91
  "just-bash": "3.0.1",
92
92
  "node-html-markdown": "^2.0.0",
93
- "p-limit": "^7.3.1",
93
+ "p-limit": "^7.3.3",
94
94
  "parse5": "^7.3.0",
95
95
  "pg": "^8.16.3",
96
96
  "sharp": "^0.35.3",
@@ -116,9 +116,9 @@
116
116
  "@emnapi/core": "^1.10.0",
117
117
  "@emnapi/runtime": "^1.10.0",
118
118
  "@hono/node-server": "2.1.3",
119
- "@sentry/junior-github": "0.311.0",
120
- "@sentry/junior-notion": "0.311.0",
121
- "@sentry/junior-sentry": "0.311.0",
119
+ "@sentry/junior-github": "0.313.0",
120
+ "@sentry/junior-notion": "0.313.0",
121
+ "@sentry/junior-sentry": "0.313.0",
122
122
  "@sentry/junior-testing": "0.0.0",
123
123
  "@types/node": "^24.19.2",
124
124
  "@types/pg": "^8.15.6",
@@ -0,0 +1,108 @@
1
+ ---
2
+ name: design-automation-skill
3
+ description: Write, change, or review a skill that Automations run, or turn a long Automation instruction into one. Gives the required sections, the inputs and scope contract, checks for work already in progress, the report and empty result, words to leave out, validation, and naming. Use when asked to write or review such a skill, or to move an Automation instruction into a skill. Do not use to create or edit the Automation itself, or for a skill that only people run.
4
+ ---
5
+
6
+ # Design an automation skill
7
+
8
+ An automation skill does one kind of recurring work. An Automation runs it after a schedule or an event, and a person can run it by hand with the same result. The skill owns the work. The Automation owns when it runs, where the result goes, and the values for one setup.
9
+
10
+ When you turn an instruction into a skill, move its steps, defaults, and report format into the skill. The rest stays in the Automation context.
11
+
12
+ ## Required sections
13
+
14
+ Use this order:
15
+
16
+ 1. **Frontmatter description.** Say what one run produces, name both scopes, and write triggers as the work, such as "when a CI check fails and might be flaky". Do not name the caller.
17
+ 2. **Purpose.** One or two sentences: what a run produces, and how often a run finds nothing.
18
+ 3. **Inputs.** A table with the columns `Input` and `How to resolve it`.
19
+ 4. **Rules.** Hard limits, then a **Side effects** list with each kind of write the skill can make.
20
+ 5. **Workflow.** Numbered steps. The first step reads the target's own conventions: agent docs, contributing guide, and CI files.
21
+ 6. **Report.** The format, and the one empty-result line.
22
+
23
+ Put only a brief for parallel workers or a long template in `references/`.
24
+
25
+ ## Inputs and scope
26
+
27
+ - Give each input a row. Resolve it in this order: the value the request names; the value from the item the request points at, such as a failed run, a pull request, or an issue; the current checkout or a configured default. With none of these, stop and name the missing input.
28
+ - Give each row a default, and say that the request can change it.
29
+ - Values that change between setups are inputs: repos, projects, teams, thresholds, people to tag, and paths that need sign-off. Do not write them into the steps. A skill for one named system can keep its fixed values.
30
+ - Use two scopes:
31
+ - **One item**: the request points at one thing. Decide about that thing, and look back over a short window, such as 7 days, for the same problem.
32
+ - **Sweep**: all other requests. Check every item in a default window, such as the last 48 hours.
33
+ - The skill never asks whether a person or an Automation started it.
34
+
35
+ ## Evidence
36
+
37
+ When a run acts on problems that it finds:
38
+
39
+ - Before you act on an item, prove that the evidence caused the problem. Compare with healthy cases of the same kind. Evidence that also shows in healthy cases is noise.
40
+ - Require repeats before a write. One occurrence is not enough unless the request says so.
41
+ - Group by cause, not by name. One cause in many places is one item. Two causes in one place are two items.
42
+
43
+ ## Work already in progress
44
+
45
+ Runs can overlap, and people work on the same problems.
46
+
47
+ - Give each item a stable key that a search finds, such as a branch name `fix-<kind>/<slug>`, an issue title prefix, or a marker in a comment. Use the target's own convention when it has one.
48
+ - Before you act, search open pull requests, recent branches, open issues, and changes merged since the problem started. When something covers the item, skip it and keep the link for the report.
49
+ - Search again right before each write.
50
+ - Do not push to, rebase, or comment on work that someone else owns, unless the request says to.
51
+
52
+ ## Parallel work
53
+
54
+ When items are independent, write a brief in `references/` that one worker can follow with no other context: the item key, the evidence with links, the suspect change, and the standard the result must meet. Write "when you can hand work to parallel workers", and do not name a tool. Do not report before every worker returns.
55
+
56
+ ## Report
57
+
58
+ - The first line gives the outcome.
59
+ - Then one block for each item, with the same fields each time and a link for each claim.
60
+ - The empty result is exactly one line, such as `No new <items> in <scope> since <time>.`
61
+ - The skill does not say whether to post the report or the empty line. The Automation context says when to post nothing.
62
+
63
+ ## Side effects
64
+
65
+ List each kind of write under **Side effects**, such as "opens pull requests in the target repo" or "comments on the issue that the request names". Action review does not read the skill. Until it does, the Automation context must restate the scope that a run needs, such as the repos it can write to or the teams it can read.
66
+
67
+ ## Leave out
68
+
69
+ Do not put these in `SKILL.md` or `references/`:
70
+
71
+ - Schedules, Destinations, and where to post.
72
+ - How a run ends, or which tool ends it.
73
+ - Different steps for an Automation run and a request by hand, and columns such as "Automation run" and "Manual request".
74
+ - Automation instruction templates or setup steps.
75
+ - Runtime words:
76
+
77
+ | Do not write | Write |
78
+ | --- | --- |
79
+ | `reply`, `noReply`, `reportBlocked`, "Ending a run" | the report, or no report |
80
+ | `spawnAgent`, `messageAgent`, Task, Thread | parallel workers |
81
+ | `addInboxItem`, Inbox item, review item | ask a person |
82
+ | Automation creator, Automation run, Turn, Destination, outcome | the requester, a run |
83
+ | `createAutomation`, `watchEvents`, `loadSkill`, how the skill is invoked | nothing |
84
+ | "when a scheduled task names this skill" | the work that starts it |
85
+ | Guardian, action review | the scope in **Side effects** |
86
+
87
+ ## Validate
88
+
89
+ You do not need a spec file. Do these steps:
90
+
91
+ 1. Run `junior check` and fix each error.
92
+ 2. Search the skill for each word in **Leave out**.
93
+ 3. Run the skill by hand in a local agent turn, such as `junior chat -p "<request>"`, on four cases:
94
+ - an item that needs action
95
+ - an item that needs no action
96
+ - a sweep window with nothing in it: expect only the empty line
97
+ - an item with work already in progress: expect a skip with its link
98
+
99
+ Keep the replies and tool calls as evidence for review.
100
+ 4. When the skill replaces an instruction, compare its decisions with the last runs of the old Automation on the same items.
101
+ 5. Switch the Automation to the skill with a short context, and read its first runs.
102
+
103
+ ## Name
104
+
105
+ - Use `automate-<outcome>` when an Automation is the main caller and the skill works on any repo or project. `<outcome>` is what a run produces, as a plural noun: `automate-flaky-test-fixes`, `automate-dependency-updates`.
106
+ - A skill for one named system keeps a domain name.
107
+ - Do not use caller or schedule words, such as `-daily`, `-sweep`, `-responder`, or `-cron`.
108
+ - The directory name is the same as `name`.
@@ -1,395 +0,0 @@
1
- import { I as briefResourceLabel, N as briefCodeChangeSchema, R as parseBriefInput, f as conversationEventPageSchema, u as conversationDetailReportSchema } from "./conversation-ca__NDQW.js";
2
- import { c as generateBrief, n as briefEntriesFromReportEvents, t as BRIEF_PROMPT, u as completeObject } from "./prompt-CDqcsDYC.js";
3
- import { CLI_USAGE } from "./cli/run.js";
4
- import * as z from "zod";
5
- import path from "node:path";
6
- import { mkdir, readFile, writeFile } from "node:fs/promises";
7
- // src/chat/briefs/render.ts
8
- function list(items, empty) {
9
- return items.length > 0 ? items.map((item) => `- ${item}`).join("\n") : empty;
10
- }
11
- function escapeLabel(label) {
12
- return label.replaceAll("[", "\\[").replaceAll("]", "\\]");
13
- }
14
- function formatCost(costUsd) {
15
- return costUsd === void 0 ? "not reported" : `$${costUsd.toFixed(6)}`;
16
- }
17
- function formatCount(count, noun) {
18
- return `${count} ${noun}${count === 1 ? "" : "s"}`;
19
- }
20
- function formatRecordCodeChange(change) {
21
- const dates = [
22
- change.openedAt ? `opened ${change.openedAt}` : void 0,
23
- change.mergedAt ? `merged ${change.mergedAt}` : void 0,
24
- change.closedAt ? `closed ${change.closedAt}` : void 0
25
- ].filter((value) => Boolean(value));
26
- return `[${escapeLabel(`${change.repository}#${change.number}${change.title ? ` · ${change.title}` : ""}`)}](${change.url}) · ${change.state}${dates.length ? ` · ${dates.join(" · ")}` : ""}`;
27
- }
28
- /** Render the final Brief and its local evidence check as readable Markdown. */
29
- function renderBriefMarkdown(args) {
30
- const { brief, evidence } = args.generation;
31
- const links = brief.links.map((link) => `[${escapeLabel(link.label)}](${link.url}) · ${link.kind}${link.status ? ` · ${link.status}` : ""}`);
32
- const dropped = evidence.droppedUrls.length ? evidence.droppedUrls.map((url) => `raw \`${url.raw}\` · normalized \`${url.normalized}\``) : ["None"];
33
- const record = brief.record;
34
- const location = record.location ? `${record.location.provider}${record.location.channelName ? ` · ${record.location.channelName}` : ""}` : "None";
35
- return [
36
- `# ${args.input.title ?? `Brief ${args.input.conversationId}`}`,
37
- "",
38
- "## Record",
39
- "",
40
- `- Started: ${record.startedAt}`,
41
- `- Last activity: ${record.lastActivityAt}`,
42
- `- Duration: ${record.durationMs} ms`,
43
- `- Location: ${location}`,
44
- `- Messages: ${formatCount(record.userMessages, "user message")} · ${formatCount(record.assistantMessages, "assistant message")} · ${formatCount(record.toolResults, "tool result")}`,
45
- `- Events: ${record.events}`,
46
- `- Turns: ${record.turns ?? "not reported"}`,
47
- "- Participants:",
48
- ...list(record.participants.map((participant) => `${participant.name} · ${participant.messages} message${participant.messages === 1 ? "" : "s"}`), "None.").split("\n").map((line) => ` ${line}`),
49
- "- Code changes:",
50
- ...list(record.codeChanges.map(formatRecordCodeChange), "None.").split("\n").map((line) => ` ${line}`),
51
- "",
52
- "## Summary",
53
- "",
54
- brief.summary,
55
- "",
56
- "## Intent",
57
- "",
58
- brief.intent,
59
- "",
60
- `## Outcome · ${brief.outcome.status}`,
61
- "",
62
- brief.outcome.text,
63
- "",
64
- "## Decisions",
65
- "",
66
- "### Stated",
67
- "",
68
- list(brief.decisions.filter((decision) => decision.kind === "stated").map((decision) => `${decision.text}${decision.by ? ` — ${decision.by}` : ""}`), "None."),
69
- "",
70
- "### Confirmed",
71
- "",
72
- list(brief.decisions.filter((decision) => decision.kind === "confirmed").map((decision) => `${decision.text}${decision.by ? ` — ${decision.by}` : ""}`), "None."),
73
- "",
74
- "### Assumed (not confirmed)",
75
- "",
76
- list(brief.decisions.filter((decision) => decision.kind === "assumed").map((decision) => `${decision.text}${decision.by ? ` — ${decision.by}` : ""}`), "None."),
77
- "",
78
- "## Facts",
79
- "",
80
- list(brief.facts, "None."),
81
- "",
82
- "## Links",
83
- "",
84
- list(links, "None."),
85
- "",
86
- "## Keywords",
87
- "",
88
- brief.keywords.join(", ") || "None.",
89
- "",
90
- "---",
91
- "",
92
- "### Evidence check",
93
- "",
94
- `- Conversation: \`${args.input.conversationId}\``,
95
- `- Through index: ${args.generation.throughIndex}`,
96
- `- Versions generated: ${args.versionCount}`,
97
- `- Model: \`${args.model}\``,
98
- `- Code changes: ${evidence.codeChangeCount}`,
99
- `- Resources: ${evidence.resourceCount}`,
100
- `- Model URLs: ${evidence.keptUrlCount} kept of ${evidence.citedUrlCount}`,
101
- `- Coerced decision kinds: ${evidence.coercedDecisionKinds}`,
102
- `- Dropped attributions: ${evidence.droppedAttributionCount}`,
103
- `- Dropped runtime-marker items: ${evidence.droppedRuntimeMarkerCount}`,
104
- `- Merged claim without evidence: ${evidence.mergedClaimWithoutEvidence ? "yes" : "no"}`,
105
- `- Cost: ${formatCost(args.totalCostUsd)}`,
106
- "- Dropped URLs:",
107
- ...dropped.map((url) => ` - ${url}`),
108
- ""
109
- ].join("\n");
110
- }
111
- // src/chat/briefs/snapshot.ts
112
- const conversationSnapshotSchema = z.object({
113
- schemaVersion: z.literal(1),
114
- pulledAt: z.string().datetime(),
115
- detail: conversationDetailReportSchema,
116
- eventPages: z.array(conversationEventPageSchema),
117
- codeChanges: z.array(briefCodeChangeSchema)
118
- }).strict();
119
- /** Create the self-contained wire snapshot used for local Brief replay. */
120
- function createConversationSnapshot(args) {
121
- return conversationSnapshotSchema.parse({
122
- schemaVersion: 1,
123
- pulledAt: args.pulledAt ?? (/* @__PURE__ */ new Date()).toISOString(),
124
- detail: args.detail,
125
- eventPages: args.eventPages,
126
- codeChanges: args.codeChanges ?? []
127
- });
128
- }
129
- function allEvents(snapshot) {
130
- const bySequence = /* @__PURE__ */ new Map();
131
- for (const event of [...snapshot.eventPages.flatMap((page) => page.events), ...snapshot.detail.events]) bySequence.set(event.seq, event);
132
- return [...bySequence.values()].sort((left, right) => left.seq - right.seq);
133
- }
134
- function assertAvailableHistory(snapshot) {
135
- if ([snapshot.detail.eventHistory, ...snapshot.eventPages.map((page) => page.eventHistory)].some((history) => history.status !== "available")) throw new Error("A Brief snapshot requires available event history");
136
- }
137
- function codeChangeAt(change, boundaryMs) {
138
- if (change.openedAt && Date.parse(change.openedAt) > boundaryMs) return;
139
- const mergedAt = change.mergedAt && Date.parse(change.mergedAt) <= boundaryMs ? change.mergedAt : void 0;
140
- const closedAt = change.closedAt && Date.parse(change.closedAt) <= boundaryMs ? change.closedAt : void 0;
141
- const { mergedAt: _mergedAt, closedAt: _closedAt, ...rest } = change;
142
- return {
143
- ...rest,
144
- state: mergedAt ? "merged" : closedAt ? "closed" : "open",
145
- ...mergedAt ? { mergedAt } : void 0,
146
- ...closedAt ? { closedAt } : void 0
147
- };
148
- }
149
- /**
150
- * Project a downloaded conversation snapshot into generator input. Evidence
151
- * is limited to what existed at the `throughIndex` event, so a replayed
152
- * earlier version cannot cite a later pull request or resource.
153
- */
154
- function briefInputFromSnapshot(snapshot, throughIndex) {
155
- assertAvailableHistory(snapshot);
156
- const detail = snapshot.detail;
157
- const boundary = allEvents(snapshot).filter((event) => event.seq <= throughIndex).at(-1);
158
- if (!boundary) throw new Error(`Snapshot has no event at or before index ${throughIndex}`);
159
- const boundaryMs = Date.parse(boundary.createdAt);
160
- const channelName = detail.channelName?.trim() || detail.channel?.trim();
161
- const hasLocation = Boolean(channelName || detail.locationId);
162
- return parseBriefInput({
163
- conversationId: detail.conversationId,
164
- ...detail.displayTitle.trim() ? { title: detail.displayTitle.trim() } : void 0,
165
- visibility: detail.visibility ?? "public",
166
- ...hasLocation ? { location: {
167
- provider: "slack",
168
- ...channelName ? { channelName } : void 0
169
- } } : void 0,
170
- entries: briefEntriesFromReportEvents(allEvents(snapshot)),
171
- codeChanges: snapshot.codeChanges.flatMap((change) => {
172
- const bounded = codeChangeAt(change, boundaryMs);
173
- return bounded ? [bounded] : [];
174
- }),
175
- resources: (detail.annotations ?? []).flatMap((annotation) => annotation.url !== null && Date.parse(annotation.createdAt) <= boundaryMs ? [{
176
- label: briefResourceLabel(annotation),
177
- url: annotation.url,
178
- ...annotation.status ? { status: annotation.status } : void 0
179
- }] : [])
180
- });
181
- }
182
- /** Return the last event index included in a conversation snapshot. */
183
- function throughIndexFromSnapshot(snapshot) {
184
- return allEvents(snapshot).at(-1)?.seq;
185
- }
186
- /** Return event indexes for turns that reached a successful terminal state. */
187
- function completedTurnIndexesFromSnapshot(snapshot) {
188
- return allEvents(snapshot).filter((event) => event.data.type === "turn_lifecycle" && (event.data.state === "succeeded" || event.data.state === "no_reply" || event.data.state === "blocked")).map((event) => event.seq);
189
- }
190
- // src/cli/briefs.ts
191
- /**
192
- * Local Brief snapshot and replay CLI.
193
- *
194
- * This module owns dashboard download pagination and local files. The Brief
195
- * module owns projection, generation, evidence checks, and rendering.
196
- */
197
- function optionValue(argv, index, option) {
198
- const value = argv[index + 1];
199
- if (!value || value.startsWith("--")) throw new Error(`${option} requires a value`);
200
- return value;
201
- }
202
- function parsePullOptions(argv) {
203
- const conversationIds = [];
204
- let baseUrl;
205
- let token = process.env["JUNIOR_API_TOKEN"]?.trim();
206
- let out;
207
- for (let index = 0; index < argv.length; index += 1) {
208
- const argument = argv[index];
209
- if (argument === "--base-url") {
210
- baseUrl = optionValue(argv, index, argument);
211
- index += 1;
212
- } else if (argument === "--token") {
213
- token = optionValue(argv, index, argument);
214
- index += 1;
215
- } else if (argument === "--out") {
216
- out = optionValue(argv, index, argument);
217
- index += 1;
218
- } else if (argument.startsWith("-")) throw new Error(`Unknown option: ${argument}`);
219
- else conversationIds.push(argument);
220
- }
221
- if (!baseUrl || !token || !out || conversationIds.length === 0) throw new Error(CLI_USAGE);
222
- return {
223
- baseUrl,
224
- conversationIds,
225
- out,
226
- token
227
- };
228
- }
229
- async function parseRunOptions(argv) {
230
- const snapshots = [];
231
- let model;
232
- let promptFile;
233
- let out = process.cwd();
234
- let turnByTurn = false;
235
- for (let index = 0; index < argv.length; index += 1) {
236
- const argument = argv[index];
237
- if (argument === "--model") {
238
- model = optionValue(argv, index, argument);
239
- index += 1;
240
- } else if (argument === "--prompt") {
241
- promptFile = optionValue(argv, index, argument);
242
- index += 1;
243
- } else if (argument === "--out") {
244
- out = optionValue(argv, index, argument);
245
- index += 1;
246
- } else if (argument === "--turn-by-turn") turnByTurn = true;
247
- else if (argument.startsWith("-")) throw new Error(`Unknown option: ${argument}`);
248
- else snapshots.push(argument);
249
- }
250
- if (snapshots.length === 0) throw new Error(CLI_USAGE);
251
- const bot = await configuredBot();
252
- return {
253
- assistantName: bot.userName,
254
- model: model ?? bot.fastModelId,
255
- out,
256
- promptFile,
257
- snapshots,
258
- turnByTurn
259
- };
260
- }
261
- /**
262
- * Read the production bot config only when a run needs it. `chat/config`
263
- * reads `DATABASE_URL` at import, and `briefs pull` must work with only a
264
- * token.
265
- */
266
- async function configuredBot() {
267
- const { botConfig } = await import("./config-BrXDQefC.js").then((n) => n.r);
268
- return botConfig;
269
- }
270
- function apiUrl(baseUrl, pathname) {
271
- const base = new URL(baseUrl);
272
- base.pathname = `${base.pathname.replace(/\/*$/, "")}/`;
273
- base.search = "";
274
- base.hash = "";
275
- return new URL(pathname.replace(/^\//, ""), base);
276
- }
277
- async function fetchJson(url, token) {
278
- const response = await fetch(url, { headers: {
279
- accept: "application/json",
280
- authorization: `Bearer ${token}`
281
- } });
282
- if (!response.ok) {
283
- const body = (await response.text()).trim().slice(0, 500);
284
- throw new Error(`Dashboard request failed (${response.status} ${response.statusText})${body ? `: ${body}` : ""}`);
285
- }
286
- return await response.json();
287
- }
288
- async function pullSnapshot(options, conversationId) {
289
- const detailUrl = apiUrl(options.baseUrl, `api/conversations/${encodeURIComponent(conversationId)}`);
290
- detailUrl.searchParams.set("limit", "1000");
291
- const detail = conversationDetailReportSchema.parse(await fetchJson(detailUrl, options.token));
292
- const eventPages = [];
293
- const seenCursors = /* @__PURE__ */ new Set();
294
- let cursor = detail.previousCursor;
295
- while (cursor) {
296
- if (seenCursors.has(cursor)) throw new Error(`Conversation ${conversationId} repeated an event cursor`);
297
- seenCursors.add(cursor);
298
- const eventsUrl = apiUrl(options.baseUrl, `api/conversations/${encodeURIComponent(conversationId)}/events`);
299
- eventsUrl.searchParams.set("before", cursor);
300
- eventsUrl.searchParams.set("limit", "1000");
301
- const page = conversationEventPageSchema.parse(await fetchJson(eventsUrl, options.token));
302
- eventPages.push(page);
303
- cursor = page.previousCursor;
304
- }
305
- return createConversationSnapshot({
306
- detail,
307
- eventPages
308
- });
309
- }
310
- function fileStem(conversationId) {
311
- const stem = conversationId.replaceAll(/[\\/\0]/g, "_");
312
- if (!stem || stem === "." || stem === "..") throw new Error("Conversation id cannot be used as a file name");
313
- return stem;
314
- }
315
- async function pullAll(options) {
316
- await mkdir(options.out, { recursive: true });
317
- for (const conversationId of options.conversationIds) {
318
- const snapshot = await pullSnapshot(options, conversationId);
319
- const output = path.join(options.out, `${fileStem(snapshot.detail.conversationId)}.snapshot.json`);
320
- await writeFile(output, `${JSON.stringify(snapshot, void 0, 2)}\n`);
321
- console.log(output);
322
- }
323
- }
324
- function generationIndexes(snapshot, turnByTurn, throughIndex) {
325
- if (!turnByTurn) return [throughIndex];
326
- const indexes = completedTurnIndexesFromSnapshot(snapshot);
327
- if (indexes.length === 0) throw new Error("Snapshot has no completed turns");
328
- return indexes;
329
- }
330
- async function runSnapshot(snapshotPath, options, prompt) {
331
- const snapshot = conversationSnapshotSchema.parse(JSON.parse(await readFile(snapshotPath, "utf8")));
332
- const finalThroughIndex = throughIndexFromSnapshot(snapshot);
333
- if (finalThroughIndex === void 0) throw new Error(`Snapshot ${snapshotPath} has no Conversation events`);
334
- const input = briefInputFromSnapshot(snapshot, finalThroughIndex);
335
- const versions = [];
336
- for (const throughIndex of generationIndexes(snapshot, options.turnByTurn, finalThroughIndex)) versions.push(await generateBrief({
337
- assistantName: options.assistantName,
338
- completeObject: (request) => completeObject({
339
- ...request,
340
- modelId: options.model,
341
- operation: "brief_update",
342
- cost: { owner: "caller" }
343
- }),
344
- input: briefInputFromSnapshot(snapshot, throughIndex),
345
- previous: versions.at(-1)?.brief,
346
- prompt,
347
- throughIndex
348
- }));
349
- const costs = versions.flatMap((version) => version.costUsd === void 0 ? [] : [version.costUsd]);
350
- const totalCostUsd = costs.length > 0 ? costs.reduce((sum, cost) => sum + cost, 0) : void 0;
351
- const stem = fileStem(input.conversationId);
352
- const jsonPath = path.join(options.out, `${stem}.brief.json`);
353
- const markdownPath = path.join(options.out, `${stem}.brief.md`);
354
- const report = {
355
- schemaVersion: 1,
356
- conversationId: input.conversationId,
357
- model: options.model,
358
- versions,
359
- ...totalCostUsd !== void 0 ? { totalCostUsd } : void 0
360
- };
361
- await Promise.all([writeFile(jsonPath, `${JSON.stringify(report, void 0, 2)}\n`), writeFile(markdownPath, renderBriefMarkdown({
362
- generation: versions.at(-1),
363
- input,
364
- model: options.model,
365
- totalCostUsd,
366
- versionCount: versions.length
367
- }))]);
368
- console.log(jsonPath);
369
- console.log(markdownPath);
370
- }
371
- async function runAll(options) {
372
- const prompt = options.promptFile ? await readFile(options.promptFile, "utf8") : BRIEF_PROMPT;
373
- if (!prompt.trim()) throw new Error("Brief prompt must not be empty");
374
- await mkdir(options.out, { recursive: true });
375
- for (const snapshot of options.snapshots) await runSnapshot(snapshot, options, prompt);
376
- }
377
- /** Run `junior briefs pull` or `junior briefs run`. */
378
- async function runBriefs(argv) {
379
- try {
380
- const [subcommand, ...rest] = argv;
381
- if (subcommand === "pull") {
382
- await pullAll(parsePullOptions(rest));
383
- return 0;
384
- }
385
- if (subcommand === "run") {
386
- await runAll(await parseRunOptions(rest));
387
- return 0;
388
- }
389
- throw new Error(CLI_USAGE);
390
- } catch (error) {
391
- console.error(error instanceof Error ? error.message : String(error));
392
- return 1;
393
- }
394
- }
395
- export { runBriefs };