typeclaw 0.48.13 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -1,10 +1,21 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ import { z } from 'zod'
4
+
1
5
  import type { GithubReviewOn } from '@/channels/schema'
2
- import type { InboundMessage } from '@/channels/types'
6
+ import type { InboundMessage, RouteReceipt } from '@/channels/types'
3
7
 
4
8
  import { describeError } from '../../describe-error'
9
+ import { canonicalGithubRepo } from '../../github-repo'
5
10
  import type { GithubAuthContext } from './auth'
6
11
  import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
7
- import { DEFAULT_RECONCILE_COOLDOWN_MS, type ReconcileCooldownStore } from './reconcile-cooldown-store'
12
+ import { followupInstruction } from './inbound'
13
+ import type { PendingReview, PendingReviewStore } from './pending-review-store'
14
+ import {
15
+ DEFAULT_RECONCILE_COOLDOWN_MS,
16
+ type ReconcileCooldownStore,
17
+ type ReconcileReplayReservation,
18
+ } from './reconcile-cooldown-store'
8
19
  import type { TeamMembershipChecker } from './team-membership'
9
20
 
10
21
  // Catches up on review work that a live webhook delivery missed. The github
@@ -26,7 +37,7 @@ export type ReconcileOpenPrsOptions = {
26
37
  selfLogin: string | null
27
38
  authType: 'pat' | 'app'
28
39
  token: (context?: GithubAuthContext) => Promise<string>
29
- route: (message: InboundMessage) => void
40
+ route: (message: InboundMessage) => Promise<RouteReceipt>
30
41
  logger: { info: (m: string) => void; warn: (m: string) => void }
31
42
  // Resolves whether the bot is a member of a requested team, gating
32
43
  // team-requested reviews under review.on 'review_requested' (mirrors the
@@ -36,16 +47,228 @@ export type ReconcileOpenPrsOptions = {
36
47
  fetchImpl?: typeof fetch
37
48
  // When provided, a PR that still needs review is replayed at most once per
38
49
  // `cooldownMs`, keyed durably by `repo#prId` so restarts don't re-trigger it.
50
+ // Only a replay the router durably admitted keeps that cooldown; a rejected
51
+ // or non-admitted replay releases it so the next pass retries the PR.
39
52
  // Omitted in tests that assert the raw replay decision.
40
53
  cooldownStore?: ReconcileCooldownStore
41
54
  cooldownMs?: number
55
+ pendingStore?: PendingReviewStore
56
+ // Under review.on 'opened', only PRs created at or after this instant (epoch
57
+ // ms) are replayed. Reconcile catches webhooks missed since the adapter was
58
+ // last alive; without a bound, adding a repo would review its whole backlog.
59
+ createdSince?: number
60
+ // Also replay PRs where the bot's standing CHANGES_REQUESTED predates the
61
+ // current head: a push follow-up a restart killed (or whose synchronize
62
+ // delivery was lost) is never re-sent, so the block would hold until a human
63
+ // pings. Boot-only on purpose: a periodic tick would race a live follow-up
64
+ // re-review still in flight for the same push.
65
+ includeHeldReviews?: boolean
66
+ generateReviewRoundId?: () => string
42
67
  now?: () => number
68
+ // The pass runs detached from adapter start(), so it can outlive stop(). Once
69
+ // cancelled it must not persist cooldowns, route, or prune for a lifecycle
70
+ // that no longer owns the channel.
71
+ isCancelled?: () => boolean
43
72
  }
44
73
 
74
+ // `replayed` counts only replays the router durably admitted (accepted, or a
75
+ // duplicate of an identity it had already admitted).
45
76
  export type ReconcileOutcome = { repo: string; scanned: number; replayed: number } | { repo: string; error: string }
46
77
 
47
78
  const BOT_LOGIN_SUFFIX = '[bot]'
48
79
 
80
+ const pendingPullSchema = z.object({
81
+ number: z.number(),
82
+ id: z.number(),
83
+ state: z.enum(['open', 'closed']),
84
+ draft: z.boolean(),
85
+ title: z.string(),
86
+ user: z.object({ login: z.string(), id: z.number(), type: z.string() }),
87
+ head: z.object({ sha: z.string(), ref: z.string().optional() }),
88
+ base: z.object({ ref: z.string().optional() }).optional(),
89
+ updated_at: z.string().optional(),
90
+ })
91
+
92
+ const submittedReviewsSchema = z.array(
93
+ z.object({
94
+ id: z.number().optional(),
95
+ state: z.string(),
96
+ commit_id: z.string().nullable(),
97
+ submitted_at: z.string().nullable(),
98
+ user: z.object({ login: z.string(), type: z.string() }).nullable(),
99
+ }),
100
+ )
101
+
102
+ // This path deliberately does not consult the scan age or launch cooldown. Each
103
+ // boot needs a fresh identity: the previous admission may be the interrupted one.
104
+ export async function replayPendingReviews(
105
+ options: ReconcileOpenPrsOptions & { pendingStore: PendingReviewStore; replayId: string },
106
+ ): Promise<void> {
107
+ if (options.reviewOn === 'off' || options.selfLogin === null) return
108
+ const repos = new Set(options.repos.map(canonicalGithubRepo))
109
+ const fetchImpl = options.fetchImpl ?? fetch
110
+ for (const entry of await options.pendingStore.list()) {
111
+ if (options.isCancelled?.() === true) return
112
+ if (!repos.has(canonicalGithubRepo(entry.repo))) continue
113
+ try {
114
+ const target = parseRepo(entry.repo)
115
+ if (target === null) continue
116
+ const token = await options.token({ repoSlug: entry.repo })
117
+ const url = `${GITHUB_API_BASE}/repos/${target.owner}/${target.repo}/pulls/${entry.prNumber}`
118
+ const response = await fetchImpl(url, { headers: githubJsonHeaders(token) })
119
+ if (!response.ok) throw new Error(`GitHub pending pull ${response.status}`)
120
+ const row = pendingPullSchema.parse(await response.json())
121
+ if (options.isCancelled?.() === true) return
122
+ if (row.state === 'closed' || row.draft) {
123
+ await options.pendingStore.clear(entry.repo, entry.prNumber, entry)
124
+ continue
125
+ }
126
+ // A submission can succeed remotely just before a crash, without either
127
+ // the local completion callback or the self-review webhook being saved.
128
+ let reviewUrl: string | null = `${url}/reviews?per_page=100`
129
+ let done = false
130
+ let latestDecisive: { id?: number; state: string } | undefined
131
+ while (reviewUrl !== null && !done) {
132
+ const reviews = await fetchImpl(reviewUrl, { headers: githubJsonHeaders(token) })
133
+ if (!reviews.ok) throw new Error(`GitHub pending reviews ${reviews.status}`)
134
+ for (const review of submittedReviewsSchema.parse(await reviews.json())) {
135
+ if (review.user === null || !isSelfLogin(review.user.login, review.user.type === 'Bot', options.selfLogin))
136
+ continue
137
+ if (DECISIVE_REVIEW_STATES.has(review.state)) latestDecisive = { id: review.id, state: review.state }
138
+ if (review.state === 'PENDING' || review.submitted_at === null || review.commit_id === null) continue
139
+ if (
140
+ Date.parse(review.submitted_at) < Math.floor(entry.admittedAt / 1000) * 1000 ||
141
+ !Number.isFinite(Date.parse(review.submitted_at))
142
+ )
143
+ continue
144
+ if (await pendingHeadCovered(entry, review.commit_id, token, fetchImpl)) {
145
+ done = true
146
+ break
147
+ }
148
+ }
149
+ reviewUrl = nextLink(reviews.headers.get('link'))
150
+ }
151
+ if (
152
+ !done &&
153
+ entry.kind === 'rereview' &&
154
+ latestDecisive?.state === 'DISMISSED' &&
155
+ latestDecisive.id !== undefined
156
+ ) {
157
+ done = await pendingReviewDismissed(entry, latestDecisive.id, token, fetchImpl)
158
+ }
159
+ if (options.isCancelled?.() === true) return
160
+ if (done) {
161
+ await options.pendingStore.clear(entry.repo, entry.prNumber, entry)
162
+ continue
163
+ }
164
+ // A concurrent live admission may have advanced this obligation while the
165
+ // API reads were in flight. Its live turn owns the newer head.
166
+ const latest = (await options.pendingStore.list()).find(
167
+ (p) => canonicalGithubRepo(p.repo) === canonicalGithubRepo(entry.repo) && p.prNumber === entry.prNumber,
168
+ )
169
+ if (
170
+ latest?.headSha !== entry.headSha ||
171
+ latest.admittedAt !== entry.admittedAt ||
172
+ latest.authorId !== entry.authorId ||
173
+ latest.authorName !== entry.authorName ||
174
+ latest.authorIsBot !== entry.authorIsBot
175
+ )
176
+ continue
177
+ const pr = parsePrRow(row)
178
+ if (pr === null || pr.id !== entry.prId) continue
179
+ if (options.isCancelled?.() === true) return
180
+ await options.route({
181
+ ...buildSyntheticInbound(
182
+ pr,
183
+ target,
184
+ entry.kind,
185
+ options.generateReviewRoundId ?? randomUUID,
186
+ `boot-${options.replayId}`,
187
+ ),
188
+ authorId: entry.authorId,
189
+ authorName: entry.authorName,
190
+ authorIsBot: entry.authorIsBot,
191
+ })
192
+ } catch (error) {
193
+ options.logger.warn(
194
+ `[github] pending review ${entry.repo}#${entry.prNumber} replay failed: ${describeError(error)}`,
195
+ )
196
+ }
197
+ }
198
+ }
199
+
200
+ async function pendingReviewDismissed(
201
+ entry: PendingReview,
202
+ reviewId: number,
203
+ token: string,
204
+ fetchImpl: typeof fetch,
205
+ ): Promise<boolean> {
206
+ let url: string | null = `${GITHUB_API_BASE}/repos/${entry.repo}/issues/${entry.prNumber}/timeline?per_page=100`
207
+ const eventsSchema = z.array(
208
+ z.object({
209
+ event: z.string(),
210
+ created_at: z.string().optional(),
211
+ dismissed_review: z
212
+ .object({
213
+ review_id: z.union([z.string(), z.number()]),
214
+ dismissal_commit_id: z.string().nullable().optional(),
215
+ })
216
+ .optional(),
217
+ }),
218
+ )
219
+ // A dismissed review retains its original commit_id/submitted_at. Only the
220
+ // matching timeline event dates the dismissal itself, including after a crash.
221
+ while (url !== null) {
222
+ const response = await fetchImpl(url, { headers: githubJsonHeaders(token) })
223
+ if (!response.ok) throw new Error(`GitHub pending dismissal timeline ${response.status}`)
224
+ for (const event of eventsSchema.parse(await response.json())) {
225
+ if (event.event !== 'review_dismissed' || String(event.dismissed_review?.review_id) !== String(reviewId)) continue
226
+ const dismissedAt = Date.parse(event.created_at ?? '')
227
+ if (!Number.isFinite(dismissedAt) || dismissedAt < Math.floor(entry.admittedAt / 1000) * 1000) continue
228
+ const commitSha = event.dismissed_review?.dismissal_commit_id
229
+ if (commitSha == null || (await pendingHeadCovered(entry, commitSha, token, fetchImpl))) return true
230
+ }
231
+ url = nextLink(response.headers.get('link'))
232
+ }
233
+ return false
234
+ }
235
+
236
+ // Any submitted state completes logged work, but an old-head review must not
237
+ // erase a newer push. Compare ancestry only when the SHAs differ.
238
+ export async function completePendingReview(
239
+ store: PendingReviewStore,
240
+ submitted: { repo: string; prNumber: number; headSha: string; submittedAt: number },
241
+ token: (context?: GithubAuthContext) => Promise<string>,
242
+ fetchImpl: typeof fetch,
243
+ ): Promise<void> {
244
+ const entry = (await store.list()).find(
245
+ (p) => canonicalGithubRepo(p.repo) === canonicalGithubRepo(submitted.repo) && p.prNumber === submitted.prNumber,
246
+ )
247
+ if (entry === undefined || submitted.submittedAt < Math.floor(entry.admittedAt / 1000) * 1000) return
248
+ if (
249
+ entry.headSha === submitted.headSha ||
250
+ (await pendingHeadCovered(entry, submitted.headSha, await token({ repoSlug: submitted.repo }), fetchImpl))
251
+ ) {
252
+ await store.clear(entry.repo, entry.prNumber, entry)
253
+ }
254
+ }
255
+
256
+ async function pendingHeadCovered(
257
+ entry: PendingReview,
258
+ headSha: string,
259
+ token: string,
260
+ fetchImpl: typeof fetch,
261
+ ): Promise<boolean> {
262
+ if (entry.headSha === headSha) return true
263
+ const response = await fetchImpl(
264
+ `${GITHUB_API_BASE}/repos/${entry.repo}/compare/${encodeURIComponent(entry.headSha)}...${encodeURIComponent(headSha)}`,
265
+ { headers: githubJsonHeaders(token) },
266
+ )
267
+ if (!response.ok) throw new Error(`GitHub pending head comparison ${response.status}`)
268
+ const comparison = z.object({ status: z.string() }).parse(await response.json())
269
+ return comparison.status === 'ahead' || comparison.status === 'identical'
270
+ }
271
+
49
272
  export async function reconcileOpenPrs(options: ReconcileOpenPrsOptions): Promise<ReconcileOutcome[]> {
50
273
  // `off` disables code review entirely, so there is nothing to catch up on.
51
274
  if (options.reviewOn === 'off') return []
@@ -56,6 +279,7 @@ export async function reconcileOpenPrs(options: ReconcileOpenPrsOptions): Promis
56
279
 
57
280
  const outcomes: ReconcileOutcome[] = []
58
281
  for (const repo of new Set(options.repos)) {
282
+ if (options.isCancelled?.() === true) break
59
283
  const target = parseRepo(repo)
60
284
  if (target === null) {
61
285
  outcomes.push({ repo, error: 'malformed repo slug' })
@@ -93,15 +317,25 @@ async function reconcileRepo(
93
317
 
94
318
  let replayed = 0
95
319
  for (const pr of prs) {
96
- const needs = await prNeedsReview({ pr, options, target, token, selfLogin, decoyLogin, fetchImpl })
97
- if (!needs) continue
320
+ // Logged work is retried separately on boot, even when outside the scan
321
+ // window. Never race it with a periodic scan while its review is in flight.
322
+ if (options.pendingStore?.has(repo, pr.number)) continue
323
+ const kind = await prReplayKind({ pr, options, target, token, selfLogin, decoyLogin, fetchImpl })
324
+ if (kind === null) continue
325
+ if (options.isCancelled?.() === true) return { repo, scanned: prs.length, replayed }
326
+ let reservation: ReconcileReplayReservation | null = null
98
327
  if (cooldownStore !== undefined) {
99
- if (cooldownStore.isCoolingDown(repo, pr.id, now(), cooldownMs)) continue
328
+ // Decide only from the store's serialized latest state, never from this
329
+ // instance's cached view: another lifecycle may have released (or taken)
330
+ // the PR's reservation since that view was read. Persisting the
331
+ // reservation before routing means a failed write throws, so we skip the
332
+ // route rather than replay a PR with no durable record.
100
333
  try {
101
- // Persist the marker before routing: if the write fails the marker is
102
- // rolled back and this throws, so we skip the route rather than replay a
103
- // PR with no durable record (a restart would otherwise replay it again).
104
- await cooldownStore.markReplayed(repo, pr.id, now())
334
+ reservation = await cooldownStore.markReplayed(repo, pr.id, {
335
+ now: now(),
336
+ cooldownMs,
337
+ isCancelled: options.isCancelled,
338
+ })
105
339
  } catch (err) {
106
340
  options.logger.warn(
107
341
  `[github] reconcile ${repo}: skipping PR #${pr.number} replay, cooldown persist failed: ${describeError(
@@ -110,18 +344,80 @@ async function reconcileRepo(
110
344
  )
111
345
  continue
112
346
  }
347
+ // null: cancelled while reserving, or another attempt's reservation is
348
+ // still cooling down in the latest persisted state.
349
+ if (reservation === null) {
350
+ if (options.isCancelled?.() === true) return { repo, scanned: prs.length, replayed }
351
+ continue
352
+ }
113
353
  }
114
- options.route(buildSyntheticInbound(pr, target))
115
- replayed += 1
354
+ if (options.isCancelled?.() === true) {
355
+ // Stopped between reserving and dispatching: the replay never launches,
356
+ // so release this attempt's reservation — never a newer one's marker.
357
+ await releaseReservation(options, repo, pr, reservation)
358
+ return { repo, scanned: prs.length, replayed }
359
+ }
360
+ if (await replayPr(options, target, pr, kind, reservation)) replayed += 1
116
361
  }
117
362
 
118
- if (cooldownStore !== undefined) {
363
+ if (cooldownStore !== undefined && options.isCancelled?.() !== true) {
119
364
  await cooldownStore.prune(repo, new Set(prs.map((pr) => pr.id)), now())
120
365
  }
121
366
  return { repo, scanned: prs.length, replayed }
122
367
  }
123
368
 
124
- async function prNeedsReview(input: {
369
+ // Routes one PR's replay in isolation: a rejected route or a receipt that did
370
+ // not durably admit the replay releases only this PR's reservation, and the pass
371
+ // moves on to the next PR. Once routed, the receipt is awaited even if the
372
+ // adapter stops meanwhile: accepted (or duplicate of an identity the router
373
+ // already admitted) keeps the cooldown durable. A rejected local route may have
374
+ // committed its admission before failing; releasing is still safe because the
375
+ // router dedupes the retry against that admission.
376
+ async function replayPr(
377
+ options: ReconcileOpenPrsOptions,
378
+ target: RepoTarget,
379
+ pr: OpenPr,
380
+ kind: ReplayKind,
381
+ reservation: ReconcileReplayReservation | null,
382
+ ): Promise<boolean> {
383
+ const repo = `${target.owner}/${target.repo}`
384
+ let receipt: RouteReceipt
385
+ try {
386
+ receipt = await options.route(
387
+ buildSyntheticInbound(pr, target, kind, options.generateReviewRoundId ?? randomUUID, cooldownWindow(options)),
388
+ )
389
+ } catch (err) {
390
+ options.logger.warn(`[github] reconcile ${repo}: PR #${pr.number} replay failed: ${describeError(err)}`)
391
+ await releaseReservation(options, repo, pr, reservation)
392
+ return false
393
+ }
394
+ if (receipt.kind === 'accepted' || receipt.kind === 'duplicate') return true
395
+ options.logger.info(`[github] reconcile ${repo}: PR #${pr.number} replay not admitted (${receipt.kind})`)
396
+ await releaseReservation(options, repo, pr, reservation)
397
+ return false
398
+ }
399
+
400
+ async function releaseReservation(
401
+ options: ReconcileOpenPrsOptions,
402
+ repo: string,
403
+ pr: OpenPr,
404
+ reservation: ReconcileReplayReservation | null,
405
+ ): Promise<void> {
406
+ if (options.cooldownStore === undefined || reservation === null) return
407
+ try {
408
+ await options.cooldownStore.rollbackReplay(repo, pr.id, reservation.replayId)
409
+ } catch (err) {
410
+ options.logger.warn(
411
+ `[github] reconcile ${repo}: PR #${pr.number} launch cooldown NOT released, so it retries only after the cooldown expires: ${describeError(
412
+ err,
413
+ )}`,
414
+ )
415
+ }
416
+ }
417
+
418
+ type ReplayKind = 'review' | 'rereview'
419
+
420
+ async function prReplayKind(input: {
125
421
  pr: OpenPr
126
422
  options: ReconcileOpenPrsOptions
127
423
  target: RepoTarget
@@ -129,23 +425,46 @@ async function prNeedsReview(input: {
129
425
  selfLogin: string
130
426
  decoyLogin: string | null
131
427
  fetchImpl: typeof fetch
132
- }): Promise<boolean> {
428
+ }): Promise<ReplayKind | null> {
133
429
  const { pr, options, target, token, selfLogin, decoyLogin, fetchImpl } = input
134
- if (isSelfAuthored(pr, selfLogin, decoyLogin)) return false
430
+ if (isSelfAuthored(pr, selfLogin, decoyLogin)) return null
431
+ let summary: SelfReviewSummary | undefined
432
+ const selfReviews = async (): Promise<SelfReviewSummary> =>
433
+ (summary ??= await fetchSelfReviewSummary(fetchImpl, token, target, pr.number, selfLogin))
434
+
435
+ // A held CHANGES_REQUESTED is the bot's own obligation whichever mode woke the
436
+ // first review, mirroring the live synchronize follow-up. It wins over an open
437
+ // review request (an author re-requesting after pushing fixes): only the
438
+ // re-review replay carries the push round a fresh blocking verdict needs.
439
+ if (options.includeHeldReviews === true) {
440
+ const { blockingCommitId } = await selfReviews()
441
+ if (blockingCommitId !== null && pr.headSha !== null && blockingCommitId !== pr.headSha) return 'rereview'
442
+ }
135
443
 
136
444
  if (options.reviewOn === 'review_requested') {
137
445
  // Only the explicit request wakes a review under this mode. A draft can
138
446
  // still carry a request, so draft state is irrelevant here. Mirrors the
139
447
  // live path's `isMeAsUser || isMyTeam`: a direct user request, OR a team
140
448
  // request the bot is a member of.
141
- if (isUserReviewRequestedFromSelf(pr, selfLogin, decoyLogin)) return true
142
- return await isTeamReviewRequestedFromSelf(pr, target, selfLogin, options.isBotInTeam)
449
+ if (isUserReviewRequestedFromSelf(pr, selfLogin, decoyLogin)) return 'review'
450
+ return (await isTeamReviewRequestedFromSelf(pr, target, selfLogin, options.isBotInTeam)) ? 'review' : null
143
451
  }
144
452
 
145
453
  // reviewOn === 'opened': a non-draft PR the bot has not yet reviewed. Draft
146
454
  // PRs wait for the ready_for_review trigger, matching the live-webhook path.
147
- if (pr.draft) return false
148
- return !(await botAlreadyReviewed(fetchImpl, token, target, pr.number, selfLogin))
455
+ if (pr.draft) return null
456
+ // A PR reconcile already replayed stays eligible past the advancing bound: an
457
+ // interrupted replay gets no restart notice, so this pass is its retry path.
458
+ const owedReplay =
459
+ options.cooldownStore?.owesReplay(`${target.owner}/${target.repo}`, pr.id, (options.now ?? Date.now)()) === true
460
+ if (!owedReplay && createdBeforeReplayWindow(pr, options.createdSince)) return null
461
+ return (await selfReviews()).reviewed ? null : 'review'
462
+ }
463
+
464
+ function createdBeforeReplayWindow(pr: OpenPr, createdSince: number | undefined): boolean {
465
+ if (createdSince === undefined) return false
466
+ const createdAt = Date.parse(pr.createdAt)
467
+ return !Number.isNaN(createdAt) && createdAt < createdSince
149
468
  }
150
469
 
151
470
  async function isTeamReviewRequestedFromSelf(
@@ -161,15 +480,39 @@ async function isTeamReviewRequestedFromSelf(
161
480
  return false
162
481
  }
163
482
 
164
- function buildSyntheticInbound(pr: OpenPr, target: RepoTarget): InboundMessage {
483
+ // An interrupted reconcile replay gets no restart notice; its retry is the next
484
+ // pass after the cooldown. Keying the identity by cooldown window lets that pass
485
+ // admit afresh instead of deduping against the interrupted admission, while a
486
+ // retry within the same window (e.g. after a rejected route) still dedupes.
487
+ function cooldownWindow(options: ReconcileOpenPrsOptions): number | null {
488
+ if (options.cooldownStore === undefined) return null
489
+ const cooldownMs = options.cooldownMs ?? DEFAULT_RECONCILE_COOLDOWN_MS
490
+ return Math.floor((options.now ?? Date.now)() / cooldownMs)
491
+ }
492
+
493
+ function buildSyntheticInbound(
494
+ pr: OpenPr,
495
+ target: RepoTarget,
496
+ kind: ReplayKind,
497
+ generateReviewRoundId: () => string,
498
+ window: number | string | null,
499
+ ): InboundMessage {
165
500
  const branchSegment = pr.headRef !== null && pr.baseRef !== null ? ` Branch: ${pr.headRef} → ${pr.baseRef}.` : ''
166
501
  const text =
167
- `@${pr.authorLogin} opened PR #${pr.number}: "${pr.title}".${branchSegment}` +
168
- ' Please review the changes line-by-line and post your feedback.'
169
- // Distinct from the live `pr-<id>-opened-<updatedAt>` id so a replay never
170
- // collides with a real opened delivery, while repeated reconciles for the
171
- // same unchanged PR dedupe against each other (same updatedAt).
172
- const externalMessageId = `pr-${pr.id}-reconcile-${pr.updatedAt}`
502
+ kind === 'rereview' && pr.headSha !== null
503
+ ? `PR #${pr.number}: "${pr.title}" received new commits (now at ${pr.headSha.slice(0, 7)}) since your ` +
504
+ `blocking review, and no re-review of them has been submitted yet. ${followupInstruction(null, true)}`
505
+ : `@${pr.authorLogin} opened PR #${pr.number}: "${pr.title}".${branchSegment}` +
506
+ ' Please review the changes line-by-line and post your feedback.'
507
+ // Distinct from the live `pr-<id>-opened-<updatedAt>` and push follow-up
508
+ // `pr-<n>-recheck-<sha>` ids: a duplicate of the very admission a restart
509
+ // interrupted would be deduped instead of re-run. Repeated reconciles for the
510
+ // same unchanged PR still dedupe against each other (same updatedAt).
511
+ const windowSuffix = window === null ? '' : `-w${window}`
512
+ const externalMessageId =
513
+ kind === 'rereview'
514
+ ? `pr-${pr.id}-reconcile-rereview-${pr.headSha}-${pr.updatedAt}${windowSuffix}`
515
+ : `pr-${pr.id}-reconcile-${pr.updatedAt}${windowSuffix}`
173
516
  return {
174
517
  adapter: 'github',
175
518
  workspace: `${target.owner}/${target.repo}`,
@@ -177,6 +520,27 @@ function buildSyntheticInbound(pr: OpenPr, target: RepoTarget): InboundMessage {
177
520
  thread: null,
178
521
  text,
179
522
  externalMessageId,
523
+ ...(pr.headSha !== null ? { githubPendingReview: { prId: pr.id, headSha: pr.headSha, kind } } : {}),
524
+ // A re-review must land a fresh blocking verdict at the new head, which the
525
+ // verdict coordinator allows over a standing CHANGES_REQUESTED only inside a
526
+ // current-head push round, exactly like the live push follow-up's.
527
+ ...(kind === 'rereview' && pr.headSha !== null
528
+ ? {
529
+ githubReviewRound: {
530
+ kind: 'push' as const,
531
+ roundId: generateReviewRoundId(),
532
+ workspace: `${target.owner}/${target.repo}`,
533
+ prNumber: pr.number,
534
+ headSha: pr.headSha,
535
+ carrierThread: null,
536
+ },
537
+ }
538
+ : {}),
539
+ // Held re-reviews only replay on boot, so unlike a fresh review their retry
540
+ // is not guaranteed by the periodic pass; a distinct kind keeps their
541
+ // restart notice behavior separate from the fresh-review replay's.
542
+ eventKind: kind === 'rereview' ? 'pull_request:reconcile:rereview' : 'pull_request:reconcile',
543
+ revision: pr.updatedAt,
180
544
  authorId: String(pr.authorId),
181
545
  authorName: pr.authorLogin,
182
546
  authorIsBot: pr.authorIsBot,
@@ -200,8 +564,10 @@ type OpenPr = {
200
564
  authorId: number
201
565
  authorIsBot: boolean
202
566
  headRef: string | null
567
+ headSha: string | null
203
568
  baseRef: string | null
204
569
  updatedAt: string
570
+ createdAt: string
205
571
  requestedReviewerLogins: string[]
206
572
  requestedTeamSlugs: string[]
207
573
  }
@@ -232,13 +598,23 @@ async function fetchOpenPrs(fetchImpl: typeof fetch, token: string, target: Repo
232
598
  return prs
233
599
  }
234
600
 
235
- async function botAlreadyReviewed(
601
+ // `blockingCommitId` is the commit of the bot's latest DECISIVE review when that
602
+ // review is CHANGES_REQUESTED. COMMENTED/PENDING never clear the block (see
603
+ // review-state.ts), and the bot's own comment replies post COMMENTED reviews at
604
+ // the new head, so only the decisive review's commit tells whether it was redone.
605
+ type SelfReviewSummary = { reviewed: boolean; blockingCommitId: string | null }
606
+
607
+ const DECISIVE_REVIEW_STATES = new Set(['CHANGES_REQUESTED', 'APPROVED', 'DISMISSED'])
608
+
609
+ async function fetchSelfReviewSummary(
236
610
  fetchImpl: typeof fetch,
237
611
  token: string,
238
612
  target: RepoTarget,
239
613
  prNumber: number,
240
614
  selfLogin: string,
241
- ): Promise<boolean> {
615
+ ): Promise<SelfReviewSummary> {
616
+ let reviewed = false
617
+ let lastDecisive: { state: string; commitId: string | null } | null = null
242
618
  let url: string | null =
243
619
  `${GITHUB_API_BASE}/repos/${target.owner}/${target.repo}/pulls/${prNumber}/reviews?per_page=100`
244
620
  while (url !== null) {
@@ -252,11 +628,17 @@ async function botAlreadyReviewed(
252
628
  for (const row of page) {
253
629
  const login = row.user?.login ?? null
254
630
  if (login === null) continue
255
- if (isSelfLogin(login, row.user?.type === 'Bot', selfLogin)) return true
631
+ if (!isSelfLogin(login, row.user?.type === 'Bot', selfLogin)) continue
632
+ reviewed = true
633
+ if (typeof row.state === 'string' && DECISIVE_REVIEW_STATES.has(row.state))
634
+ lastDecisive = { state: row.state, commitId: typeof row.commit_id === 'string' ? row.commit_id : null }
256
635
  }
257
636
  url = nextLink(response.headers.get('link'))
258
637
  }
259
- return false
638
+ return {
639
+ reviewed,
640
+ blockingCommitId: lastDecisive?.state === 'CHANGES_REQUESTED' ? lastDecisive.commitId : null,
641
+ }
260
642
  }
261
643
 
262
644
  function isUserReviewRequestedFromSelf(pr: OpenPr, selfLogin: string, decoyLogin: string | null): boolean {
@@ -305,14 +687,15 @@ type PrRow = {
305
687
  title?: unknown
306
688
  draft?: unknown
307
689
  updated_at?: unknown
690
+ created_at?: unknown
308
691
  user?: { login?: unknown; id?: unknown; type?: unknown }
309
- head?: { ref?: unknown }
692
+ head?: { ref?: unknown; sha?: unknown }
310
693
  base?: { ref?: unknown }
311
694
  requested_reviewers?: Array<{ login?: unknown }>
312
695
  requested_teams?: Array<{ slug?: unknown }>
313
696
  }
314
697
 
315
- type ReviewRow = { user?: { login?: string; type?: string } }
698
+ type ReviewRow = { state?: unknown; commit_id?: unknown; user?: { login?: string; type?: string } }
316
699
 
317
700
  function parsePrRow(row: PrRow): OpenPr | null {
318
701
  const number = typeof row.number === 'number' ? row.number : null
@@ -328,8 +711,10 @@ function parsePrRow(row: PrRow): OpenPr | null {
328
711
  authorId: typeof row.user?.id === 'number' ? row.user.id : 0,
329
712
  authorIsBot: row.user?.type === 'Bot',
330
713
  headRef: typeof row.head?.ref === 'string' ? row.head.ref : null,
714
+ headSha: typeof row.head?.sha === 'string' ? row.head.sha : null,
331
715
  baseRef: typeof row.base?.ref === 'string' ? row.base.ref : null,
332
716
  updatedAt: typeof row.updated_at === 'string' ? row.updated_at : '',
717
+ createdAt: typeof row.created_at === 'string' ? row.created_at : '',
333
718
  requestedReviewerLogins: (row.requested_reviewers ?? []).flatMap((r) =>
334
719
  typeof r.login === 'string' ? [r.login] : [],
335
720
  ),