charness 4.1.0 → 4.1.1

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 (160) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/DEVELOPMENT.md +1 -1
  3. package/SETUP.md +34 -8
  4. package/dist/adapters/claudeJsonStreamAdapter.d.ts +60 -5
  5. package/dist/adapters/claudeJsonStreamAdapter.d.ts.map +1 -1
  6. package/dist/adapters/claudeJsonStreamAdapter.js +128 -14
  7. package/dist/adapters/claudeJsonStreamAdapter.js.map +1 -1
  8. package/dist/bot.d.ts.map +1 -1
  9. package/dist/bot.js +164 -31
  10. package/dist/bot.js.map +1 -1
  11. package/dist/connectors/jira/answerSink.d.ts +8 -0
  12. package/dist/connectors/jira/answerSink.d.ts.map +1 -1
  13. package/dist/connectors/jira/answerSink.js +15 -0
  14. package/dist/connectors/jira/answerSink.js.map +1 -1
  15. package/dist/connectors/jira/config.d.ts +16 -0
  16. package/dist/connectors/jira/config.d.ts.map +1 -1
  17. package/dist/connectors/jira/config.js +21 -2
  18. package/dist/connectors/jira/config.js.map +1 -1
  19. package/dist/connectors/jira/connector.d.ts +10 -3
  20. package/dist/connectors/jira/connector.d.ts.map +1 -1
  21. package/dist/connectors/jira/connector.js +21 -3
  22. package/dist/connectors/jira/connector.js.map +1 -1
  23. package/dist/connectors/jira/inbound.d.ts +200 -18
  24. package/dist/connectors/jira/inbound.d.ts.map +1 -1
  25. package/dist/connectors/jira/inbound.js +814 -43
  26. package/dist/connectors/jira/inbound.js.map +1 -1
  27. package/dist/connectors/jira/prompt.d.ts +46 -0
  28. package/dist/connectors/jira/prompt.d.ts.map +1 -1
  29. package/dist/connectors/jira/prompt.js +123 -15
  30. package/dist/connectors/jira/prompt.js.map +1 -1
  31. package/dist/connectors/jira/trigger.d.ts +27 -4
  32. package/dist/connectors/jira/trigger.d.ts.map +1 -1
  33. package/dist/connectors/jira/trigger.js +35 -1
  34. package/dist/connectors/jira/trigger.js.map +1 -1
  35. package/dist/connectors/jira/triggerLog.d.ts +60 -5
  36. package/dist/connectors/jira/triggerLog.d.ts.map +1 -1
  37. package/dist/connectors/jira/triggerLog.js +116 -7
  38. package/dist/connectors/jira/triggerLog.js.map +1 -1
  39. package/dist/connectors/telegram/commands/runners.d.ts +28 -1
  40. package/dist/connectors/telegram/commands/runners.d.ts.map +1 -1
  41. package/dist/connectors/telegram/commands/runners.js +75 -40
  42. package/dist/connectors/telegram/commands/runners.js.map +1 -1
  43. package/dist/connectors/telegram/sendOutcome.d.ts +3 -1
  44. package/dist/connectors/telegram/sendOutcome.d.ts.map +1 -1
  45. package/dist/connectors/telegram/sendOutcome.js.map +1 -1
  46. package/dist/connectors/telegram/telegramFailureRetry.d.ts +8 -0
  47. package/dist/connectors/telegram/telegramFailureRetry.d.ts.map +1 -1
  48. package/dist/connectors/telegram/telegramFailureRetry.js +8 -0
  49. package/dist/connectors/telegram/telegramFailureRetry.js.map +1 -1
  50. package/dist/i18n/de.d.ts.map +1 -1
  51. package/dist/i18n/de.js +4 -0
  52. package/dist/i18n/de.js.map +1 -1
  53. package/dist/i18n/en.d.ts.map +1 -1
  54. package/dist/i18n/en.js +4 -0
  55. package/dist/i18n/en.js.map +1 -1
  56. package/dist/i18n/es.d.ts.map +1 -1
  57. package/dist/i18n/es.js +4 -0
  58. package/dist/i18n/es.js.map +1 -1
  59. package/dist/i18n/fr.d.ts.map +1 -1
  60. package/dist/i18n/fr.js +4 -0
  61. package/dist/i18n/fr.js.map +1 -1
  62. package/dist/i18n/hi.d.ts.map +1 -1
  63. package/dist/i18n/hi.js +4 -0
  64. package/dist/i18n/hi.js.map +1 -1
  65. package/dist/i18n/ja.d.ts.map +1 -1
  66. package/dist/i18n/ja.js +4 -0
  67. package/dist/i18n/ja.js.map +1 -1
  68. package/dist/i18n/ka.d.ts.map +1 -1
  69. package/dist/i18n/ka.js +4 -0
  70. package/dist/i18n/ka.js.map +1 -1
  71. package/dist/i18n/pt.d.ts.map +1 -1
  72. package/dist/i18n/pt.js +4 -0
  73. package/dist/i18n/pt.js.map +1 -1
  74. package/dist/i18n/ru.d.ts.map +1 -1
  75. package/dist/i18n/ru.js +4 -0
  76. package/dist/i18n/ru.js.map +1 -1
  77. package/dist/i18n/uk.d.ts.map +1 -1
  78. package/dist/i18n/uk.js +4 -0
  79. package/dist/i18n/uk.js.map +1 -1
  80. package/dist/i18n/uz.d.ts.map +1 -1
  81. package/dist/i18n/uz.js +4 -0
  82. package/dist/i18n/uz.js.map +1 -1
  83. package/dist/i18n/zh.d.ts.map +1 -1
  84. package/dist/i18n/zh.js +4 -0
  85. package/dist/i18n/zh.js.map +1 -1
  86. package/dist/i18n.d.ts.map +1 -1
  87. package/dist/i18n.js +2 -1
  88. package/dist/i18n.js.map +1 -1
  89. package/dist/requests/requestHeader.d.ts.map +1 -1
  90. package/dist/requests/requestHeader.js +1 -0
  91. package/dist/requests/requestHeader.js.map +1 -1
  92. package/dist/requests/types.d.ts +4 -1
  93. package/dist/requests/types.d.ts.map +1 -1
  94. package/dist/requests/wakeUpEngine.d.ts +31 -1
  95. package/dist/requests/wakeUpEngine.d.ts.map +1 -1
  96. package/dist/requests/wakeUpEngine.js +94 -2
  97. package/dist/requests/wakeUpEngine.js.map +1 -1
  98. package/dist/requests/wakeUpRules.d.ts +7 -0
  99. package/dist/requests/wakeUpRules.d.ts.map +1 -1
  100. package/dist/requests/wakeUpRules.js +14 -0
  101. package/dist/requests/wakeUpRules.js.map +1 -1
  102. package/dist/scheduler/engine.d.ts +17 -4
  103. package/dist/scheduler/engine.d.ts.map +1 -1
  104. package/dist/scheduler/engine.js +55 -10
  105. package/dist/scheduler/engine.js.map +1 -1
  106. package/dist/scheduler/mcpBoot.d.ts +6 -2
  107. package/dist/scheduler/mcpBoot.d.ts.map +1 -1
  108. package/dist/scheduler/mcpBoot.js +7 -1
  109. package/dist/scheduler/mcpBoot.js.map +1 -1
  110. package/dist/scheduler/mcpSurface.d.ts.map +1 -1
  111. package/dist/scheduler/mcpSurface.js +18 -9
  112. package/dist/scheduler/mcpSurface.js.map +1 -1
  113. package/dist/sendErrorClassifier.d.ts +6 -0
  114. package/dist/sendErrorClassifier.d.ts.map +1 -1
  115. package/dist/sendErrorClassifier.js +9 -0
  116. package/dist/sendErrorClassifier.js.map +1 -1
  117. package/dist/startupPromptBuffer.d.ts +8 -8
  118. package/dist/startupPromptBuffer.d.ts.map +1 -1
  119. package/dist/startupPromptBuffer.js +7 -5
  120. package/dist/startupPromptBuffer.js.map +1 -1
  121. package/dist/testTimings.d.ts +3 -2
  122. package/dist/testTimings.d.ts.map +1 -1
  123. package/dist/testTimings.js +3 -1
  124. package/dist/testTimings.js.map +1 -1
  125. package/dist/threadRouting.d.ts +23 -0
  126. package/dist/threadRouting.d.ts.map +1 -1
  127. package/dist/threadRouting.js +28 -0
  128. package/dist/threadRouting.js.map +1 -1
  129. package/dist/trackers/taskAgentSlots.d.ts +42 -3
  130. package/dist/trackers/taskAgentSlots.d.ts.map +1 -1
  131. package/dist/trackers/taskAgentSlots.js +31 -11
  132. package/dist/trackers/taskAgentSlots.js.map +1 -1
  133. package/dist/types.d.ts +7 -0
  134. package/dist/types.d.ts.map +1 -1
  135. package/dist/utils/fileSendPlan.d.ts +30 -8
  136. package/dist/utils/fileSendPlan.d.ts.map +1 -1
  137. package/dist/utils/fileSendPlan.js +37 -12
  138. package/dist/utils/fileSendPlan.js.map +1 -1
  139. package/dist/utils/fileSendService.d.ts +1 -1
  140. package/dist/utils/fileSendService.d.ts.map +1 -1
  141. package/dist/utils/fileSendService.js +9 -1
  142. package/dist/utils/fileSendService.js.map +1 -1
  143. package/dist/utils/imageDimensions.d.ts +32 -0
  144. package/dist/utils/imageDimensions.d.ts.map +1 -0
  145. package/dist/utils/imageDimensions.js +181 -0
  146. package/dist/utils/imageDimensions.js.map +1 -0
  147. package/dist/utils/jsonStreamHost.d.ts +35 -9
  148. package/dist/utils/jsonStreamHost.d.ts.map +1 -1
  149. package/dist/utils/jsonStreamHost.js +59 -16
  150. package/dist/utils/jsonStreamHost.js.map +1 -1
  151. package/dist/utils/lostWork.d.ts +8 -2
  152. package/dist/utils/lostWork.d.ts.map +1 -1
  153. package/dist/utils/lostWork.js +9 -5
  154. package/dist/utils/lostWork.js.map +1 -1
  155. package/dist/utils/promptDelivery.d.ts +11 -2
  156. package/dist/utils/promptDelivery.d.ts.map +1 -1
  157. package/dist/utils/promptDelivery.js +3 -3
  158. package/dist/utils/promptDelivery.js.map +1 -1
  159. package/npm-shrinkwrap.json +2 -2
  160. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.JiraInbound = exports.jiraSearchFields = exports.jiraMentionScanCommentCount = exports.jiraMentionWindowMinMs = exports.jiraRetryBackoffCapMs = exports.jiraSearchPageSize = void 0;
