typeclaw 0.48.6 → 0.48.8

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 (105) hide show
  1. package/auth.schema.json +15 -1
  2. package/package.json +1 -1
  3. package/secrets.schema.json +15 -1
  4. package/src/agent/guard-types.ts +25 -0
  5. package/src/agent/guards.ts +102 -0
  6. package/src/agent/index.ts +33 -3
  7. package/src/agent/live-subagents.ts +14 -0
  8. package/src/agent/multimodal/read-redirect.ts +8 -9
  9. package/src/agent/plugin-tools.ts +283 -148
  10. package/src/agent/provider-error.ts +6 -1
  11. package/src/agent/reload-tool.ts +12 -5
  12. package/src/agent/retry-same-ref.ts +95 -36
  13. package/src/agent/session-origin.ts +13 -1
  14. package/src/agent/system-prompt.ts +14 -3
  15. package/src/agent/todo/continuation-policy.ts +3 -4
  16. package/src/agent/tool-file-safety.ts +36 -13
  17. package/src/agent/tools/channel-reply.ts +39 -2
  18. package/src/agent/tools/channel-send.ts +45 -2
  19. package/src/agent/tools/post-github-review.ts +31 -13
  20. package/src/agent/tools/spawn-subagent.ts +15 -0
  21. package/src/agent/tools/webfetch/inline-style-visibility.ts +2 -2
  22. package/src/agent/tools/webfetch/strategies/readability.ts +109 -10
  23. package/src/agent/turn-runner.ts +23 -19
  24. package/src/bundled-plugins/backup/git-auth.ts +7 -4
  25. package/src/bundled-plugins/backup/subagents.ts +1 -1
  26. package/src/bundled-plugins/bun-hygiene/README.md +23 -20
  27. package/src/bundled-plugins/bun-hygiene/index.ts +1 -7
  28. package/src/bundled-plugins/bun-hygiene/policy.ts +111 -35
  29. package/src/bundled-plugins/github-cli-auth/gh-review-detect.ts +44 -2
  30. package/src/bundled-plugins/github-cli-auth/gh-store.ts +733 -0
  31. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +25 -0
  32. package/src/bundled-plugins/github-cli-auth/git-command.ts +231 -30
  33. package/src/bundled-plugins/github-cli-auth/git-credential-env.ts +151 -0
  34. package/src/bundled-plugins/github-cli-auth/index.ts +249 -42
  35. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +5 -0
  36. package/src/bundled-plugins/guard/index.ts +2 -25
  37. package/src/bundled-plugins/guard/keys.ts +8 -0
  38. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +7 -8
  39. package/src/bundled-plugins/guard/policy.ts +1 -7
  40. package/src/bundled-plugins/security/policies/git-exfil.ts +22 -30
  41. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +2 -4
  42. package/src/bundled-plugins/security/policies/private-surface-read.ts +8 -6
  43. package/src/bundled-plugins/security/policies/secret-exfil-bash.ts +2 -5
  44. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +2 -4
  45. package/src/bundled-plugins/security/policies/session-search-secrets.ts +2 -4
  46. package/src/bundled-plugins/security/policies/system-prompt-leak.ts +2 -4
  47. package/src/bundled-plugins/security/policy.ts +0 -8
  48. package/src/channels/adapters/discord-bot-slash-commands.ts +22 -0
  49. package/src/channels/adapters/discord-bot.ts +2 -1
  50. package/src/channels/adapters/discord-classify.ts +16 -4
  51. package/src/channels/adapters/discord.ts +20 -8
  52. package/src/channels/adapters/github/dedup.ts +37 -8
  53. package/src/channels/adapters/github/inbound.ts +241 -46
  54. package/src/channels/adapters/github/review-state.ts +13 -9
  55. package/src/channels/adapters/github/review-thread-resolver.ts +52 -20
  56. package/src/channels/adapters/slack-classify.ts +40 -5
  57. package/src/channels/adapters/slack.ts +3 -9
  58. package/src/channels/adapters/webex-bot-classify.ts +4 -33
  59. package/src/channels/adapters/webex-bot.ts +2 -4
  60. package/src/channels/adapters/webex-classify.ts +4 -33
  61. package/src/channels/adapters/webex-format.ts +36 -0
  62. package/src/channels/adapters/webex.ts +2 -4
  63. package/src/channels/continuation-willingness.ts +64 -39
  64. package/src/channels/github-rereview-guard.ts +20 -0
  65. package/src/channels/github-review-turn-ledger.ts +11 -1
  66. package/src/channels/github-review-verdict-coordinator.ts +475 -41
  67. package/src/channels/github-verdict-activity.ts +14 -5
  68. package/src/channels/persistence.ts +89 -5
  69. package/src/channels/router.ts +1223 -225
  70. package/src/channels/types.ts +21 -5
  71. package/src/cli/compose-stats.ts +6 -7
  72. package/src/cli/compose-status.ts +6 -7
  73. package/src/cli/compose-usage.ts +6 -7
  74. package/src/cli/stats.ts +6 -7
  75. package/src/cli/status.ts +7 -8
  76. package/src/cli/ui.ts +4 -4
  77. package/src/container/start.ts +41 -1
  78. package/src/cron/consumer.ts +30 -9
  79. package/src/cron/scheduler.ts +24 -9
  80. package/src/doctor/channel-checks.ts +64 -0
  81. package/src/doctor/report.ts +8 -8
  82. package/src/dreams/render.ts +2 -2
  83. package/src/init/dockerfile.ts +8 -1
  84. package/src/inspect/render.ts +2 -2
  85. package/src/path-safety/real-intended-path.ts +14 -1
  86. package/src/permissions/permissions.ts +10 -2
  87. package/src/permissions/resolve.ts +8 -2
  88. package/src/plugin/core-tool-names.ts +15 -0
  89. package/src/plugin/hooks.ts +37 -3
  90. package/src/plugin/registry.ts +7 -3
  91. package/src/run/index.ts +35 -15
  92. package/src/sandbox/build.ts +19 -3
  93. package/src/sandbox/policy.ts +1 -0
  94. package/src/secrets/export-github-cli-store.ts +158 -0
  95. package/src/secrets/index.ts +19 -1
  96. package/src/secrets/provision-github-cli-store.ts +322 -0
  97. package/src/secrets/schema.ts +13 -7
  98. package/src/secrets/storage.ts +30 -0
  99. package/src/shared/index.ts +2 -0
  100. package/src/shared/style-text.ts +13 -0
  101. package/src/skills/typeclaw-channel-github/SKILL.md +24 -12
  102. package/src/skills/typeclaw-config/SKILL.md +3 -1
  103. package/src/skills/typeclaw-github-contributing/SKILL.md +6 -2
  104. package/src/skills/typeclaw-permissions/SKILL.md +11 -22
  105. package/src/usage/report.ts +3 -3
@@ -1,13 +1,14 @@
1
- import { createHmac, timingSafeEqual } from 'node:crypto'
1
+ import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto'
2
2
 
3
+ import { registerOrJoinReplyReviewRound } from '@/channels/github-review-verdict-coordinator'
3
4
  import type { GithubReviewOn } from '@/channels/schema'
4
- import type { InboundMessage } from '@/channels/types'
5
+ import type { GithubReviewFollowupRound, InboundMessage } from '@/channels/types'
5
6
 
6
7
  import { describeError } from '../../describe-error'
7
8
  import type { GithubAuthContext } from './auth'
8
9
  import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
9
10
  import { removeRequestedReviewer } from './decoy-reviewer'
10
- import type { DeliveryDedup } from './dedup'
11
+ import { createBoundedMap, type BoundedMap, type DeliveryDedup } from './dedup'
11
12
  import { isGithubEventAllowed } from './event-allowlist'
12
13
  import { encodeGithubReactionRef, type GithubReactionTarget } from './reactions'
13
14
  import { fetchSelfReviewBlocking } from './review-state'
@@ -48,7 +49,9 @@ export type GithubWebhookHandlerOptions = {
48
49
  // Schedules the decoy-drop off the webhook ACK path so the 200 stays fast.
49
50
  // Defaults to fire-and-forget; tests inject a recorder to await the task.
50
51
  scheduleBackgroundTask?: (task: () => Promise<void>) => void
52
+ sleepImpl?: (ms: number) => Promise<void>
51
53
  fetchImpl?: typeof fetch
54
+ generateReviewRoundId?: () => string
52
55
  }
53
56
 