3
+ exports.JiraInbound = exports.jiraSearchFields = exports.jiraIssueUpdatesPer24hMax = exports.jiraMentionScanCommentCount = exports.jiraMentionWindowMinMs = exports.jiraRetryBackoffCapMs = exports.jiraSearchPageSize = void 0;
4
4
  exports.getJiraRetryDelayMs = getJiraRetryDelayMs;
5
5
  exports.getJiraMentionWindowMs = getJiraMentionWindowMs;
6
6
  exports.buildJiraTriggerJql = buildJiraTriggerJql;
@@ -12,6 +12,7 @@ const trigger_1 = require("./trigger");
12
12
  const issueBlocks_1 = require("./issueBlocks");
13
13
  const issueContext_1 = require("./issueContext");
14
14
  const prompt_1 = require("./prompt");
15
+ const taskAgentSlots_1 = require("../../trackers/taskAgentSlots");
15
16
  const issueDelta_1 = require("./issueDelta");
16
17
  const storedPromptRefresh_1 = require("../../requests/storedPromptRefresh");
17
18
  const promptSpill_1 = require("./promptSpill");
@@ -37,16 +38,34 @@ const trustedGroup_1 = require("./trustedGroup");
37
38
  * first in the list and a slot is free (`trackers/taskAgentSlots.ts`; a slot freeing wakes the poll at once, `pollSoon`).
38
39
  * A Jira event never cancels an armed usage-limit wait — the ledger's create hook tells the new request about it (core S5).
39
40
  *
40
- * With mention wakes on (a trusted group is set), the same poll also finds a comment that @-mentions the AI
41
- * account — on an issue that is NOT handed to it — and opens a request that answers only:
41
+ * With comment wakes on (a trusted group is set), a trusted person's comment on an issue HANDED to the AI account —
42
+ * assigned to it in a trigger status, its hand-over seen — reaches its agent; a mention there is a comment like any other:
43
+ *
44
+ * `updated` moved since this process last read it → its newest comments: a person's (not the AI account's, not an app's
45
+ * or an automation's — those ride the next prompt), newer than every comment a recorded prompt of the issue was built
46
+ * from (the trigger log's `newestCommentId`: no window, so a comment made while the bot was down is not lost), whose
47
+ * `comment:<id>` (and `mention:<id>`) is not seen →
48
+ * author and last editor trusted (else `untrusted`, silent) →
49
+ * a hand-over request of the conversation open → an ISSUE UPDATE posted for it: no request is opened (a new one
50
+ * would supersede the hand-over, or hand the issue to the commenter on its first final answer)
51
+ * none open → run budget → a free task-agent slot → a request of its own (`commented`, the commenter its requester)
52
+ * → RECORD every comment once its post settled (an update that failed is decided again, after a backoff)
53
+ *
54
+ * With mention wakes on, the same poll also finds a comment that @-mentions the AI account — on an issue that is NOT
55
+ * handed to it (with comment wakes off: on any issue) — and opens a request:
42
56
  *
43
57
  * issue returned and its `updated` moved since this process last read it → its newest comments, those
44
58
  * created or edited within the mention window that mention the AI account (the ADF mention node's id) and
45
59
  * whose trigger id `mention:<commentId>` is not seen →
46
- * author and last editor trusted → not covered by an open hand-over request of the same person
47
- * → run budget → open a request (no hand-back; the answer sink knows by the origin kind)
60
+ * author and last editor trusted → by the requester of an open hand-over request: an issue update for that
61
+ * request (with comment wakes off: `covered`, nothing posted) → run budget → with `mentionMode: "act"` a free
62
+ * task-agent slot (an acting mention may start a build) → open a request (no hand-back; the answer sink knows by
63
+ * the origin kind)
48
64
  *
49
- * One decision per comment, recorded in the same trigger log: an edit of a decided comment wakes nothing.
65
+ * One decision per comment, recorded in the same trigger log: an edit of a decided comment wakes nothing. An acting
66
+ * mention that waits for a slot keeps its place across polls and restarts: its comment is decided again outside the
67
+ * window, and its issue is read by its key once the search no longer returns it. So does a mention held back from its
68
+ * issue update (the cap on updates paused it, or its post failed: `held-mention:` in the trigger log) until it is delivered.
50
69
  */
51
70
  exports.jiraSearchPageSize = 50;
52
71
  /** The longest wait between two attempts while Jira keeps failing (R22). */
@@ -56,6 +75,13 @@ exports.jiraMentionWindowMinMs = 5 * 60 * 1000;
56
75
  /** How many of an issue's newest comments a mention scan reads — more than a window of activity holds. */
57
76
  exports.jiraMentionScanCommentCount = 100;
58
77
  const msPerMinute = 60 * 1000;
78
+ const msPerDay = 24 * 60 * msPerMinute;
79
+ /**
80
+ * The issue updates one issue may get in a rolling 24 h. A person's comment is one; an account that comments as the agent's
81
+ * own tooling would loop (each comment the next poll's update), and the cap ends that: past it, comments wait until the
82
+ * oldest update of the window leaves it, with one log line per pause.
83
+ */
84
+ exports.jiraIssueUpdatesPer24hMax = 20;
59
85
  /** Separates an issue key from a trigger id in the key a mention decision has in the poll's result and log line. */
60
86
  const mentionDecisionKeySeparator = '#';
61
87
  /**
@@ -78,10 +104,12 @@ function getJiraMentionWindowMs(pollIntervalMs) {
78
104
  /** Decisions that change nothing, left out of the poll's log line. */
79
105
  const quietDecisions = new Set(['notMatching', 'posting', 'seen', 'waiting']);
80
106
  /**
81
- * Decisions that end an issue's wait for a slot: its hand-over is gone, was refused or was handled without one. `notAllowed` is not
107
+ * Decisions that end a hand-over's wait for a slot: its hand-over is gone, was refused or was handled without one. `notAllowed` is not
82
108
  * one: that issue never waited, and its key may not even be an issue key (`makeJiraKey` would throw).
83
109
  */
84
110
  const waitEndingDecisions = new Set(['notMatching', 'seen', 'selfAuthored', 'parked', 'untrusted']);
111
+ /** The decisions of a mention or a comment that leave it to the next poll: it is not decided yet. */
112
+ const undecidedDecisions = new Set(['queued', 'waiting', 'failed']);
85
113
  /**
86
114
  * @description The poll's JQL (D13): the allowlist, assigned to the AI account, in a trigger status — and, with
87
115
  * `mentionWindowMs`, the issues whose comments mention the AI account and that changed within that window. The
@@ -98,6 +126,38 @@ function buildJiraTriggerJql(projects, mentionWindowMs) {
98
126
  const windowMinutes = Math.ceil(mentionWindowMs / msPerMinute);
99
127
  return `project in (${projectKeys}) AND ((${assignedBranch}) OR (comment ~ currentUser() AND updated >= -${windowMinutes}m)) ORDER BY created ASC`;
100
128
  }
129
+ /** What {@link getNewestCommentId} says of an issue with no comment yet: below every real id, so any later comment is newer. */
130
+ const noCommentId = '0';
131
+ /** The newest of `comments` by id — a prompt built from them carried every comment up to it — or {@link noCommentId} for none. */
132
+ function getNewestCommentId(comments) {
133
+ return comments.reduce((newest, comment) => ((0, trigger_1.compareJiraCommentIds)(comment.id, newest) > 0 ? comment.id : newest), noCommentId);
134
+ }
135
+ /** A changelog item that changed an issue's parent (a sub-task's, a team-managed or an epic's child's). */
136
+ function checkIsParentChangeItem(item) {
137
+ return ['parent', 'issueparentassociation', 'epic link'].includes((0, trigger_1.getItemField)(item).toLowerCase());
138
+ }
139
+ /**
140
+ * The issues the AI account itself tied `context`'s issue to, as its whole changelog shows them (read with the context, no
141
+ * further request): the far end of every issue link the AI account made, and its parent when the AI account set it — at
142
+ * the creation (no entry: it created the issue and no one changed the parent since) or by the parent's last change.
143
+ */
144
+ function listIssueKeysTiedByAi(context, aiAccountId) {
145
+ const keys = new Set();
146
+ for (const history of context.changelog) {
147
+ if (history.author?.accountId !== aiAccountId)
148
+ continue;
149
+ for (const item of history.items) {
150
+ if ((item.field.toLowerCase() === 'link' || item.fieldId === 'issuelinks') && item.to)
151
+ keys.add(item.to);
152
+ }
153
+ }
154
+ const { parent, creator } = context.issue.fields;
155
+ const lastParentChange = context.changelog.filter((history) => history.items.some(checkIsParentChangeItem)).at(-1);
156
+ const parentSetBy = lastParentChange ? lastParentChange.author : creator;
157
+ if (parent && parentSetBy?.accountId === aiAccountId)
158
+ keys.add(parent.key);
159
+ return keys;
160
+ }
101
161
  /** The first line of a stored request prompt names its request: `[Request req_… · from: …]`. */
102
162
  const storedPromptRequestIdPattern = /^\[Request (req_[A-Za-z0-9_-]+) · /;
103
163
  /** How many mention prompts can be rebuilt at delivery at once (each keeps its issue in memory). */
@@ -115,8 +175,19 @@ class JiraInbound {
115
175
  failureCount = 0;
116
176
  /** Issues whose last request's post has not settled yet. */
117
177
  postingIssueKeys = new Set();
118
- /** Per issue, its `updated` as of the last mention scan that decided every comment — in memory only: a restart scans once more. */
178
+ /** Per issue, its `updated` as of the last comment or mention scan that decided every comment — in memory only: a restart scans once more. */
119
179
  lastUpdatedByIssue = new Map();
180
+ /** Per issue, the issue updates in a row that did not reach the session, and when the next may be tried — in memory only. */
181
+ updateRetries = new Map();
182
+ /** Issues whose seen hand-over the AI account made itself (it took the issue up) — in memory, refreshed by every poll. */
183
+ selfAssignedIssueKeys = new Set();
184
+ /**
185
+ * The issues handed to the AI account (their hand-over seen) at the last poll, each with the request its last update went
186
+ * to or would have gone to — in memory only. One that leaves the handed state gets one last comment scan.
187
+ */
188
+ handedIssues = new Map();
189
+ /** The issues the poll under way found handed to the AI account (whatever their decision). */
190
+ handedThisPoll = new Set();
120
191
  /**
121
192
  * The mention requests whose stored prompt can be rebuilt with the hand-over requests that are open NOW, by request id —
122
193
  * in memory only (a restart leaves the stored text, whose wording holds on its own) and bounded: an entry of a request
@@ -199,9 +270,11 @@ class JiraInbound {
199
270
  */
200
271
  async pollOnce() {
201
272
  const decisions = new Map();
273
+ this.handedThisPoll.clear();
202
274
  const mentionWindowMs = this.getMentionWindowMs();
203
275
  const jql = buildJiraTriggerJql(this.deps.projects, mentionWindowMs);
204
276
  const returnedIssueKeys = new Set();
277
+ const returnedIssues = new Map();
205
278
  let nextPageToken;
206
279
  do {
207
280
  // Before every page, not only the first: deciding a long page takes time, and the list must not age out under it.
@@ -215,15 +288,38 @@ class JiraInbound {
215
288
  });
216
289
  for (const issue of page.issues) {
217
290
  returnedIssueKeys.add(issue.key);
218
- const decision = await this.getDecisionSafely(issue);
219
- decisions.set(issue.key, decision);
220
- if (mentionWindowMs !== null && decision !== 'notAllowed') {
221
- for (const [decisionKey, mentionDecision] of await this.getMentionDecisionsSafely(issue))
222
- decisions.set(decisionKey, mentionDecision);
223
- }
291
+ returnedIssues.set(issue.key, issue);
292
+ for (const [decisionKey, decision] of await this.decideIssue(issue, mentionWindowMs))
293
+ decisions.set(decisionKey, decision);
224
294
  }
225
295
  nextPageToken = page.isLast ? undefined : (page.nextPageToken ?? undefined);
226
296
  } while (nextPageToken);
297
+ for (const [decisionKey, decision] of await this.scanIssuesThatLeftHanded(returnedIssues))
298
+ decisions.set(decisionKey, decision);
299
+ // An acting mention that waits for a slot may be older than the search's window by now: its issue is read by its key.
300
+ for (const { issueKey } of this.listWaitingMentions()) {
301
+ if (returnedIssueKeys.has(issueKey))
302
+ continue;
303
+ // Kept in the list even when the read fails: a Jira hiccup must not cost the place.
304
+ returnedIssueKeys.add(issueKey);
305
+ const issue = await this.readWaitingIssue(issueKey);
306
+ if (issue)
307
+ for (const [decisionKey, decision] of await this.decideIssue(issue, mentionWindowMs))
308
+ decisions.set(decisionKey, decision);
309
+ }
310
+ // So may a mention held back from its issue update (the cap on updates, a post that failed) by the time it may go.
311
+ for (const issueKey of mentionWindowMs === null ? [] : this.deps.triggerLog.listHeldMentionIssueKeys(this.deps.now())) {
312
+ if (returnedIssueKeys.has(issueKey))
313
+ continue;
314
+ returnedIssueKeys.add(issueKey);
315
+ // Not read while its pause or its post's backoff lasts: the scan would skip it anyway.
316
+ if (this.checkIsUpdateRetryPending(issueKey))
317
+ continue;
318
+ const issue = await this.readHeldMentionIssue(issueKey);
319
+ if (issue)
320
+ for (const [decisionKey, decision] of await this.decideIssue(issue, mentionWindowMs))
321
+ decisions.set(decisionKey, decision);
322
+ }
227
323
  // An issue that left the results is read from scratch if it comes back; the seen-log keeps that from waking twice.
228
324
  for (const issueKey of this.lastUpdatedByIssue.keys()) {
229
325
  if (!returnedIssueKeys.has(issueKey))
@@ -245,6 +341,207 @@ class JiraInbound {
245
341
  getMentionWindowMs() {
246
342
  return this.deps.isMentionWakeOn && this.deps.trust !== null ? getJiraMentionWindowMs(this.deps.pollIntervalMs) : null;
247
343
  }
344
+ /** Comment wakes are on and can judge someone (a trusted group read). */
345
+ checkIsCommentWakeOn() {
346
+ return this.deps.isCommentWakeOn && this.deps.trust !== null;
347
+ }
348
+ /** Handed to the AI account: assigned to it, in one of its project's trigger statuses. */
349
+ checkIsHanded(issue, project) {
350
+ const statusId = issue.fields.status?.id;
351
+ return issue.fields.assignee?.accountId === this.deps.aiAccountId && statusId !== undefined && project.triggerStatusIds.has(statusId);
352
+ }
353
+ /**
354
+ * Every decision one returned issue gets in a poll: the hand-over's, then — with comment wakes on and the issue handed
355
+ * to the AI, once its hand-over is seen — its new comments', else — with mention wakes on — its mentions'.
356
+ */
357
+ async decideIssue(issue, mentionWindowMs) {
358
+ const decisions = new Map();
359
+ const decision = await this.getDecisionSafely(issue);
360
+ decisions.set(issue.key, decision);
361
+ const project = this.getAllowlistedProject(issue);
362
+ if (decision === 'notAllowed' || !project)
363
+ return decisions;
364
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
365
+ if (this.checkIsCommentWakeOn() && this.checkIsHanded(issue, project)) {
366
+ this.handedThisPoll.add(issue.key);
367
+ // A mention on a handed issue is a comment like any other: a mention still waiting for a slot gives its place up.
368
+ this.deps.slots.dropWaiting(key, (triggerId) => triggerId.startsWith(trigger_1.mentionTriggerIdPrefix));
369
+ if (decision === 'seen') {
370
+ for (const [decisionKey, commentDecision] of await this.getCommentDecisionsSafely(issue, project))
371
+ decisions.set(decisionKey, commentDecision);
372
+ this.noteHanded(key);
373
+ }
374
+ return decisions;
375
+ }
376
+ if (mentionWindowMs !== null) {
377
+ for (const [decisionKey, mentionDecision] of await this.getMentionDecisionsSafely(issue))
378
+ decisions.set(decisionKey, mentionDecision);
379
+ }
380
+ else {
381
+ // Mention wakes went off (a restart with another jira.json): a mention that waited for a slot can never start.
382
+ this.deps.slots.dropWaiting(key, (triggerId) => triggerId.startsWith(trigger_1.mentionTriggerIdPrefix));
383
+ }
384
+ return decisions;
385
+ }
386
+ /** A handed issue whose hand-over is seen: remembered with the request an update would go to now (kept when none is open). */
387
+ noteHanded(key) {
388
+ const targets = this.listUpdateTargetRequests(key);
389
+ const newest = targets[targets.length - 1];
390
+ const target = newest
391
+ ? { requestId: newest.id, requesterAccountId: (0, requestGroup_1.getRequestRequester)(newest.origin), isMention: newest.origin.kind === 'trackerMention' }
392
+ : (this.handedIssues.get(key.thread) ?? null);
393
+ this.handedIssues.set(key.thread, target);
394
+ }
395
+ /**
396
+ * @description One last comment scan of each issue that was handed to the AI account at an earlier poll and is not now
397
+ * (handed back, unassigned, moved on): a comment written while it was handed — before the change that ended that —
398
+ * which the agent never got (its final answer came first) is delivered as the "finished" update of the request it was
399
+ * working on, or to a request still open — on an issue the AI account took up in another issue's run, to that run's
400
+ * request when no request of its own is known. An issue the search no longer returns is read by its key. Kept for the next
401
+ * poll while a post of it is in flight, its read fails, or an update of it is still to land.
402
+ */
403
+ async scanIssuesThatLeftHanded(returnedIssues) {
404
+ const decisions = new Map();
405
+ if (!this.checkIsCommentWakeOn()) {
406
+ this.handedIssues.clear();
407
+ return decisions;
408
+ }
409
+ for (const [issueKey, lastTarget] of [...this.handedIssues]) {
410
+ if (this.handedThisPoll.has(issueKey) || this.postingIssueKeys.has(issueKey) || this.checkIsUpdateRetryPending(issueKey))
411
+ continue;
412
+ const issue = returnedIssues.get(issueKey) ?? await this.readIssueThatLeft(issueKey);
413
+ if (issue === null)
414
+ continue;
415
+ const project = issue === 'gone' ? undefined : this.getAllowlistedProject(issue);
416
+ if (issue === 'gone' || !project) {
417
+ this.handedIssues.delete(issueKey);
418
+ continue;
419
+ }
420
+ if (this.checkIsHanded(issue, project))
421
+ continue;
422
+ const scanned = await this.runOrWarn(issueKey, 'last comment scan: ', () => this.getLastCommentDecisions(issue, project, lastTarget), null);
423
+ if (scanned === null)
424
+ continue;
425
+ for (const [decisionKey, decision] of scanned.decisions)
426
+ decisions.set(decisionKey, decision);
427
+ if (!scanned.isPosting)
428
+ this.handedIssues.delete(issueKey);
429
+ }
430
+ return decisions;
431
+ }
432
+ /** An issue that left the handed state, read by its key; `'gone'` when Jira no longer has it, `null` when the read failed. */
433
+ async readIssueThatLeft(issueKey) {
434
+ try {
435
+ return await this.deps.client.getIssue(issueKey, exports.jiraSearchFields);
436
+ }
437
+ catch (error) {
438
+ if (error instanceof client_1.JiraAuthError)
439
+ throw error;
440
+ if (error instanceof client_1.JiraHttpError && error.status === 404)
441
+ return 'gone';
442
+ console.warn(`[jira] ${issueKey}: the issue that left the AI account could not be read for its last comment scan: ${error instanceof Error ? error.message : String(error)}`);
443
+ return null;
444
+ }
445
+ }
446
+ /** When the issue stopped being handed: the newest changelog entry that assigned it away from the AI account or moved it out of a trigger status; `null` when none is found. */
447
+ async findLeftHandedAt(issue, project) {
448
+ const { aiAccountId } = this.deps;
449
+ for await (const page of this.getChangelogNewestPagesFirst(issue)) {
450
+ const newestFirst = [...page].sort((left, right) => Date.parse(right.created) - Date.parse(left.created));
451
+ const left = newestFirst.find((history) => history.items.some((item) => {
452
+ const field = (0, trigger_1.getItemField)(item);
453
+ return (field === 'assignee' && item.to !== aiAccountId) || (field === 'status' && (item.to === null || item.to === undefined || !project.triggerStatusIds.has(item.to)));
454
+ }));
455
+ if (left)
456
+ return Date.parse(left.created);
457
+ }
458
+ return null;
459
+ }
460
+ /** The last comment scan of an issue that left the handed state (see {@link scanIssuesThatLeftHanded}). */
461
+ async getLastCommentDecisions(issue, project, lastTarget) {
462
+ const { deps } = this;
463
+ const decisions = new Map();
464
+ const { trust } = deps;
465
+ if (!trust)
466
+ return { decisions, isPosting: false };
467
+ const leftAt = (await this.findLeftHandedAt(issue, project)) ?? deps.now();
468
+ const comments = await deps.client.getRecentComments(issue.key, exports.jiraMentionScanCommentCount);
469
+ const at = deps.now();
470
+ const written = this.listNewComments(issue.key, comments).filter((comment) => Date.parse(comment.created) <= leftAt);
471
+ const { counted } = this.partitionTrustedComments(issue.key, written, trust, at, decisions);
472
+ if (counted.length === 0)
473
+ return { decisions, isPosting: false };
474
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
475
+ const newest = counted[counted.length - 1];
476
+ let decision;
477
+ if (this.listUpdateTargetRequests(key).length > 0 || lastTarget) {
478
+ decision = await this.postIssueUpdate(issue, project, counted, trigger_1.commentTriggerIdPrefix, at, lastTarget);
479
+ }
480
+ else {
481
+ // An issue the AI account took up in another issue's run: its comments go to that run, as at every poll before.
482
+ const linked = this.selfAssignedIssueKeys.has(issue.key) ? await this.findLinkedWorkingRequest(issue, project) : null;
483
+ if (!linked) {
484
+ console.log(`[jira] ${issue.key}: comments ${counted.map((comment) => comment.id).join(', ')} came while it was handed to the AI, but no request of it is known any more to bring them to`);
485
+ return { decisions, isPosting: false };
486
+ }
487
+ decision = await this.postLinkedIssueUpdate(issue, counted, at, linked);
488
+ }
489
+ decisions.set(`${issue.key}${mentionDecisionKeySeparator}${trigger_1.commentTriggerIdPrefix}${newest.id}`, decision);
490
+ // Posted (it may still fail and be retried), or waiting out the cap on updates: either way the issue is scanned again.
491
+ return { decisions, isPosting: decision === 'update' || decision === 'waiting' };
492
+ }
493
+ /** The acting mentions that wait for a task-agent slot, oldest first: each issue's key and its `mention:<id>` trigger. */
494
+ listWaitingMentions() {
495
+ return this.deps.slots.listWaiting('jira')
496
+ .filter((entry) => entry.triggerId.startsWith(trigger_1.mentionTriggerIdPrefix))
497
+ .map((entry) => ({ issueKey: entry.key.thread, triggerId: entry.triggerId }));
498
+ }
499
+ /** The trigger `key`'s conversation waits for a slot with, when it starts with `prefix`; else `null`. */
500
+ getWaitingTriggerId(key, prefix) {
501
+ return this.deps.slots.listWaiting('jira').find((entry) => entry.key.thread === key.thread && entry.triggerId.startsWith(prefix))?.triggerId ?? null;
502
+ }
503
+ /**
504
+ * The issue of a waiting acting mention, read by its key with the search's fields; `null` when it could not be read. An
505
+ * issue Jira no longer has (deleted, or moved out of reach) gives its place up.
506
+ */
507
+ async readWaitingIssue(issueKey) {
508
+ try {
509
+ return await this.deps.client.getIssue(issueKey, exports.jiraSearchFields);
510
+ }
511
+ catch (error) {
512
+ if (error instanceof client_1.JiraAuthError)
513
+ throw error;
514
+ if (error instanceof client_1.JiraHttpError && error.status === 404) {
515
+ console.log(`[jira] ${issueKey}: the issue of a mention waiting for a slot is gone; its place is dropped`);
516
+ this.deps.slots.dropWaiting((0, sessionKeyCodec_1.makeJiraKey)(issueKey), (triggerId) => triggerId.startsWith(trigger_1.mentionTriggerIdPrefix));
517
+ return null;
518
+ }
519
+ console.warn(`[jira] ${issueKey}: the issue of a mention waiting for a slot could not be read: ${error instanceof Error ? error.message : String(error)}`);
520
+ return null;
521
+ }
522
+ }
523
+ /**
524
+ * The issue of a mention held back from its issue update, read by its key with the search's fields; `null` when it could
525
+ * not be read. An issue Jira no longer has (deleted, or moved out of reach) is no longer kept for its held mentions.
526
+ */
527
+ async readHeldMentionIssue(issueKey) {
528
+ const { deps } = this;
529
+ try {
530
+ return await deps.client.getIssue(issueKey, exports.jiraSearchFields);
531
+ }
532
+ catch (error) {
533
+ if (error instanceof client_1.JiraAuthError)
534
+ throw error;
535
+ if (error instanceof client_1.JiraHttpError && error.status === 404) {
536
+ console.log(`[jira] ${issueKey}: the issue of a mention held back from its update is gone; it is not kept any more`);
537
+ for (const commentId of deps.triggerLog.listHeldMentionIds(issueKey, deps.now()))
538
+ deps.triggerLog.forgetHeldMention(issueKey, commentId);
539
+ return null;
540
+ }
541
+ console.warn(`[jira] ${issueKey}: the issue of a mention held back from its update could not be read: ${error instanceof Error ? error.message : String(error)}`);
542
+ return null;
543
+ }
544
+ }
248
545
  /**
249
546
  * Runs `run`: a refused token propagates (it stops polling); any other failure is one warning naming the issue and
250
547
  * `what` failed, and the answer is `fallback` — the next poll tries again.
@@ -262,8 +559,11 @@ class JiraInbound {
262
559
  }
263
560
  async getDecisionSafely(issue) {
264
561
  const decision = await this.runOrWarn(issue.key, '', () => this.getDecision(issue), 'failed');
265
- if (waitEndingDecisions.has(decision))
266
- this.deps.slots.dropWaiting((0, sessionKeyCodec_1.makeJiraKey)(issue.key));
562
+ // A hand-over's place: its own decision ends it. A comment's request waits only while the issue is handed; a mention's
563
+ // place is its own scan's to end.
564
+ if (waitEndingDecisions.has(decision)) {
565
+ this.deps.slots.dropWaiting((0, sessionKeyCodec_1.makeJiraKey)(issue.key), (triggerId) => (0, trigger_1.checkIsHandOverTriggerId)(triggerId) || (decision === 'notMatching' && triggerId.startsWith(trigger_1.commentTriggerIdPrefix)));
566
+ }
267
567
  return decision;
268
568
  }
269
569
  async getDecision(issue) {
@@ -279,8 +579,15 @@ class JiraInbound {
279
579
  if (this.postingIssueKeys.has(issue.key))
280
580
  return 'posting';
281
581
  const found = await this.findTrigger(issue, project);
282
- if (found === 'seen')
582
+ if ('seen' in found) {
583
+ // The AI account handed the issue to itself (an acting mention's "take up the work"): its comments go to the open
584
+ // request that did so, never into a request of their own.
585
+ if (found.seen.author?.accountId === deps.aiAccountId)
586
+ this.selfAssignedIssueKeys.add(issue.key);
587
+ else
588
+ this.selfAssignedIssueKeys.delete(issue.key);
283
589
  return 'seen';
590
+ }
284
591
  const { trigger, requester } = found;
285
592
  const at = deps.now();
286
593
  if (trigger.author?.accountId === deps.aiAccountId) {
@@ -332,7 +639,9 @@ class JiraInbound {
332
639
  /**
333
640
  * @description The comments of `issue` that mention the AI account and were not decided yet, each decided once
334
641
  * (oldest first). Skipped altogether while the issue's `updated` is what the last complete scan saw, and while
335
- * a request of the issue is being posted (the next poll takes the rest: one request is posted at a time).
642
+ * a request of the issue is being posted (the next poll takes the rest: one request is posted at a time). A mention
643
+ * waiting for a task-agent slot is scanned at every poll and stays in, outside the window too, until it is decided; so
644
+ * does a mention held back from its issue update (the cap on updates, a post that failed), once the wait is over.
336
645
  */
337
646
  async getMentionDecisions(issue) {
338
647
  const { deps } = this;
@@ -341,20 +650,44 @@ class JiraInbound {
341
650
  const { trust } = deps;
342
651
  if (!project || !trust)
343
652
  return decisions;
653
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
654
+ const waitingTriggerId = this.getWaitingTriggerId(key, trigger_1.mentionTriggerIdPrefix);
655
+ const heldCommentIds = new Set(deps.triggerLog.listHeldMentionIds(issue.key, deps.now()));
344
656
  const { updated } = issue.fields;
345
- if (updated !== undefined && this.lastUpdatedByIssue.get(issue.key) === updated)
657
+ const isRescanDue = waitingTriggerId !== null || heldCommentIds.size > 0 || this.updateRetries.has(issue.key);
658
+ if (!isRescanDue && updated !== undefined && this.lastUpdatedByIssue.get(issue.key) === updated)
346
659
  return decisions;
347
660
  if (this.postingIssueKeys.has(issue.key))
348
661
  return decisions;
662
+ if (this.checkIsUpdateRetryPending(issue.key))
663
+ return decisions;
349
664
  const comments = await deps.client.getRecentComments(issue.key, exports.jiraMentionScanCommentCount);
350
665
  // The whole window every time, not "since the last scan": a comment that became visible a moment after a scan
351
666
  // is still inside it, and the seen-log makes the overlap harmless.
352
667
  const windowStartMs = deps.now() - getJiraMentionWindowMs(deps.pollIntervalMs);
668
+ const checkIsDecided = (comment) => deps.triggerLog.checkIsSeen(issue.key, `${trigger_1.mentionTriggerIdPrefix}${comment.id}`)
669
+ || deps.triggerLog.checkIsSeen(issue.key, `${trigger_1.commentTriggerIdPrefix}${comment.id}`);
670
+ // A waiting mention whose comment is gone, or was decided meanwhile, waits no more.
671
+ if (waitingTriggerId !== null && !comments.some((comment) => `${trigger_1.mentionTriggerIdPrefix}${comment.id}` === waitingTriggerId && !checkIsDecided(comment))) {
672
+ deps.slots.dropWaiting(key, (triggerId) => triggerId === waitingTriggerId);
673
+ }
674
+ // A held mention is kept no more once its comment is gone (or no longer among the newest) — it can never be delivered —
675
+ // or a prompt of the issue built since carried it (the watermark passed it: an update of the issue once it was handed).
676
+ const shownUpToId = deps.triggerLog.getNewestShownCommentId(issue.key);
677
+ for (const commentId of heldCommentIds) {
678
+ const isShown = shownUpToId !== null && (0, trigger_1.compareJiraCommentIds)(commentId, shownUpToId) <= 0;
679
+ if (!isShown && comments.some((comment) => comment.id === commentId))
680
+ continue;
681
+ deps.triggerLog.forgetHeldMention(issue.key, commentId);
682
+ heldCommentIds.delete(commentId);
683
+ }
353
684
  const undecidedMentions = comments
354
685
  .filter((comment) => comment.author?.accountId !== deps.aiAccountId
355
- && Math.max(Date.parse(comment.created), Date.parse(comment.updated ?? comment.created)) >= windowStartMs
686
+ && (Math.max(Date.parse(comment.created), Date.parse(comment.updated ?? comment.created)) >= windowStartMs
687
+ || `${trigger_1.mentionTriggerIdPrefix}${comment.id}` === waitingTriggerId
688
+ || heldCommentIds.has(comment.id))
356
689
  && (0, adf_1.getMentionedAccountIds)(comment.body).includes(deps.aiAccountId)
357
- && !deps.triggerLog.checkIsSeen(issue.key, `${trigger_1.mentionTriggerIdPrefix}${comment.id}`))
690
+ && !checkIsDecided(comment))
358
691
  .sort((left, right) => Date.parse(left.created) - Date.parse(right.created));
359
692
  let isEveryMentionDecided = true;
360
693
  for (const comment of undecidedMentions) {
@@ -364,16 +697,23 @@ class JiraInbound {
364
697
  }
365
698
  const decision = await this.getMentionDecisionSafely(issue, project, comment, trust);
366
699
  decisions.set(`${issue.key}${mentionDecisionKeySeparator}${trigger_1.mentionTriggerIdPrefix}${comment.id}`, decision);
367
- if (decision === 'failed')
700
+ if (undecidedDecisions.has(decision))
368
701
  isEveryMentionDecided = false;
369
702
  }
370
703
  if (isEveryMentionDecided && updated !== undefined)
371
704
  this.lastUpdatedByIssue.set(issue.key, updated);
372
705
  return decisions;
373
706
  }
374
- /** One comment failing (the issue could not be read for its prompt, say) leaves the others' decisions standing; the next poll retries it. */
375
- getMentionDecisionSafely(issue, project, comment, trust) {
376
- return this.runOrWarn(issue.key, `mention in comment ${comment.id}: `, () => this.getMentionDecision(issue, project, comment, trust), 'failed');
707
+ /**
708
+ * One comment failing (the issue could not be read for its prompt, say) leaves the others' decisions standing; the next poll
709
+ * retries it. A mention that waited for a slot and is decided now — started, or refused, parked or turned into an update —
710
+ * gives its place up.
711
+ */
712
+ async getMentionDecisionSafely(issue, project, comment, trust) {
713
+ const decision = await this.runOrWarn(issue.key, `mention in comment ${comment.id}: `, () => this.getMentionDecision(issue, project, comment, trust), 'failed');
714
+ if (!undecidedDecisions.has(decision))
715
+ this.deps.slots.dropWaiting((0, sessionKeyCodec_1.makeJiraKey)(issue.key), (triggerId) => triggerId === `${trigger_1.mentionTriggerIdPrefix}${comment.id}`);
716
+ return decision;
377
717
  }
378
718
  async getMentionDecision(issue, project, comment, trust) {
379
719
  const { deps } = this;
@@ -388,17 +728,23 @@ class JiraInbound {
388
728
  console.log(`[jira] ${issue.key}: the mention in comment ${comment.id} is ignored: its author or last editor is outside the trusted group`);
389
729
  return 'untrusted';
390
730
  }
391
- // D9: the requester of an open hand-over request already has the agent on this issue; their comment reaches that
392
- // run (a delta, or the news). A request of their own would supersede it and strip its hand-back. A hand-over
393
- // request with NO requester is superseded by ANY next request of the conversation (`requestLedger.ts`), so while
394
- // one is open every mention is covered by it.
731
+ // D9: the requester of an open hand-over request already has the agent on this issue; a request of their own would
732
+ // supersede it and strip its hand-back. A hand-over request with NO requester is superseded by ANY next request of
733
+ // the conversation (`requestLedger.ts`), so while one is open every mention belongs to it. With comment wakes on the
734
+ // comment reaches that run as an issue update; with them off it is `covered`: recorded, nothing posted.
735
+ // With comment wakes on, the same holds for an open mention that acts: a follow-up mention by its requester (on an issue
736
+ // not handed to the AI, where a plain comment never arrives) goes into that work, not into a second mention request.
395
737
  const requesterAccountId = comment.author?.accountId;
738
+ const isCommentWakeOn = this.checkIsCommentWakeOn();
396
739
  const isCovered = deps.listOpenRequests((0, sessionKeyCodec_1.makeJiraKey)(issue.key)).some((request) => {
397
740
  const openRequester = (0, requestGroup_1.getRequestRequester)(request.origin);
398
- return request.origin.kind === 'trackerEvent' && (openRequester === requesterAccountId || openRequester === requestGroup_1.emptyRequester);
741
+ const isCoveringKind = isCommentWakeOn ? (0, taskAgentSlots_1.checkIsSlotHoldingOrigin)(request.origin) : request.origin.kind === 'trackerEvent';
742
+ return isCoveringKind && !request.isWakeStopped && (openRequester === requesterAccountId || openRequester === requestGroup_1.emptyRequester);
399
743
  });
400
- if (isCovered)
744
+ if (isCovered && !isCommentWakeOn)
401
745
  return record('covered') ? 'covered' : 'failed';
746
+ if (isCovered)
747
+ return this.postIssueUpdate(issue, project, [comment], trigger_1.mentionTriggerIdPrefix, at);
402
748
  if (deps.triggerLog.getRequestCountLastDay(issue.key, at) >= deps.runBudgetPer24h) {
403
749
  // D10: the notice is posted at most once per issue per rolling 24 h; later over-budget mentions are recorded silently.
404
750
  const isNoticeDue = !deps.triggerLog.checkIsMentionParkNoticePostedLastDay(issue.key, at);
@@ -408,8 +754,409 @@ class JiraInbound {
408
754
  await deps.parkMention(issue.key);
409
755
  return 'parked';
410
756
  }
757
+ // An acting mention may start a build: it takes a task-agent slot like a hand-over (and waits for one past the cap).
758
+ if (deps.mentionMode === 'act')
759
+ return this.openRequestInSlot(issue, project, trigger, comment.author ?? null, at);
411
760
  return this.openRequest(issue, project, trigger, comment.author ?? null, at);
412
761
  }
762
+ /**
763
+ * Open the request of `trigger` in a free task-agent slot; past the cap the conversation joins the bot's wait list — told
764
+ * once with the queued notice, its trigger unrecorded, decided again by every poll until it is first in the list.
765
+ */
766
+ async openRequestInSlot(issue, project, trigger, requester, at, extraRecords = []) {
767
+ const { deps } = this;
768
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
769
+ const slot = await deps.slots.checkIn(key, trigger.triggerId);
770
+ if (slot.kind === 'queued') {
771
+ if (!slot.isNewlyQueued)
772
+ return 'waiting';
773
+ await deps.postQueuedNotice(issue.key, slot);
774
+ return 'queued';
775
+ }
776
+ try {
777
+ const decision = await this.openRequest(issue, project, trigger, requester, at, extraRecords);
778
+ deps.slots.noteStarted(key);
779
+ return decision;
780
+ }
781
+ catch (error) {
782
+ deps.slots.noteStartFailed(key);
783
+ throw error;
784
+ }
785
+ }
786
+ getCommentDecisionsSafely(issue, project) {
787
+ const failed = new Map([[`${issue.key}${mentionDecisionKeySeparator}comment`, 'failed']]);
788
+ return this.runOrWarn(issue.key, 'comment scan: ', () => this.getCommentDecisions(issue, project), failed);
789
+ }
790
+ /**
791
+ * @description The new comments of an issue HANDED to the AI account (its hand-over seen), decided in one go: the trusted
792
+ * people's reach its agent — as ONE issue update of the open hand-over request, else as ONE request of their own —
793
+ * the others are recorded `untrusted` (silent), and an app's or an automation's ride the next prompt. Skipped while the
794
+ * issue's `updated` is what the last complete scan saw (unless a comment's request waits for a slot: then every poll
795
+ * decides it again), while a post of the issue is in flight, and while a failed update waits for its retry.
796
+ */
797
+ async getCommentDecisions(issue, project) {
798
+ const { deps } = this;
799
+ const decisions = new Map();
800
+ const { trust } = deps;
801
+ if (!trust)
802
+ return decisions;
803
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
804
+ // Read again whatever `updated` says while a comment's request waits for a slot, or a failed update waits for its retry.
805
+ const isRescanDue = this.getWaitingTriggerId(key, trigger_1.commentTriggerIdPrefix) !== null || this.updateRetries.has(issue.key);
806
+ const { updated } = issue.fields;
807
+ if (!isRescanDue && updated !== undefined && this.lastUpdatedByIssue.get(issue.key) === updated)
808
+ return decisions;
809
+ if (this.postingIssueKeys.has(issue.key) || this.checkIsUpdateRetryPending(issue.key))
810
+ return decisions;
811
+ const comments = await deps.client.getRecentComments(issue.key, exports.jiraMentionScanCommentCount);
812
+ const at = deps.now();
813
+ const partition = this.partitionTrustedComments(issue.key, this.listNewComments(issue.key, comments), trust, at, decisions);
814
+ const { counted } = partition;
815
+ let { isEveryCommentDecided } = partition;
816
+ if (counted.length > 0) {
817
+ const newest = counted[counted.length - 1];
818
+ const decision = await this.runOrWarn(issue.key, `comments ${counted.map((comment) => comment.id).join(', ')}: `, () => this.deliverComments(issue, project, counted, at), 'failed');
819
+ decisions.set(`${issue.key}${mentionDecisionKeySeparator}${trigger_1.commentTriggerIdPrefix}${newest.id}`, decision);
820
+ if (undecidedDecisions.has(decision))
821
+ isEveryCommentDecided = false;
822
+ }
823
+ if (isEveryCommentDecided && updated !== undefined)
824
+ this.lastUpdatedByIssue.set(issue.key, updated);
825
+ return decisions;
826
+ }
827
+ /** The comments of `comments` new to the issue's conversation and not decided yet (none the AI account wrote), oldest first. */
828
+ listNewComments(issueKey, comments) {
829
+ const { deps } = this;
830
+ return comments
831
+ .filter((comment) => comment.author?.accountId !== deps.aiAccountId
832
+ && this.checkIsCommentNewToConversation(issueKey, comment)
833
+ && !deps.triggerLog.checkIsSeen(issueKey, `${trigger_1.commentTriggerIdPrefix}${comment.id}`)
834
+ && !deps.triggerLog.checkIsSeen(issueKey, `${trigger_1.mentionTriggerIdPrefix}${comment.id}`))
835
+ .sort((left, right) => (0, trigger_1.compareJiraCommentIds)(left.id, right.id));
836
+ }
837
+ /**
838
+ * The people's comments of `comments` that may reach the agent (`counted`): an app's or an automation's (a pipeline notice,
839
+ * a rule) wakes nothing — it rides the next prompt — and one whose author or last editor is not trusted is recorded
840
+ * `untrusted` (one log line, nothing posted; its decision goes into `decisions`).
841
+ */
842
+ partitionTrustedComments(issueKey, comments, trust, at, decisions) {
843
+ const counted = [];
844
+ let isEveryCommentDecided = true;
845
+ for (const comment of comments) {
846
+ if (!comment.author || !(0, trigger_1.checkIsPersonAccount)(comment.author))
847
+ continue;
848
+ const decisionKey = `${issueKey}${mentionDecisionKeySeparator}${trigger_1.commentTriggerIdPrefix}${comment.id}`;
849
+ // The same rule as for the comment's text: its author AND its last editor.
850
+ if (!(0, issueBlocks_1.checkIsCommentTrusted)(comment, trust)) {
851
+ const isRecorded = this.recordOrWarn({ issueKey, triggerId: `${trigger_1.commentTriggerIdPrefix}${comment.id}`, outcome: 'untrusted', at });
852
+ if (isRecorded)
853
+ console.log(`[jira] ${issueKey}: comment ${comment.id} does not wake the AI: its author or last editor is outside the trusted group`);
854
+ else
855
+ isEveryCommentDecided = false;
856
+ decisions.set(decisionKey, isRecorded ? 'untrusted' : 'failed');
857
+ continue;
858
+ }
859
+ counted.push(comment);
860
+ }
861
+ return { counted, isEveryCommentDecided };
862
+ }
863
+ /**
864
+ * Is `comment` new to the issue's conversation? Newer than every comment a recorded prompt of the issue was built from
865
+ * (the trigger log's watermark — it survives a restart, a compaction and a fresh session) or the conversation was shown.
866
+ * With neither (decisions recorded before the watermark was): not shown, and written after the issue's last decision.
867
+ */
868
+ checkIsCommentNewToConversation(issueKey, comment) {
869
+ const { deps } = this;
870
+ const recordedId = deps.triggerLog.getNewestShownCommentId(issueKey);
871
+ if (recordedId !== null)
872
+ return (0, trigger_1.compareJiraCommentIds)(comment.id, recordedId) > 0;
873
+ if (deps.contextLedger.getShownBlock(issueKey, `${trigger_1.commentTriggerIdPrefix}${comment.id}`))
874
+ return false;
875
+ const lastDecidedAt = deps.triggerLog.getLastDecidedAt(issueKey);
876
+ return lastDecidedAt !== null && Date.parse(comment.created) > lastDecidedAt;
877
+ }
878
+ /**
879
+ * The requests of the conversation an update can belong to, open and not given up: its hand-overs and its mentions that
880
+ * may act (the work it is doing on the issue) — and, on an issue the AI account handed to itself, any open request: the
881
+ * one that made it take the issue up is still working on it.
882
+ */
883
+ listUpdateTargetRequests(key) {
884
+ const open = this.deps.listOpenRequests(key).filter((request) => !request.isWakeStopped);
885
+ const working = open.filter((request) => (0, taskAgentSlots_1.checkIsSlotHoldingOrigin)(request.origin));
886
+ if (working.length > 0 || !this.selfAssignedIssueKeys.has(key.thread))
887
+ return working;
888
+ return open.filter((request) => request.origin.kind === 'trackerMention');
889
+ }
890
+ /**
891
+ * The trusted comments `counted` (oldest first) of a handed issue: an issue update when a hand-over request is open, else
892
+ * a request of their own — the newest comment's trigger, its author the requester — through the run budget and a slot.
893
+ */
894
+ async deliverComments(issue, project, counted, at) {
895
+ const { deps } = this;
896
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
897
+ if (this.listUpdateTargetRequests(key).length > 0) {
898
+ // A comment's request that waited for a slot is no longer needed: the hand-over that opened since carries it.
899
+ deps.slots.dropWaiting(key, (triggerId) => triggerId.startsWith(trigger_1.commentTriggerIdPrefix));
900
+ return this.postIssueUpdate(issue, project, counted, trigger_1.commentTriggerIdPrefix, at);
901
+ }
902
+ // An issue the AI account handed to itself while ANOTHER issue's request works on it (it created the issue, or took it up,
903
+ // in that run): the comment goes to that request — a request of its own would be a second agent on the same work.
904
+ if (this.selfAssignedIssueKeys.has(issue.key)) {
905
+ const linked = await this.findLinkedWorkingRequest(issue, project);
906
+ if (linked)
907
+ return this.postLinkedIssueUpdate(issue, counted, at, linked);
908
+ }
909
+ const newest = counted[counted.length - 1];
910
+ const trigger = (0, trigger_1.createCommentTrigger)(counted.map((comment) => comment.id), newest.author ?? null);
911
+ const requester = newest.author ?? null;
912
+ const olderRecords = counted.slice(0, -1).map((comment) => ({ issueKey: issue.key, triggerId: `${trigger_1.commentTriggerIdPrefix}${comment.id}`, outcome: 'update', at }));
913
+ if (deps.triggerLog.getRequestCountLastDay(issue.key, at) >= deps.runBudgetPer24h) {
914
+ // Recorded first, as a hand-over's park: the notice and the hand-back go out at most once.
915
+ const records = [...olderRecords.map((record) => ({ ...record, outcome: 'parked' })), { issueKey: issue.key, triggerId: trigger.triggerId, outcome: 'parked', at }];
916
+ if (!records.every((record) => this.recordOrWarn(record)))
917
+ return 'failed';
918
+ await deps.parkIssue(issue.key, requester);
919
+ return 'parked';
920
+ }
921
+ return this.openRequestInSlot(issue, project, trigger, requester, at, olderRecords);
922
+ }
923
+ /**
924
+ * The open request that works on an issue linked to `issue` — its parent, a sub-task or child, either end of an issue link,
925
+ * in an allowlisted project — and holds a task-agent slot (a hand-over, or a mention that may act); `null` when none does.
926
+ * When several do, the one on an issue the AI account tied `issue` to (it linked them, or set the parent: the run that
927
+ * created or took it up), else the first. Read with the issue's context, which the update then quotes.
928
+ */
929
+ async findLinkedWorkingRequest(issue, project) {
930
+ const { deps } = this;
931
+ const context = await (0, issueContext_1.fetchJiraIssueContext)(deps.client, issue.key, project.extraFields.map((extraField) => extraField.id), deps.trust !== null);
932
+ const { fields } = context.issue;
933
+ const linkedKeys = [
934
+ fields.parent?.key,
935
+ ...(fields.issuelinks ?? []).flatMap((link) => [link.outwardIssue?.key, link.inwardIssue?.key]),
936
+ ...(fields.subtasks ?? []).map((subtask) => subtask.key),
937
+ ...context.children.map((child) => child.key),
938
+ ].filter((linkedKey) => linkedKey !== undefined && linkedKey !== issue.key && (0, sessionKeyCodec_1.getJiraIssueProjectKey)(linkedKey) !== null && deps.projects.has((0, sessionKeyCodec_1.getJiraIssueProjectKey)(linkedKey) ?? ''));
939
+ const working = [...new Set(linkedKeys)].flatMap((linkedKey) => {
940
+ const request = deps.listOpenRequests((0, sessionKeyCodec_1.makeJiraKey)(linkedKey)).find((open) => (0, taskAgentSlots_1.checkIsSlotHoldingOrigin)(open.origin) && !open.isWakeStopped);
941
+ return request ? [{ linkedKey, request }] : [];
942
+ });
943
+ if (working.length === 0)
944
+ return null;
945
+ const tiedKeys = working.length > 1 ? listIssueKeysTiedByAi(context, deps.aiAccountId) : new Set();
946
+ const picked = working.find(({ linkedKey }) => tiedKeys.has(linkedKey)) ?? working[0];
947
+ if (working.length > 1) {
948
+ const why = tiedKeys.has(picked.linkedKey) ? 'the AI account tied the issue to it' : 'the first: the changelog shows no tie the AI account made';
949
+ console.log(`[jira] ${issue.key}: linked issues ${working.map(({ linkedKey }) => linkedKey).join(', ')} each have a request at work; its comments go to ${picked.linkedKey}'s (${why})`);
950
+ }
951
+ return { issueKey: picked.linkedKey, requestId: picked.request.id, origin: picked.request.origin, context, project };
952
+ }
953
+ /**
954
+ * @description Post the comments of a self-handed issue into the conversation of the linked issue whose request works on it:
955
+ * an issue update of THAT request whose header names the issue the comments are on, carrying only the new comments (that
956
+ * conversation's context ledger is its own issue's). Recorded on the commented issue once posted, like any update.
957
+ */
958
+ async postLinkedIssueUpdate(issue, comments, at, linked) {
959
+ const { deps } = this;
960
+ const { trust } = deps;
961
+ if (deps.triggerLog.getUpdateCountLastDay(issue.key, at) >= exports.jiraIssueUpdatesPer24hMax)
962
+ return this.pauseUpdates(issue.key, comments, trigger_1.commentTriggerIdPrefix);
963
+ const blockTrust = trust && {
964
+ checkIsTrusted: (account) => trust.checkIsTrusted(account),
965
+ allowlistedProjectKeys: new Set(deps.projects.keys()),
966
+ };
967
+ const commentKeys = new Set(comments.map((comment) => `${trigger_1.commentTriggerIdPrefix}${comment.id}`));
968
+ const commentBlocks = (0, issueBlocks_1.buildIssueBlocks)(linked.context, linked.project.extraFields, deps.aiAccountId, blockTrust).filter((block) => commentKeys.has(block.key));
969
+ const requesterAccountId = (0, requestGroup_1.getRequestRequester)(linked.origin);
970
+ const targetKey = (0, sessionKeyCodec_1.makeJiraKey)(linked.issueKey);
971
+ const buildText = () => (0, prompt_1.buildJiraUpdatePrompt)({
972
+ issueKey: issue.key,
973
+ issueUrl: `${deps.siteUrl.replace(/\/+$/, '')}/browse/${issue.key}`,
974
+ requestIssueKey: linked.issueKey,
975
+ target: {
976
+ requestId: linked.requestId,
977
+ requester: (0, issueContext_1.findAccountInContext)(linked.context, requesterAccountId),
978
+ isMention: linked.origin.kind === 'trackerMention',
979
+ isOpen: deps.listOpenRequests(targetKey).some((open) => open.id === linked.requestId),
980
+ },
981
+ openHandOvers: [],
982
+ comments: comments.map((comment) => ({ commentId: comment.id, author: comment.author ?? null })),
983
+ isTextFiltered: trust !== null,
984
+ delta: { entries: commentBlocks.map((block) => ({ block, stateNote: issueDelta_1.newBlockNote })), unchangedKinds: [], unchangedCommentCount: 0, deletedCommentLabels: [], sent: {} },
985
+ });
986
+ const prompt = { fullText: buildText(), buildText };
987
+ // Only the delivered comments were shown (not the rest of the issue, read after the scan): one written in between stays new.
988
+ const newestCommentId = getNewestCommentId(comments);
989
+ this.postingIssueKeys.add(issue.key);
990
+ void this.postUpdateAndRecord(targetKey, issue.key, prompt, () => linked.requestId, (requestId) => comments.map((comment) => ({
991
+ issueKey: issue.key,
992
+ triggerId: `${trigger_1.commentTriggerIdPrefix}${comment.id}`,
993
+ outcome: 'update',
994
+ at,
995
+ requestId,
996
+ newestCommentId,
997
+ })));
998
+ return 'update';
999
+ }
1000
+ /**
1001
+ * Past the cap on issue updates: the comments stay undecided and are delivered once the oldest update of the last 24 h
1002
+ * leaves that window (the scan waits until then; a mention, found only inside the mention window, is held back so the
1003
+ * scan keeps it). One log line per pause says until when; the issue gets ONE comment by the AI account saying so at most
1004
+ * once per rolling 24 h — a steady stream of comments pauses it again at every window end — and the AI account's own
1005
+ * comments are never delivered, so the notice starts no loop.
1006
+ */
1007
+ async pauseUpdates(issueKey, comments, prefix) {
1008
+ const { deps } = this;
1009
+ const at = deps.now();
1010
+ const until = deps.triggerLog.getUpdateWindowEnd(issueKey, at) ?? at + msPerDay;
1011
+ this.updateRetries.set(issueKey, { failureCount: 0, retryAt: until });
1012
+ if (prefix === trigger_1.mentionTriggerIdPrefix)
1013
+ this.holdMentionsBack(issueKey, comments, at);
1014
+ const pauseTriggerId = `${trigger_1.updatesPausedTriggerIdPrefix}${until}`;
1015
+ if (deps.triggerLog.checkIsSeen(issueKey, pauseTriggerId))
1016
+ return 'waiting';
1017
+ // Recorded first, like a mention's park notice: never logged or posted again after a failed post or a restart.
1018
+ const isNoticeDue = !deps.triggerLog.checkIsUpdatesPausedNoticePostedLastDay(issueKey, at);
1019
+ if (!this.recordOrWarn({ issueKey, triggerId: pauseTriggerId, outcome: 'parked', at, isNoticePosted: isNoticeDue }))
1020
+ return 'failed';
1021
+ const noticeText = isNoticeDue ? 'the issue says so in one comment' : 'the issue got its one comment about a pause in the last 24 h, so it gets none now';
1022
+ console.warn(`[jira] ${issueKey}: ${exports.jiraIssueUpdatesPer24hMax} issue updates in 24 h, the cap: comments ${comments.map((comment) => comment.id).join(', ')} and later ones wait until ${new Date(until).toISOString()} and are delivered then; ${noticeText}. Does the agent comment under a person's account instead of the AI account?`);
1023
+ if (isNoticeDue)
1024
+ await deps.postUpdatesPausedNotice(issueKey, until);
1025
+ return 'waiting';
1026
+ }
1027
+ /**
1028
+ * Mark the mentions `comments` held back from their issue update (`held-mention:`): the mention scan keeps them, outside
1029
+ * the mention window too, until they are delivered. Kept for this process when the line could not be written.
1030
+ */
1031
+ holdMentionsBack(issueKey, comments, at) {
1032
+ for (const comment of comments) {
1033
+ const triggerId = `${trigger_1.heldMentionTriggerIdPrefix}${comment.id}`;
1034
+ if (this.deps.triggerLog.checkIsSeen(issueKey, triggerId))
1035
+ continue;
1036
+ const record = { issueKey, triggerId, outcome: 'parked', at };
1037
+ if (!this.recordOrWarn(record))
1038
+ this.deps.triggerLog.remember(record);
1039
+ }
1040
+ }
1041
+ /** A failed issue update of the issue waits for its retry. */
1042
+ checkIsUpdateRetryPending(issueKey) {
1043
+ const retry = this.updateRetries.get(issueKey);
1044
+ return retry !== undefined && this.deps.now() < retry.retryAt;
1045
+ }
1046
+ /**
1047
+ * @description Post an ISSUE UPDATE: the comments `comments` (trigger ids `prefix` + id: a comment's, or a mention's)
1048
+ * reach the agent inside an open hand-over request of the conversation — no request is opened. Which request is
1049
+ * settled right before the forward (the post may have waited behind a running turn): the commenter's own open one,
1050
+ * else one with no requester, else the newest; when every hand-over finished meanwhile, the one the update was meant
1051
+ * for, named as finished — the comment still reaches the agent, and its answer becomes a comment. The text is the
1052
+ * issue's delta (or the whole issue for a session that does not know it). Recorded once the post settled; a post that
1053
+ * failed is decided again after a backoff. Not awaited: the issue is skipped until the post settles.
1054
+ */
1055
+ async postIssueUpdate(issue, project, comments, prefix, at, finishedTarget = null) {
1056
+ const { deps } = this;
1057
+ const { trust } = deps;
1058
+ // A trusted account that is not the AI account may write as the agent's own tooling (an operator token in its MCP
1059
+ // config): every comment it writes would be the next poll's update, one turn per poll for ever. Updates are capped.
1060
+ if (deps.triggerLog.getUpdateCountLastDay(issue.key, at) >= exports.jiraIssueUpdatesPer24hMax)
1061
+ return this.pauseUpdates(issue.key, comments, prefix);
1062
+ const context = await (0, issueContext_1.fetchJiraIssueContext)(deps.client, issue.key, project.extraFields.map((extraField) => extraField.id), trust !== null);
1063
+ const blockTrust = trust && {
1064
+ checkIsTrusted: (account) => trust.checkIsTrusted(account),
1065
+ allowlistedProjectKeys: new Set(deps.projects.keys()),
1066
+ };
1067
+ const blocks = (0, issueBlocks_1.buildIssueBlocks)(context, project.extraFields, deps.aiAccountId, blockTrust);
1068
+ deps.noteShownSummary?.(issue.key, (0, issueBlocks_1.getShownIssueSummary)(context, blockTrust));
1069
+ const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
1070
+ const commenterAccountId = comments[comments.length - 1].author?.accountId;
1071
+ const newComments = comments.map((comment) => ({ commentId: comment.id, author: comment.author ?? null }));
1072
+ /** The requests the update can belong to now, named from the issue's data (a mention's marked as one). */
1073
+ const getTargets = () => this.listUpdateTargetRequests(key).map((request) => ({
1074
+ requestId: request.id,
1075
+ requester: (0, issueContext_1.findAccountInContext)(context, (0, requestGroup_1.getRequestRequester)(request.origin)),
1076
+ requesterAccountId: (0, requestGroup_1.getRequestRequester)(request.origin),
1077
+ isMention: request.origin.kind === 'trackerMention',
1078
+ }));
1079
+ const pickTarget = () => {
1080
+ const targets = getTargets();
1081
+ return targets.find((target) => target.requesterAccountId === commenterAccountId)
1082
+ ?? targets.find((target) => target.requesterAccountId === requestGroup_1.emptyRequester)
1083
+ ?? targets[targets.length - 1]
1084
+ ?? null;
1085
+ };
1086
+ const firstTarget = pickTarget() ?? (finishedTarget ? { ...finishedTarget, requester: (0, issueContext_1.findAccountInContext)(context, finishedTarget.requesterAccountId) } : null);
1087
+ if (!firstTarget)
1088
+ throw new Error('no request is open for the update');
1089
+ let target = firstTarget;
1090
+ const getBase = () => {
1091
+ const now = pickTarget();
1092
+ if (now)
1093
+ target = now;
1094
+ return {
1095
+ issueKey: issue.key,
1096
+ issueUrl: `${deps.siteUrl.replace(/\/+$/, '')}/browse/${issue.key}`,
1097
+ target: { requestId: target.requestId, requester: target.requester, isMention: target.isMention, isOpen: now !== null },
1098
+ openHandOvers: getTargets().map((open) => ({ requestId: open.requestId, requester: open.requester })),
1099
+ comments: newComments,
1100
+ isTextFiltered: trust !== null,
1101
+ };
1102
+ };
1103
+ const fitted = await (0, promptSpill_1.fitBlocksToPrompt)({
1104
+ blocks,
1105
+ textDir: deps.getSpillDir(key),
1106
+ measure: (candidate) => (0, prompt_1.buildJiraUpdatePrompt)({ ...getBase(), ...candidate }).length,
1107
+ });
1108
+ const newestCommentId = getNewestCommentId(context.comments);
1109
+ const prompt = {
1110
+ fullText: (0, prompt_1.buildJiraUpdatePrompt)({ ...getBase(), ...fitted }),
1111
+ buildText: ({ isFresh }) => {
1112
+ const base = getBase();
1113
+ const snapshot = deps.contextLedger.getSnapshot(issue.key);
1114
+ const isWhole = isFresh || Object.keys(snapshot.sent).length === 0;
1115
+ const delta = (0, issueDelta_1.getIssueDelta)(fitted.blocks, isWhole ? {} : snapshot.sent);
1116
+ // Counted as sent once the request it belongs to takes it in, or is closed by its answer (C4).
1117
+ deps.contextLedger.recordBuild(issue.key, base.target.requestId, snapshot.generation, delta.sent);
1118
+ return isWhole ? (0, prompt_1.buildJiraUpdatePrompt)({ ...base, ...fitted }) : (0, prompt_1.buildJiraUpdatePrompt)({ ...base, delta });
1119
+ },
1120
+ };
1121
+ this.postingIssueKeys.add(issue.key);
1122
+ // A mention whose update failed is retried after a backoff that may outlast the mention window: it is held back.
1123
+ const onFailed = prefix === trigger_1.mentionTriggerIdPrefix ? () => this.holdMentionsBack(issue.key, comments, at) : undefined;
1124
+ void this.postUpdateAndRecord(key, issue.key, prompt, () => target.requestId, (requestId) => comments.map((comment) => ({
1125
+ issueKey: issue.key,
1126
+ triggerId: `${prefix}${comment.id}`,
1127
+ outcome: 'update',
1128
+ at,
1129
+ requestId,
1130
+ newestCommentId,
1131
+ })), onFailed);
1132
+ return 'update';
1133
+ }
1134
+ /**
1135
+ * Post the update, then record its comments — only when it reached the session (or a usage-limit wait holds it): an
1136
+ * update that failed is decided again by a later poll, after a backoff (the session could not be started, say, and a
1137
+ * start per poll would hammer it). Never rejects.
1138
+ */
1139
+ async postUpdateAndRecord(key, issueKey, prompt, getTargetRequestId, createRecords, onFailed) {
1140
+ try {
1141
+ await this.deps.postUpdate(key, prompt, getTargetRequestId);
1142
+ }
1143
+ catch (error) {
1144
+ const failureCount = (this.updateRetries.get(issueKey)?.failureCount ?? 0) + 1;
1145
+ const delayMs = getJiraRetryDelayMs(this.deps.pollIntervalMs, failureCount);
1146
+ // Kept until an update of the issue reaches the session: while it is, the issue is scanned again once the wait is over.
1147
+ this.updateRetries.set(issueKey, { failureCount, retryAt: this.deps.now() + delayMs });
1148
+ onFailed?.();
1149
+ this.postingIssueKeys.delete(issueKey);
1150
+ console.warn(`[jira] ${issueKey}: an issue update for request ${getTargetRequestId()} was not posted (${error instanceof Error ? error.message : String(error)}); tried again in ${Math.round(delayMs / 1000)} s`);
1151
+ return;
1152
+ }
1153
+ this.updateRetries.delete(issueKey);
1154
+ for (const record of createRecords(getTargetRequestId())) {
1155
+ if (!this.recordOrWarn(record))
1156
+ this.deps.triggerLog.remember(record);
1157
+ }
1158
+ this.postingIssueKeys.delete(issueKey);
1159
+ }
413
1160
  /**
414
1161
  * The hand-over requests (`trackerEvent`) the conversation has open, each with its requester named as the issue's own
415
1162
  * data names them — what a mention note says goes on. A mention request itself is not one: it hands nothing over.
@@ -456,7 +1203,11 @@ class JiraInbound {
456
1203
  }
457
1204
  return entry.rebuild();
458
1205
  };
459
- async openRequest(issue, project, trigger, requester, at) {
1206
+ /**
1207
+ * Open the request of `trigger` and post it (not awaited); `extraRecords` are recorded with its trigger once the post
1208
+ * settled (the older comments a comment's request carries). Every record names the newest comment the prompt was built from.
1209
+ */
1210
+ async openRequest(issue, project, trigger, requester, at, extraRecords = []) {
460
1211
  const { deps } = this;
461
1212
  const { trust } = deps;
462
1213
  // Fetched before the request opens: a request is never left without its prompt. The whole changelog is read
@@ -471,6 +1222,11 @@ class JiraInbound {
471
1222
  const key = (0, sessionKeyCodec_1.makeJiraKey)(issue.key);
472
1223
  const statusId = context.issue.fields.status?.id;
473
1224
  const isMention = trigger.kind === 'mentioned';
1225
+ const isActingMention = isMention && deps.mentionMode === 'act';
1226
+ const newComments = (trigger.commentIds ?? []).map((commentId) => ({
1227
+ commentId,
1228
+ author: context.comments.find((comment) => comment.id === commentId)?.author ?? null,
1229
+ }));
474
1230
  const promptInput = {
475
1231
  issueKey: issue.key,
476
1232
  statusName: context.issue.fields.status?.name,
@@ -485,6 +1241,8 @@ class JiraInbound {
485
1241
  openHandOvers: isMention ? this.getOpenHandOvers(key, context) : [],
486
1242
  triggerStatusNames: project.triggerStatusNames,
487
1243
  isTextFiltered: trust !== null,
1244
+ mentionMode: deps.mentionMode,
1245
+ newComments,
488
1246
  };
489
1247
  // Rendered and written BEFORE the request opens: the ledger builds the prompt inside its own synchronous update.
490
1248
  const fitted = await (0, promptSpill_1.fitBlocksToPrompt)({
@@ -503,9 +1261,15 @@ class JiraInbound {
503
1261
  // R34: the requester is part of the request's group key — a second person's trigger on the same
504
1262
  // issue opens a request of its own instead of superseding the first (`requests/requestGroup.ts`).
505
1263
  const request = await deps.createRequest(key, {
506
- // A mention hands nothing over, so its answer never hands anything back: the origin kind is what the sink reads.
507
- kind: trigger.kind === 'mentioned' ? 'trackerMention' : 'trackerEvent',
508
- attributes: { issueKey: issue.key, triggerId: trigger.triggerId, [requestGroup_1.requestRequesterAttribute]: requester?.accountId ?? requestGroup_1.emptyRequester },
1264
+ // A mention hands nothing over, so its answer never hands anything back: the origin kind is what the sink reads. An
1265
+ // acting mention says so in its origin: it holds a task-agent slot like a hand-over.
1266
+ kind: isMention ? 'trackerMention' : 'trackerEvent',
1267
+ attributes: {
1268
+ issueKey: issue.key,
1269
+ triggerId: trigger.triggerId,
1270
+ [requestGroup_1.requestRequesterAttribute]: requester?.accountId ?? requestGroup_1.emptyRequester,
1271
+ ...(isActingMention ? { [taskAgentSlots_1.actingMentionAttribute]: 'true' } : {}),
1272
+ },
509
1273
  }, createPrompt);
510
1274
  const supersededRequestIds = request.supersededRequestIds ?? [];
511
1275
  const fullText = createPrompt(request.id, supersededRequestIds);
@@ -530,7 +1294,11 @@ class JiraInbound {
530
1294
  // Not awaited: a busy session may take minutes to take the prompt, and the rest of
531
1295
  // the poll must not wait for it; until the post settles, the issue is skipped.
532
1296
  this.postingIssueKeys.add(issue.key);
533
- void this.postAndRecord(key, request.id, prompt, { issueKey: issue.key, triggerId: trigger.triggerId, outcome: 'request', at, requestId: request.id });
1297
+ const newestCommentId = getNewestCommentId(context.comments);
1298
+ void this.postAndRecord(key, request.id, prompt, [
1299
+ { issueKey: issue.key, triggerId: trigger.triggerId, outcome: 'request', at, requestId: request.id, newestCommentId },
1300
+ ...extraRecords.map((record) => ({ ...record, requestId: request.id, newestCommentId })),
1301
+ ]);
534
1302
  return 'request';
535
1303
  }
536
1304
  /**
@@ -540,16 +1308,19 @@ class JiraInbound {
540
1308
  * A record that cannot be written is still remembered for this process, so the
541
1309
  * posted request is never posted again before a restart. Never rejects.
542
1310
  */
543
- async postAndRecord(key, requestId, prompt, record) {
1311
+ async postAndRecord(key, requestId, prompt, records) {
1312
+ const { issueKey } = records[0];
544
1313
  try {
545
1314
  await this.deps.postRequest(key, requestId, prompt);
546
1315
  }
547
1316
  catch (error) {
548
- console.warn(`[jira] ${record.issueKey}: request ${requestId} not posted: ${error instanceof Error ? error.message : String(error)}`);
1317
+ console.warn(`[jira] ${issueKey}: request ${requestId} not posted: ${error instanceof Error ? error.message : String(error)}`);
1318
+ }
1319
+ for (const record of records) {
1320
+ if (!this.recordOrWarn(record))
1321
+ this.deps.triggerLog.remember(record);
549
1322
  }
550
- if (!this.recordOrWarn(record))
551
- this.deps.triggerLog.remember(record);
552
- this.postingIssueKeys.delete(record.issueKey);
1323
+ this.postingIssueKeys.delete(issueKey);
553
1324
  }
554
1325
  recordOrWarn(record) {
555
1326
  const isRecorded = this.deps.triggerLog.record(record);
@@ -575,7 +1346,7 @@ class JiraInbound {
575
1346
  if (!trigger)
576
1347
  continue;
577
1348
  if (deps.triggerLog.checkIsSeen(issue.key, trigger.triggerId))
578
- return 'seen';
1349
+ return { seen: trigger };
579
1350
  const isRequesterKnown = trigger.author?.accountId === deps.aiAccountId
580
1351
  || (0, trigger_1.getRequester)(trigger, histories, null, deps.aiAccountId) !== null;
581
1352
  if (isRequesterKnown)
@@ -583,7 +1354,7 @@ class JiraInbound {
583
1354
  }
584
1355
  const trigger = (0, trigger_1.getIssueTrigger)(histories, match, issue.fields.creator ?? reporter);
585
1356
  if (deps.triggerLog.checkIsSeen(issue.key, trigger.triggerId))
586
- return 'seen';
1357
+ return { seen: trigger };
587
1358
  return { trigger, requester: (0, trigger_1.getRequester)(trigger, histories, reporter, deps.aiAccountId) };
588
1359
  }
589
1360
  /**