54
57
  export function createGithubWebhookHandler(options: GithubWebhookHandlerOptions): (req: Request) => Promise<Response> {
@@ -85,21 +88,23 @@ export async function processVerifiedGithubDelivery(
85
88
  input: { event: string; delivery: string; payload: Record<string, unknown> },
86
89
  ): Promise<void> {
87
90
  const { event, delivery, payload } = input
88
- if (delivery !== '') {
91
+ const action = readString(payload, 'action')
92
+ const isSynchronize = event === 'pull_request' && action === 'synchronize'
93
+ if (!isSynchronize && delivery !== '') {
89
94
  if (options.dedup.has(delivery)) {
90
95
  options.logger.info(`[github] duplicate delivery ignored id=${delivery}`)
91
96
  return
92
97
  }
93
98
  // Reserve the delivery id synchronously, BEFORE the awaits below, so a live
94
99
  // webhook and the recovery sweep can never both clear the dedup gate for the
95
- // same event and route it twice. JS is single-threaded: nothing else runs
96
- // between this has-check and add, so the reservation is atomic. The awaits
97
- // and classify that follow are all throw-safe, so reserving early cannot
98
- // strand a routable event.
100
+ // same event and route it twice. Synchronize uses its own synchronous,
101
+ // releasable head-SHA reservation so a failed redelivery can retry. JS is
102
+ // single-threaded: nothing else runs between this has-check and add, so the
103
+ // reservation is atomic. The awaits and classify that follow are all
104
+ // throw-safe, so reserving early cannot strand a routable event.
99
105
  options.dedup.add(delivery)
100
106
  }
101
107
 
102
- const action = readString(payload, 'action')
103
108
  if (!isGithubEventAllowed(options.allowlist(), event, action)) return
104
109
 
105
110
  const selfId = options.selfId()
@@ -121,13 +126,14 @@ export async function processVerifiedGithubDelivery(
121
126
  // so it runs OFF the ACK path (like the decoy-reviewer drop) and only wakes a
122
127
  // session when an obligation is outstanding. Returning here also keeps
123
128
  // synchronize out of the generic awareness-only fallthrough below.
124
- if (event === 'pull_request' && action === 'synchronize') {
129
+ if (isSynchronize) {
125
130
  scheduleReviewFollowup({ payload, selfLogin, options })
126
131
  return
127
132
  }
128
133
 
129
134
  const teamIsBotMember = await resolveTeamMembership(event, payload, options)
130
135
  const reviewCommentParent = await resolveReviewCommentParent(event, payload, selfId, selfLogin, options)
136
+ const replyReviewRound = await resolveReplyReviewRound(event, payload, selfLogin, reviewCommentParent, options)
131
137
  const classified = classifyGithubInbound(event, payload, selfLogin, {
132
138
  teamIsBotMember,
133
139
  authType: options.authType?.() ?? 'pat',
@@ -136,7 +142,12 @@ export async function processVerifiedGithubDelivery(
136
142
  })
137
143
  if (classified === null) return
138
144
 
139
- options.route(withApprovalPolicy(classified, options.allowApprove?.() ?? true))
145
+ options.route(
146
+ withApprovalPolicy(
147
+ replyReviewRound === null ? classified : { ...classified, githubReviewRound: replyReviewRound },
148
+ options.allowApprove?.() ?? true,
149
+ ),
150
+ )
140
151
  }
141
152
 
142
153
  export const PR_APPROVAL_DISABLED_NOTE =
@@ -145,15 +156,28 @@ export const PR_APPROVAL_DISABLED_NOTE =
145
156
  'verdict is `approve`, submit a `COMMENT` review instead of `APPROVE` — post ' +
146
157
  'the findings, but never formally approve.'
147
158
 
159
+ // The generic note's "submit a COMMENT instead of APPROVE" advice is wrong for a
160
+ // blocking re-review round: a COMMENT does not supersede a standing
161
+ // CHANGES_REQUESTED, so following it posts a non-decisive comment, never trips
162
+ // the dismissal guard, and strands the round with every sibling gated. This note
163
+ // is appended AFTER followupInstruction, so the generic wording would also be the
164
+ // last instruction the model reads and would win over the dismissal directive.
165
+ export const PR_APPROVAL_DISABLED_BLOCKING_NOTE =
166
+ 'Operator policy: PR approval is disabled for this agent ' +
167
+ '(`channels.github.review.approve: false`). Never submit an `APPROVE` review. ' +
168
+ 'To clear your standing `CHANGES_REQUESTED` on this re-review, DISMISS it — a ' +
169
+ '`COMMENT` review does not clear the block and leaves this follow-up round stranded.'
170
+
148
171
  // Gating PR approval lives here (inbound text), not at the bash layer: the
149
172
  // review is posted via `gh api --input <file>`, so the `event: APPROVE` value
150
173
  // sits in a temp file the gh-cli-auth command interceptor never inspects. The
151
174
  // note rides on every inbound (cheap: one line, only when an operator has
152
175
  // opted out) so it reaches the agent for both webhook review requests and
153
176
  // plain-language "@bot review this" asks, which arrive on arbitrary inbounds.
154
- function withApprovalPolicy(message: InboundMessage, allowApprove: boolean): InboundMessage {
177
+ function withApprovalPolicy(message: InboundMessage, allowApprove: boolean, carriesBlocking = false): InboundMessage {
155
178
  if (allowApprove) return message
156
- const text = message.text === '' ? PR_APPROVAL_DISABLED_NOTE : `${message.text}\n\n${PR_APPROVAL_DISABLED_NOTE}`
179
+ const note = carriesBlocking ? PR_APPROVAL_DISABLED_BLOCKING_NOTE : PR_APPROVAL_DISABLED_NOTE
180
+ const text = message.text === '' ? note : `${message.text}\n\n${note}`
157
181
  return { ...message, text }
158
182
  }
159
183
 
@@ -214,6 +238,38 @@ function defaultScheduleBackgroundTask(task: () => Promise<void>): void {
214
238
  void task().catch(() => {})
215
239
  }
216
240
 
241
+ const MAX_REVIEW_FOLLOWUP_ATTEMPTS = 3
242
+ const REVIEW_FOLLOWUP_RETRY_BASE_MS = 1000
243
+ const REVIEW_FOLLOWUP_DEDUP_LIMIT = 1000
244
+
245
+ function defaultSleep(ms: number): Promise<void> {
246
+ return new Promise((resolve) => setTimeout(resolve, ms))
247
+ }
248
+
249
+ type ReviewFollowupDedupState = {
250
+ reservations: BoundedMap<string, 'pending' | 'completed'>
251
+ failures: BoundedMap<string, number>
252
+ }
253
+
254
+ // This state cannot live in createGithubWebhookHandler's closure because the
255
+ // exported processVerifiedGithubDelivery core is also called directly by the
256
+ // recovery sweep. Keying by the shared options identity gives both paths one
257
+ // handler-scoped state while allowing it to be garbage-collected. It stays
258
+ // separate from options.dedup because that add-only delivery cache has no
259
+ // release path, which would recreate the transient-failure retry hole here.
260
+ const reviewFollowupDedupByHandler = new WeakMap<GithubWebhookHandlerOptions, ReviewFollowupDedupState>()
261
+
262
+ function reviewFollowupDedup(options: GithubWebhookHandlerOptions): ReviewFollowupDedupState {
263
+ const existing = reviewFollowupDedupByHandler.get(options)
264
+ if (existing !== undefined) return existing
265
+ const created: ReviewFollowupDedupState = {
266
+ reservations: createBoundedMap(REVIEW_FOLLOWUP_DEDUP_LIMIT),
267
+ failures: createBoundedMap(REVIEW_FOLLOWUP_DEDUP_LIMIT),
268
+ }
269
+ reviewFollowupDedupByHandler.set(options, created)
270
+ return created
271
+ }
272
+
217
273
  function scheduleReviewFollowup(input: {
218
274
  payload: Record<string, unknown>
219
275
  selfLogin: string | null
@@ -239,15 +295,20 @@ function scheduleReviewFollowup(input: {
239
295
  options.logger.warn(`[github] synchronize for ${repository.owner}/${repository.name}#${pullNumber} has no head sha`)
240
296
  return
241
297
  }
242
- const followupKey = `synchronize-followup:${repository.owner}/${repository.name}#${pullNumber}:${headSha}`
243
- if (options.dedup.has(followupKey)) return
244
- options.dedup.add(followupKey)
298
+ const followupKey = `${repository.owner}/${repository.name}#${pullNumber}:${headSha}`
299
+ const followupDedup = reviewFollowupDedup(options)
300
+ if (followupDedup.reservations.has(followupKey)) return
301
+ if ((followupDedup.failures.get(followupKey) ?? 0) >= MAX_REVIEW_FOLLOWUP_ATTEMPTS) return
302
+ followupDedup.reservations.set(followupKey, 'pending')
245
303
 
246
304
  const reviewOn = options.reviewOn?.() ?? 'review_requested'
247
305
  const fetchImpl = options.fetchImpl ?? fetch
248
306
  const schedule = options.scheduleBackgroundTask ?? defaultScheduleBackgroundTask
307
+ const sleepImpl = options.sleepImpl ?? defaultSleep
308
+ const generateReviewRoundId = options.generateReviewRoundId ?? randomUUID
249
309
  const target = `${repository.owner}/${repository.name}#${pullNumber}`
250
- schedule(async () => {
310
+
311
+ const runFollowupAttempt = async (): Promise<'completed' | 'retry'> => {
251
312
  try {
252
313
  const token = await authToken({ repoSlug: `${repository.owner}/${repository.name}` })
253
314
  const threads = await listUnresolvedSelfReviewThreads({
@@ -260,7 +321,7 @@ function scheduleReviewFollowup(input: {
260
321
  })
261
322
  if (!threads.ok) {
262
323
  options.logger.warn(`[github] review-thread recheck failed for ${target}: ${threads.error}`)
263
- return
324
+ return 'retry'
264
325
  }
265
326
 
266
327
  // A held CHANGES_REQUESTED is the bot's own obligation regardless of how
@@ -276,26 +337,94 @@ function scheduleReviewFollowup(input: {
276
337
  fetchImpl,
277
338
  })
278
339
  if (blocking.ok) selfBlocking = blocking.selfBlocking
279
- else options.logger.warn(`[github] review-state recheck failed for ${target}: ${blocking.error}`)
340
+ else {
341
+ options.logger.warn(`[github] review-state recheck failed for ${target}: ${blocking.error}`)
342
+ // Thread and verdict obligations form one follow-up attempt. Routing
343
+ // only the known threads would mark this SHA complete and permanently
344
+ // lose a blocking-review obligation, so fail the whole attempt and let
345
+ // the scheduled job retry both lookups before anything is routed.
346
+ return 'retry'
347
+ }
348
+ }
349
+
350
+ if (threads.threads.length === 0) {
351
+ if (selfBlocking) {
352
+ const round = buildReviewRound(repository, pullNumber, headSha, null, generateReviewRoundId)
353
+ options.route(
354
+ withApprovalPolicy(
355
+ buildReviewFollowupInbound({
356
+ repository,
357
+ pullNumber,
358
+ headSha,
359
+ thread: null,
360
+ selfBlocking: true,
361
+ round,
362
+ title: readString(pr, 'title'),
363
+ }),
364
+ options.allowApprove?.() ?? true,
365
+ true,
366
+ ),
367
+ )
368
+ }
369
+ return 'completed'
280
370
  }
281
371
 
282
- if (threads.threads.length === 0 && !selfBlocking) return
283
- options.route(
284
- withApprovalPolicy(
285
- buildReviewFollowupInbound({
372
+ const round = selfBlocking
373
+ ? buildReviewRound(
286
374
  repository,
287
375
  pullNumber,
288
376
  headSha,
289
- threads: threads.threads,
290
- selfBlocking,
291
- title: readString(pr, 'title'),
292
- }),
293
- options.allowApprove?.() ?? true,
294
- ),
295
- )
377
+ String(threads.threads[0]!.rootCommentId),
378
+ generateReviewRoundId,
379
+ )
380
+ : undefined
381
+ for (const [index, thread] of threads.threads.entries()) {
382
+ // Deliver the PR-level blocking obligation through exactly one sibling
383
+ // thread session. A landed verdict is already fanned across every live
384
+ // sibling PR session by injectPrVerdictActivity, while asking all of them
385
+ // to submit it would recreate a cross-session verdict race.
386
+ const carriesBlockingObligation = selfBlocking && index === 0
387
+ options.route(
388
+ withApprovalPolicy(
389
+ buildReviewFollowupInbound({
390
+ repository,
391
+ pullNumber,
392
+ headSha,
393
+ thread,
394
+ selfBlocking: carriesBlockingObligation,
395
+ ...(round !== undefined ? { round } : {}),
396
+ title: readString(pr, 'title'),
397
+ }),
398
+ options.allowApprove?.() ?? true,
399
+ carriesBlockingObligation,
400
+ ),
401
+ )
402
+ }
403
+ return 'completed'
296
404
  } catch (err) {
297
405
  options.logger.warn(`[github] review followup failed for ${target}: ${describeError(err)}`)
406
+ return 'retry'
298
407
  }
408
+ }
409
+
410
+ schedule(async () => {
411
+ for (let attempt = 1; attempt <= MAX_REVIEW_FOLLOWUP_ATTEMPTS; attempt += 1) {
412
+ if ((await runFollowupAttempt()) === 'completed') {
413
+ followupDedup.reservations.set(followupKey, 'completed')
414
+ followupDedup.failures.delete(followupKey)
415
+ return
416
+ }
417
+ if (attempt < MAX_REVIEW_FOLLOWUP_ATTEMPTS) {
418
+ await sleepImpl(REVIEW_FOLLOWUP_RETRY_BASE_MS * 2 ** (attempt - 1))
419
+ }
420
+ }
421
+
422
+ followupDedup.reservations.delete(followupKey)
423
+ const failures = (followupDedup.failures.get(followupKey) ?? 0) + MAX_REVIEW_FOLLOWUP_ATTEMPTS
424
+ followupDedup.failures.set(followupKey, failures)
425
+ options.logger.warn(
426
+ `[github] review followup retry cap exhausted for ${target} head=${headSha} attempts=${failures}; a new head or adapter restart is required to retry`,
427
+ )
299
428
  })
300
429
  }
301
430
 
@@ -303,23 +432,25 @@ function buildReviewFollowupInbound(input: {
303
432
  repository: { owner: string; name: string }
304
433
  pullNumber: number
305
434
  headSha: string
306
- threads: readonly UnresolvedSelfReviewThread[]
435
+ thread: UnresolvedSelfReviewThread | null
307
436
  selfBlocking: boolean
437
+ round?: GithubReviewFollowupRound
308
438
  title: string | null
309
439
  }): InboundMessage {
310
- const { repository, pullNumber, headSha, threads, selfBlocking, title } = input
440
+ const { repository, pullNumber, headSha, thread, selfBlocking, round, title } = input
311
441
  const titleSegment = title !== null && title.trim() !== '' ? `: "${title}"` : ''
312
442
  const text =
313
443
  `PR #${pullNumber}${titleSegment} received new commits (now at ${headSha.slice(0, 7)}). ` +
314
- followupInstruction(threads, selfBlocking)
444
+ followupInstruction(thread, selfBlocking)
315
445
 
316
446
  return {
317
447
  adapter: 'github',
318
448
  workspace: `${repository.owner}/${repository.name}`,
319
449
  chat: `pr:${pullNumber}`,
320
- thread: null,
450
+ thread: thread === null ? null : String(thread.rootCommentId),
451
+ ...(round !== undefined ? { githubReviewRound: round } : {}),
321
452
  text,
322
- externalMessageId: `pr-${pullNumber}-recheck-${headSha}`,
453
+ externalMessageId: `pr-${pullNumber}-recheck-${headSha}${thread === null ? '' : `-thread-${thread.rootCommentId}`}`,
323
454
  authorId: 'github-system',
324
455
  authorName: 'github',
325
456
  authorIsBot: false,
@@ -332,25 +463,41 @@ function buildReviewFollowupInbound(input: {
332
463
  }
333
464
  }
334
465
 
335
- function followupInstruction(threads: readonly UnresolvedSelfReviewThread[], selfBlocking: boolean): string {
466
+ function buildReviewRound(
467
+ repository: { owner: string; name: string },
468
+ prNumber: number,
469
+ headSha: string,
470
+ carrierThread: string | null,
471
+ generateRoundId: () => string,
472
+ ): GithubReviewFollowupRound {
473
+ return {
474
+ kind: 'push',
475
+ roundId: generateRoundId(),
476
+ workspace: `${repository.owner}/${repository.name}`,
477
+ prNumber,
478
+ headSha,
479
+ carrierThread,
480
+ }
481
+ }
482
+
483
+ function followupInstruction(thread: UnresolvedSelfReviewThread | null, selfBlocking: boolean): string {
336
484
  const threadPart =
337
- threads.length > 0
338
- ? `You have ${threads.length} unresolved review thread(s) you authored on this PR. ` +
339
- `For each, check whether the new commits addressed your concern, then act on THAT thread ` +
340
- `by passing its root comment id as \`thread\` to channel_send: if addressed, reply with a short ` +
341
- `acknowledgement and resolve_review_thread: true; if not, reply with resolve_review_thread: false ` +
342
- `(or leave it). Use the id — not the file/line — as \`thread\`; the file/line is only to tell the ` +
343
- `threads apart:\n${threads.map(renderThreadLine).join('\n')}\n`
485
+ thread !== null
486
+ ? `This session is scoped to one unresolved review thread you authored. Check whether the new commits ` +
487
+ `addressed its concern. If addressed, use channel_reply with a short acknowledgement and ` +
488
+ `resolve_review_thread: true; if not, reply with resolve_review_thread: false (or leave it):\n` +
489
+ `${renderThreadLine(thread)}\n`
344
490
  : ''
345
491
  // A held CHANGES_REQUESTED never clears itself: GitHub keeps the block until a
346
- // fresh APPROVE/COMMENT/dismiss, so a blocking follow-up must always end with a
492
+ // fresh APPROVE or dismissal, so a blocking follow-up must always end with a
347
493
  // submitted verdict — the "end without replying" escape hatch is reserved for
348
494
  // the thread-only path, where leaving every thread open is a valid no-op.
349
495
  const blockingPart = selfBlocking
350
496
  ? `Your latest review on this PR is still CHANGES_REQUESTED, which keeps the PR blocked until you ` +
351
497
  `submit a fresh review. Re-review the current head against the concerns from that blocking review ` +
352
- `and always end with a new verdict: if the commits resolve your concerns, submit an APPROVE ` +
353
- `(or COMMENT if approval is disabled) to clear the block; if concerns remain, submit a new ` +
498
+ `and always end with a new verdict: if the commits resolve your concerns, submit an APPROVE when ` +
499
+ `approval is enabled, or DISMISS your prior CHANGES_REQUESTED when approval is disabled; if concerns ` +
500
+ `remain, submit a new ` +
354
501
  `CHANGES_REQUESTED explaining what is still blocking. `
355
502
  : ''
356
503
  const tail = selfBlocking ? '' : 'If none are addressed, end your turn without replying.'
@@ -979,6 +1126,54 @@ async function resolveReviewCommentParent(
979
1126
  }
980
1127
  }
981
1128
 
1129
+ async function resolveReplyReviewRound(
1130
+ event: string,
1131
+ payload: Record<string, unknown>,
1132
+ selfLogin: string | null,
1133
+ parent: ReviewCommentParent | null,
1134
+ options: GithubWebhookHandlerOptions,
1135
+ ): Promise<GithubReviewFollowupRound | null> {
1136
+ if (event !== 'pull_request_review_comment' || parent?.isSelf !== true || selfLogin === null) return null
1137
+ const comment = readRecord(payload.comment)
1138
+ const parentId = readNumber(comment, 'in_reply_to_id')
1139
+ if (parentId === null || parent.parentId !== parentId) return null
1140
+ const repository = readRepository(payload)
1141
+ const pr = readRecord(payload.pull_request)
1142
+ const prNumber = readNumber(pr, 'number')
1143
+ const headSha = readString(readRecord(pr?.head), 'sha')
1144
+ const authToken = options.authToken
1145
+ if (repository === null || prNumber === null || headSha === null || authToken === undefined) return null
1146
+
1147
+ const target = `${repository.owner}/${repository.name}#${prNumber}`
1148
+ try {
1149
+ const token = await authToken({ repoSlug: `${repository.owner}/${repository.name}` })
1150
+ const blocking = await fetchSelfReviewBlocking({
1151
+ token,
1152
+ selfLogin,
1153
+ owner: repository.owner,
1154
+ repo: repository.name,
1155
+ prNumber,
1156
+ fetchImpl: options.fetchImpl ?? fetch,
1157
+ })
1158
+ if (!blocking.ok) {
1159
+ options.logger.warn(`[github] reply review-state lookup failed for ${target}: ${blocking.error}`)
1160
+ return null
1161
+ }
1162
+ if (!blocking.selfBlocking || blocking.selfBlockingReviewId === null) return null
1163
+ return registerOrJoinReplyReviewRound({
1164
+ workspace: `${repository.owner}/${repository.name}`,
1165
+ prNumber,
1166
+ headSha,
1167
+ blockingReviewId: blocking.selfBlockingReviewId,
1168
+ thread: String(parentId),
1169
+ generateRoundId: options.generateReviewRoundId ?? randomUUID,
1170
+ })
1171
+ } catch (err) {
1172
+ options.logger.warn(`[github] reply review-state lookup failed for ${target}: ${describeError(err)}`)
1173
+ return null
1174
+ }
1175
+ }
1176
+
982
1177
  function readRepository(payload: Record<string, unknown>): { owner: string; name: string } | null {
983
1178
  const repository = readRecord(payload.repository)
984
1179
  const owner = readRecord(repository?.owner)
@@ -39,10 +39,12 @@ export function createGithubReviewStateResolver(deps: {
39
39
  if (!reviews.ok) return { ok: false, error: reviews.error, code: reviews.code }
40
40
  if (!reviewDecision.ok) return { ok: false, error: reviewDecision.error, code: reviewDecision.code }
41
41
 
42
- const lastDecisive = reviews.states.filter(isDecisive).at(-1) ?? null
42
+ const lastDecisive = reviews.reviews.filter((review) => isDecisive(review.state)).at(-1) ?? null
43
+ const selfBlocking = lastDecisive?.state === 'CHANGES_REQUESTED'
43
44
  return {
44
45
  ok: true,
45
- selfBlocking: lastDecisive === 'CHANGES_REQUESTED',
46
+ selfBlocking,
47
+ selfBlockingReviewId: selfBlocking ? lastDecisive.id : null,
46
48
  approve,
47
49
  ...(reviewDecision.reviewDecision !== null ? { reviewDecision: reviewDecision.reviewDecision } : {}),
48
50
  }
@@ -50,7 +52,7 @@ export function createGithubReviewStateResolver(deps: {
50
52
  }
51
53
 
52
54
  export type SelfReviewBlockingResult =
53
- | { ok: true; selfBlocking: boolean }
55
+ | { ok: true; selfBlocking: boolean; selfBlockingReviewId: number | null }
54
56
  | { ok: false; error: string; code: 'not-found' | 'permission-denied' | 'transient' }
55
57
 
56
58
  // Last DECISIVE self review == CHANGES_REQUESTED? (COMMENTED/PENDING ignored, as
@@ -72,8 +74,9 @@ export async function fetchSelfReviewBlocking(deps: {
72
74
  deps.selfLogin,
73
75
  )
74
76
  if (!reviews.ok) return { ok: false, error: reviews.error, code: reviews.code }
75
- const lastDecisive = reviews.states.filter(isDecisive).at(-1) ?? null
76
- return { ok: true, selfBlocking: lastDecisive === 'CHANGES_REQUESTED' }
77
+ const lastDecisive = reviews.reviews.filter((review) => isDecisive(review.state)).at(-1) ?? null
78
+ const selfBlocking = lastDecisive?.state === 'CHANGES_REQUESTED'
79
+ return { ok: true, selfBlocking, selfBlockingReviewId: selfBlocking ? lastDecisive.id : null }
77
80
  }
78
81
 
79
82
  type Target = { owner: string; repo: string; prNumber: number }
@@ -89,7 +92,7 @@ function parseTarget(workspace: string, chat: string): Target | null {
89
92
  }
90
93
 
91
94
  type SelfReviewsResult =
92
- | { ok: true; states: string[] }
95
+ | { ok: true; reviews: Array<{ state: string; id: number | null }> }
93
96
  | { ok: false; error: string; code: 'not-found' | 'permission-denied' | 'transient' }
94
97
 
95
98
  type ReviewDecision = 'APPROVED' | 'CHANGES_REQUESTED' | 'REVIEW_REQUIRED'
@@ -104,7 +107,7 @@ async function fetchSelfReviews(
104
107
  target: Target,
105
108
  selfLogin: string,
106
109
  ): Promise<SelfReviewsResult> {
107
- const states: string[] = []
110
+ const reviews: Array<{ state: string; id: number | null }> = []
108
111
  let url: string | null =
109
112
  `${GITHUB_API_BASE}/repos/${target.owner}/${target.repo}/pulls/${target.prNumber}/reviews?per_page=100`
110
113
  while (url !== null) {
@@ -130,11 +133,12 @@ async function fetchSelfReviews(
130
133
  if (login === null) continue
131
134
  const isBot = row.user?.type === 'Bot'
132
135
  if (!isSelfReviewer(login, isBot, selfLogin)) continue
133
- states.push(row.state)
136
+ const id = typeof row.id === 'number' && Number.isSafeInteger(row.id) && row.id > 0 ? row.id : null
137
+ reviews.push({ state: row.state, id })
134
138
  }
135
139
  url = nextLink(response.headers.get('link'))
136
140
  }
137
- return { ok: true, states }
141
+ return { ok: true, reviews }
138
142
  }
139
143
 
140
144
  async function fetchReviewDecision(
@@ -57,33 +57,65 @@ export function createGithubReviewThreadResolver(deps: {
57
57
  }
58
58
  }
59
59
 
60
- const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
61
- const lookup = await findThread(fetchImpl, token, target)
62
- if (lookup.kind === 'error') return lookup.result
63
- if (lookup.kind === 'absent') {
64
- return {
65
- ok: false,
66
- error: `no review thread rooted at comment ${target.rootCommentId} on ${req.chat}`,
67
- code: 'no-match',
60
+ return await withThreadLock(threadLockKey(target), async () => {
61
+ const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
62
+ const lookup = await findThread(fetchImpl, token, target)
63
+ if (lookup.kind === 'error') return lookup.result
64
+ if (lookup.kind === 'absent') {
65
+ return {
66
+ ok: false,
67
+ error: `no review thread rooted at comment ${target.rootCommentId} on ${req.chat}`,
68
+ code: 'no-match',
69
+ }
68
70
  }
69
- }
70
71
 
71
- const thread = lookup.thread
72
- // The load-bearing guard: only the bot may resolve the bot's own thread.
73
- // Resolving a human reviewer's thread would erase their open question.
74
- if (!isSelfAuthor(thread, selfLogin)) {
75
- return {
76
- ok: false,
77
- error: `refusing to resolve thread authored by @${thread.rootAuthorLogin ?? 'unknown'} (not @${selfLogin})`,
78
- code: 'not-author',
72
+ const thread = lookup.thread
73
+ // The load-bearing guard: only the bot may resolve the bot's own thread.
74
+ // Resolving a human reviewer's thread would erase their open question.
75
+ if (!isSelfAuthor(thread, selfLogin)) {
76
+ return {
77
+ ok: false,
78
+ error: `refusing to resolve thread authored by @${thread.rootAuthorLogin ?? 'unknown'} (not @${selfLogin})`,
79
+ code: 'not-author',
80
+ }
79
81
  }
80
- }
81
- if (thread.isResolved) return { ok: true, alreadyResolved: true }
82
+ if (thread.isResolved) return { ok: true, alreadyResolved: true }
82
83
 
83
- return await runResolveMutation(fetchImpl, token, thread.id)
84
+ return await runResolveMutation(fetchImpl, token, thread.id)
85
+ })
84
86
  }
85
87
  }
86
88
 
89
+ // `alreadyResolved` is only observable from the pre-mutation lookup, so two
90
+ // callers that each see the thread open would both mutate and both post an
91
+ // acknowledgement. Serializing per thread makes the follower's lookup run after
92
+ // the leader's mutation, so it observes `isResolved` and reports the no-op
93
+ // instead. Resolved state is never cached — GitHub stays the authority, which is
94
+ // what keeps this correct across processes and restarts.
95
+ const threadResolveLocks = new Map<string, Promise<void>>()
96
+
97
+ function threadLockKey(target: ResolveTarget): string {
98
+ return `${target.owner}/${target.repo}#${target.prNumber}:${target.rootCommentId}`
99
+ }
100
+
101
+ // Deliberately NOT a bounded/evicting map: dropping an in-flight key would let a
102
+ // second caller enter the critical section concurrently and reopen the race this
103
+ // closes. Entries are deleted once their tail settles, so the map stays bounded
104
+ // by the number of resolves actually in flight.
105
+ function withThreadLock<T>(key: string, run: () => Promise<T>): Promise<T> {
106
+ const previous = threadResolveLocks.get(key) ?? Promise.resolve()
107
+ const result = previous.then(run)
108
+ const tail = result.then(
109
+ () => undefined,
110
+ () => undefined,
111
+ )
112
+ threadResolveLocks.set(key, tail)
113
+ void tail.then(() => {
114
+ if (threadResolveLocks.get(key) === tail) threadResolveLocks.delete(key)
115
+ })
116
+ return result
117
+ }
118
+
87
119
  // A GitHub App's own login differs across the two APIs this guard straddles:
88
120
  // REST `getSelf` returns `slug[bot]` (selfLogin) but GraphQL's `Bot` author node
89
121
  // returns the bare `slug` (rootAuthorLogin). Strict `===` thus refused the App's