typeclaw 0.48.12 → 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 (213) hide show
  1. package/package.json +6 -3
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/attention-escalation.ts +8 -5
  4. package/src/agent/auth-reloadable.ts +2 -3
  5. package/src/agent/auth.ts +59 -79
  6. package/src/agent/compaction.ts +2 -2
  7. package/src/agent/index.ts +173 -85
  8. package/src/agent/live-sessions.ts +2 -2
  9. package/src/agent/live-subagents.ts +1 -0
  10. package/src/agent/llm-replay-sanitizer.ts +1 -1
  11. package/src/agent/model-overrides.ts +1 -1
  12. package/src/agent/multimodal/look-at.ts +3 -3
  13. package/src/agent/multimodal/read-redirect.ts +1 -1
  14. package/src/agent/plugin-tools.ts +76 -39
  15. package/src/agent/prompt-cache-key.ts +42 -0
  16. package/src/agent/provider-error.ts +179 -10
  17. package/src/agent/reload-tool.ts +1 -1
  18. package/src/agent/restart-handoff/index.ts +7 -14
  19. package/src/agent/reviewer-activity.ts +68 -0
  20. package/src/agent/session-origin.ts +33 -0
  21. package/src/agent/subagents.ts +14 -2
  22. package/src/agent/system-prompt.ts +68 -202
  23. package/src/agent/todo/continuation-policy.ts +12 -4
  24. package/src/agent/tool-error-remediation.ts +1 -1
  25. package/src/agent/tool-file-safety.ts +113 -14
  26. package/src/agent/tool-not-found-nudge.ts +1 -1
  27. package/src/agent/tool-result-budget.ts +2 -2
  28. package/src/agent/tools/channel-disengage.ts +2 -2
  29. package/src/agent/tools/channel-edit.ts +2 -2
  30. package/src/agent/tools/channel-fetch-attachment.ts +2 -2
  31. package/src/agent/tools/channel-history-render.ts +2 -1
  32. package/src/agent/tools/channel-history.ts +2 -2
  33. package/src/agent/tools/channel-react.ts +2 -2
  34. package/src/agent/tools/channel-read.ts +2 -2
  35. package/src/agent/tools/channel-reply.ts +25 -7
  36. package/src/agent/tools/channel-send.ts +51 -9
  37. package/src/agent/tools/curl-impersonate.ts +11 -2
  38. package/src/agent/tools/grant-role.ts +2 -2
  39. package/src/agent/tools/post-github-review.ts +79 -17
  40. package/src/agent/tools/restart.ts +2 -2
  41. package/src/agent/tools/skip-response.ts +4 -4
  42. package/src/agent/tools/spawn-subagent.ts +165 -14
  43. package/src/agent/tools/stream-snapshot.ts +2 -2
  44. package/src/agent/tools/subagent-cancel.ts +2 -2
  45. package/src/agent/tools/subagent-output.ts +10 -2
  46. package/src/agent/tools/todo/index.ts +2 -2
  47. package/src/agent/tools/webfetch/tool.ts +2 -2
  48. package/src/agent/tools/websearch.ts +2 -2
  49. package/src/bundled-plugins/backup/README.md +10 -9
  50. package/src/bundled-plugins/backup/runner.ts +140 -58
  51. package/src/bundled-plugins/backup/subagents.ts +58 -26
  52. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  53. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  54. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  55. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  56. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  57. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  58. package/src/bundled-plugins/operator/operator.ts +15 -4
  59. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  60. package/src/bundled-plugins/security/index.ts +50 -2
  61. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  62. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/discord-bot.ts +122 -67
  64. package/src/channels/adapters/discord-reactions.ts +18 -0
  65. package/src/channels/adapters/discord.ts +114 -8
  66. package/src/channels/adapters/github/inbound.ts +103 -8
  67. package/src/channels/adapters/github/index.ts +251 -19
  68. package/src/channels/adapters/github/last-alive.ts +27 -0
  69. package/src/channels/adapters/github/outbound.ts +54 -18
  70. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  71. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  72. package/src/channels/adapters/github/reactions.ts +100 -0
  73. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  74. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  75. package/src/channels/adapters/github/recovery.ts +106 -0
  76. package/src/channels/adapters/github/review-check.ts +510 -0
  77. package/src/channels/adapters/github/review-submitter.ts +34 -2
  78. package/src/channels/adapters/instagram.ts +32 -14
  79. package/src/channels/adapters/kakaotalk.ts +22 -7
  80. package/src/channels/adapters/line.ts +18 -3
  81. package/src/channels/adapters/outbound-account.ts +20 -0
  82. package/src/channels/adapters/own-reactions.ts +66 -0
  83. package/src/channels/adapters/recovery-correlation.ts +214 -0
  84. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  85. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  86. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  87. package/src/channels/adapters/slack-bot.ts +125 -57
  88. package/src/channels/adapters/slack-classify.ts +25 -4
  89. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  90. package/src/channels/adapters/slack-reactions.ts +18 -0
  91. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  92. package/src/channels/adapters/slack.ts +48 -3
  93. package/src/channels/adapters/teams.ts +14 -4
  94. package/src/channels/adapters/telegram-bot.ts +56 -10
  95. package/src/channels/adapters/webex-bot.ts +12 -2
  96. package/src/channels/adapters/webex.ts +12 -2
  97. package/src/channels/background-handoff.ts +434 -0
  98. package/src/channels/background-obligations.ts +893 -0
  99. package/src/channels/continuity-types.ts +271 -0
  100. package/src/channels/github-review-check.ts +598 -0
  101. package/src/channels/github-review-turn-ledger.ts +102 -28
  102. package/src/channels/github-review-verdict-coordinator.ts +96 -13
  103. package/src/channels/github-token-bridge.ts +11 -5
  104. package/src/channels/inbound-journal.ts +1738 -0
  105. package/src/channels/index.ts +6 -1
  106. package/src/channels/manager.ts +17 -7
  107. package/src/channels/recovery-dispatcher.ts +264 -0
  108. package/src/channels/recovery-notice.ts +94 -0
  109. package/src/channels/recovery-outbox.ts +459 -0
  110. package/src/channels/router.ts +2582 -633
  111. package/src/channels/schema.ts +8 -1
  112. package/src/channels/subagent-completion-bridge.ts +17 -14
  113. package/src/channels/types.ts +121 -16
  114. package/src/channels/waiting-reactions.ts +664 -0
  115. package/src/cli/compose.ts +7 -4
  116. package/src/cli/hostd.ts +49 -3
  117. package/src/cli/inspect.ts +11 -14
  118. package/src/cli/model.ts +7 -5
  119. package/src/cli/oauth-callbacks.ts +38 -23
  120. package/src/coding-agent/broker-body.ts +38 -0
  121. package/src/coding-agent/broker.ts +290 -0
  122. package/src/coding-agent/claude.ts +95 -0
  123. package/src/coding-agent/codex.ts +104 -0
  124. package/src/coding-agent/index.ts +506 -0
  125. package/src/coding-agent/omo-state.ts +69 -0
  126. package/src/coding-agent/omo-stream.ts +98 -0
  127. package/src/coding-agent/omo.ts +192 -0
  128. package/src/coding-agent/runner.ts +263 -0
  129. package/src/coding-agent/tool.ts +62 -0
  130. package/src/coding-agent/worktree.ts +355 -0
  131. package/src/compose/restart.ts +10 -3
  132. package/src/compose/start.ts +20 -3
  133. package/src/config/config.ts +70 -26
  134. package/src/config/providers.ts +278 -50
  135. package/src/container/exit-reason.ts +44 -0
  136. package/src/container/index.ts +5 -0
  137. package/src/container/log-archive.ts +51 -13
  138. package/src/container/memory-limit.ts +1 -1
  139. package/src/container/memory-oversubscription.ts +36 -6
  140. package/src/container/oom-events.ts +86 -0
  141. package/src/container/restart.ts +2 -0
  142. package/src/container/shared.ts +8 -1
  143. package/src/container/start.ts +25 -13
  144. package/src/container/stop.ts +6 -2
  145. package/src/container/tool-oom-priority.ts +32 -0
  146. package/src/cron/consumer.ts +10 -4
  147. package/src/cron/reloadable.ts +23 -2
  148. package/src/doctor/checks.ts +14 -2
  149. package/src/hostd/daemon.ts +20 -10
  150. package/src/hostd/spawn.ts +106 -5
  151. package/src/hostd/version.ts +20 -0
  152. package/src/hostd/watchdog.ts +241 -0
  153. package/src/init/dockerfile.ts +57 -592
  154. package/src/init/index.ts +6 -7
  155. package/src/init/oauth-login.ts +57 -17
  156. package/src/inspect/transcript-view.ts +6 -3
  157. package/src/mcp/client.ts +3 -1
  158. package/src/operations/classify-tool-outcome.ts +45 -1
  159. package/src/operations/incidents.ts +10 -5
  160. package/src/plugin/core-tool-names.ts +1 -1
  161. package/src/plugin/define.ts +1 -0
  162. package/src/plugin/index.ts +1 -0
  163. package/src/plugin/types.ts +6 -1
  164. package/src/run/background-handoff-boot.ts +86 -0
  165. package/src/run/channel-session-factory.ts +5 -4
  166. package/src/run/index.ts +93 -93
  167. package/src/run/resource-sample.ts +19 -0
  168. package/src/sandbox/build.ts +4 -0
  169. package/src/sandbox/coding-agent.ts +214 -0
  170. package/src/sandbox/policy.ts +1 -0
  171. package/src/sandbox/runtime-private.ts +4 -1
  172. package/src/secrets/coding-agent-auth.ts +97 -0
  173. package/src/secrets/index.ts +0 -16
  174. package/src/secrets/refresh-provider-oauth.ts +30 -76
  175. package/src/secrets/schema.ts +3 -4
  176. package/src/secrets/storage.ts +133 -234
  177. package/src/server/command-runner.ts +6 -2
  178. package/src/server/index.ts +102 -41
  179. package/src/sessions/index.ts +1 -1
  180. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  181. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  182. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  183. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  184. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  185. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  186. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  187. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  188. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  189. package/src/skills/typeclaw-config/SKILL.md +24 -24
  190. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  191. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  192. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  193. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  194. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  195. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  196. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  197. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  198. package/src/skills/typeclaw-plugins/SKILL.md +20 -20
  199. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  200. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  201. package/src/tui/index.ts +5 -3
  202. package/src/tui/theme.ts +1 -1
  203. package/typeclaw.schema.json +44 -2
  204. package/src/agent/adaptive-thinking-compat.ts +0 -79
  205. package/src/secrets/claude-credentials-json.ts +0 -129
  206. package/src/secrets/codex-auth-json.ts +0 -102
  207. package/src/secrets/export-claude-credentials-file.ts +0 -270
  208. package/src/secrets/export-codex-auth-file.ts +0 -250
  209. package/src/secrets/oauth-xai.ts +0 -348
  210. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  211. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  212. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  213. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -6,6 +6,32 @@
6
6
  // is a false receipt (see channel-reply.ts). State is per-session and reset at
7
7
  // turn start, so a claim must be backed by an action in the SAME turn.
8
8
 
9
+ import type { BackgroundObligationRef } from './background-obligations'
10
+ import type { InboundRef } from './inbound-journal'
11
+
12
+ export type ReviewResultCoverage = {
13
+ inboundCoverage?: InboundRef[]
14
+ backgroundCoverage?: BackgroundObligationRef[]
15
+ expectedAccountIdentity?: string
16
+ }
17
+
18
+ let reviewCoverageCapture: ((sessionId: string) => Promise<ReviewResultCoverage>) | null = null
19
+
20
+ export function setReviewCoverageCapture(capture: typeof reviewCoverageCapture): void {
21
+ reviewCoverageCapture = capture
22
+ }
23
+
24
+ export async function captureReviewResultCoverage(sessionId: string): Promise<ReviewResultCoverage> {
25
+ const coverage = await reviewCoverageCapture?.(sessionId)
26
+ return {
27
+ inboundCoverage: coverage?.inboundCoverage?.map((ref) => ({ ...ref })) ?? [],
28
+ backgroundCoverage: coverage?.backgroundCoverage?.map((ref) => ({ ...ref })) ?? [],
29
+ ...(coverage?.expectedAccountIdentity !== undefined
30
+ ? { expectedAccountIdentity: coverage.expectedAccountIdentity }
31
+ : {}),
32
+ }
33
+ }
34
+
9
35
  export type ReviewVerdict = 'APPROVE' | 'REQUEST_CHANGES'
10
36
  export type ReviewRoundOutcome = ReviewVerdict | 'DISMISSED'
11
37
 
@@ -14,6 +40,8 @@ export type ReviewObserver = (args: {
14
40
  workspace: string
15
41
  prNumber: number
16
42
  verdict: ReviewRoundOutcome
43
+ // The commit the landed review is attached to, when the publisher knows it.
44
+ commitSha?: string
17
45
  }) => void
18
46
 
19
47
  // A formal review LANDED this turn, of ANY state — the two decisive verdicts PLUS
@@ -24,12 +52,14 @@ export type ReviewObserver = (args: {
24
52
  // verdict-claim risk and must never satisfy `hasReview()`.
25
53
  export type ReviewOutputState = ReviewVerdict | 'COMMENT'
26
54
 
27
- export type ReviewOutputObserver = (args: {
28
- sessionId: string
29
- workspace: string
30
- prNumber: number
31
- state: ReviewOutputState
32
- }) => void
55
+ export type ReviewOutputObserver = (
56
+ args: {
57
+ sessionId: string
58
+ workspace: string
59
+ prNumber: number
60
+ state: ReviewOutputState
61
+ } & ReviewResultCoverage,
62
+ ) => void | Promise<void>
33
63
 
34
64
  type PrKey = string
35
65
  type ThreadKey = string
@@ -45,6 +75,21 @@ const resolvedThreads = new Set<ThreadKey>()
45
75
  // plugin/channels boundary, which is why it owns this hook.
46
76
  let reviewObserver: ReviewObserver | null = null
47
77
  let reviewOutputObserver: ReviewOutputObserver | null = null
78
+ export type VerifiedDismissal = {
79
+ sessionId: string
80
+ workspace: string
81
+ prNumber: number
82
+ commitSha?: string
83
+ startedAt?: number
84
+ }
85
+ const dismissalObservers = new Set<(dismissal: VerifiedDismissal) => Promise<void>>()
86
+
87
+ export function observeVerifiedDismissals(observer: (dismissal: VerifiedDismissal) => Promise<void>): () => void {
88
+ dismissalObservers.add(observer)
89
+ return () => {
90
+ dismissalObservers.delete(observer)
91
+ }
92
+ }
48
93
 
49
94
  export function setReviewObserver(observer: ReviewObserver | null): void {
50
95
  reviewObserver = observer
@@ -57,6 +102,8 @@ export function setReviewOutputObserver(observer: ReviewOutputObserver | null):
57
102
  export function __resetReviewObserverForTest(): void {
58
103
  reviewObserver = null
59
104
  reviewOutputObserver = null
105
+ reviewCoverageCapture = null
106
+ dismissalObservers.clear()
60
107
  }
61
108
 
62
109
  function prKey(sessionId: string, workspace: string, prNumber: number): PrKey {
@@ -76,12 +123,15 @@ export function resetReviewTurn(sessionId: string): void {
76
123
  }
77
124
  }
78
125
 
79
- export function recordReview(args: {
80
- sessionId: string
81
- workspace: string
82
- prNumber: number
83
- verdict: ReviewVerdict
84
- }): void {
126
+ export async function recordReview(
127
+ args: {
128
+ sessionId: string
129
+ workspace: string
130
+ prNumber: number
131
+ verdict: ReviewVerdict
132
+ commitSha?: string
133
+ } & ReviewResultCoverage,
134
+ ): Promise<void> {
85
135
  const key = prKey(args.sessionId, args.workspace, args.prNumber)
86
136
  const set = reviewsByPr.get(key) ?? new Set<ReviewVerdict>()
87
137
  set.add(args.verdict)
@@ -90,41 +140,65 @@ export function recordReview(args: {
90
140
  // ledger write — the false-receipt guard depends on this record being durable.
91
141
  if (reviewObserver !== null) {
92
142
  try {
93
- reviewObserver(args)
143
+ reviewObserver({
144
+ sessionId: args.sessionId,
145
+ workspace: args.workspace,
146
+ prNumber: args.prNumber,
147
+ verdict: args.verdict,
148
+ ...(args.commitSha !== undefined ? { commitSha: args.commitSha } : {}),
149
+ })
94
150
  } catch {
95
151
  // swallow: a broken broadcast must not break verdict bookkeeping
96
152
  }
97
153
  }
98
154
  // A decisive verdict IS review output too — fan it to the output observer so the
99
155
  // router's empty-turn guard sees it without a second detection path.
100
- recordReviewOutput({
156
+ await recordReviewOutput({
101
157
  sessionId: args.sessionId,
102
158
  workspace: args.workspace,
103
159
  prNumber: args.prNumber,
104
160
  state: args.verdict,
161
+ ...(args.inboundCoverage !== undefined ? { inboundCoverage: args.inboundCoverage } : {}),
162
+ ...(args.backgroundCoverage !== undefined ? { backgroundCoverage: args.backgroundCoverage } : {}),
105
163
  })
106
164
  }
107
165
 
108
- export function recordVerifiedDismissal(args: { sessionId: string; workspace: string; prNumber: number }): void {
109
- if (reviewObserver === null) return
110
- try {
111
- reviewObserver({ ...args, verdict: 'DISMISSED' })
112
- } catch {
113
- // A broken round wakeup must not turn a verified GitHub mutation into a tool failure.
166
+ export async function recordVerifiedDismissal(args: VerifiedDismissal): Promise<void> {
167
+ if (reviewObserver !== null) {
168
+ try {
169
+ reviewObserver({
170
+ sessionId: args.sessionId,
171
+ workspace: args.workspace,
172
+ prNumber: args.prNumber,
173
+ verdict: 'DISMISSED',
174
+ })
175
+ } catch {
176
+ // A broken round wakeup must not turn a verified GitHub mutation into a tool failure.
177
+ }
178
+ }
179
+ for (const observer of dismissalObservers) {
180
+ try {
181
+ await observer(args)
182
+ } catch (error) {
183
+ // Publication already succeeded; retain pending work for boot verification.
184
+ console.warn('[github] verified dismissal pending-review cleanup failed:', error)
185
+ }
114
186
  }
115
187
  }
116
188
 
117
- export function recordReviewOutput(args: {
118
- sessionId: string
119
- workspace: string
120
- prNumber: number
121
- state: ReviewOutputState
122
- }): void {
189
+ export async function recordReviewOutput(
190
+ args: {
191
+ sessionId: string
192
+ workspace: string
193
+ prNumber: number
194
+ state: ReviewOutputState
195
+ } & ReviewResultCoverage,
196
+ ): Promise<void> {
123
197
  if (reviewOutputObserver === null) return
124
198
  try {
125
- reviewOutputObserver(args)
199
+ await reviewOutputObserver(args)
126
200
  } catch {
127
- // swallow: a broken router notification must not break review bookkeeping
201
+ // The review already landed remotely. Settlement failure must not authorize a mutation retry.
128
202
  }
129
203
  }
130
204
 
@@ -51,6 +51,7 @@ export type ReviewVerdictGuard = {
51
51
  verdict: ReviewVerdict
52
52
  round?: GithubReviewFollowupRound
53
53
  thread?: string | null
54
+ reviewedHeadSha?: string
54
55
  retainDuplicateLease?: boolean
55
56
  }) => Promise<ApproveBlock | null>
56
57
  release: (args: { callId: string; outcome: ReviewOutputOutcome }) => Promise<void>
@@ -117,7 +118,30 @@ const PENDING_PUBLICATION_REASON =
117
118
 
118
119
  const ROUND_INELIGIBLE_REASON =
119
120
  'This review follow-up round assigned the formal verdict to another sibling thread session. ' +
120
- 'Do not submit a formal verdict from this session; wait for the designated sibling verdict activity, then close out only this thread.'
121
+ 'Do not submit a formal verdict from this session and do not reply now: call `skip_response`. Once the designated sibling verdict lands, ' +
122
+ 'close out only this thread with the technical outcome; never mention sessions, carriers, or review rounds on the PR.'
123
+
124
+ const ROUND_HEAD_UNVERIFIED_REASON =
125
+ "Could not verify this pull request's current head commit on GitHub, so the review round's verdict was not submitted. " +
126
+ 'You are still the designated carrier for this round. Retry the same verdict once shortly. ' +
127
+ 'If it fails again, stop retrying: the head read may be failing persistently (missing credentials or a denied or malformed GitHub API response), ' +
128
+ 'so report that the PR head could not be verified and ask the operator to check GitHub credentials and API access.'
129
+
130
+ const ROUND_HEAD_MOVED_REASON =
131
+ 'The pull request head moved past the commit this review round covers, so a verdict from this round would describe stale code. ' +
132
+ 'Do not submit it; the new push starts its own review round.'
133
+
134
+ function reviewedHeadRequiredReason(currentHead: string): string {
135
+ return (
136
+ `The pull request head moved to ${currentHead} after this review round opened. ` +
137
+ 'Submit the verdict with `post_github_review` and set `head_sha` to the full commit SHA your review covered. ' +
138
+ `If you did not review ${currentHead}, re-review that commit first.`
139
+ )
140
+ }
141
+
142
+ function sameSha(a: string | undefined, b: string): boolean {
143
+ return a !== undefined && a.toLocaleLowerCase() === b.toLocaleLowerCase()
144
+ }
121
145
 
122
146
  // The standing verdict a fresh attempt would duplicate. APPROVE duplicates a
123
147
  // standing APPROVED; REQUEST_CHANGES duplicates a standing CHANGES_REQUESTED.
@@ -400,15 +424,53 @@ export function canPromoteGithubReviewRoundTo(
400
424
  return current !== undefined && current.status !== 'completed' && !current.attemptedCarriers.has(thread)
401
425
  }
402
426
 
427
+ // `landedCommitSha` distinguishes the two callers. A restore (undefined) only
428
+ // asks whether the round still owns the PR. A completion passes the commit the
429
+ // landed verdict is attached to (null when the publisher cannot tell), because
430
+ // completing releases the carrier's thread close-outs: after an unobserved push
431
+ // the verdict must still describe the current head.
403
432
  export async function validateGithubReviewRound(
404
433
  round: GithubReviewFollowupRound,
405
434
  createdAt?: number,
406
435
  now: () => number = Date.now,
436
+ landedCommitSha?: string | null,
407
437
  ): Promise<boolean> {
408
438
  if (createdAt !== undefined && now() - createdAt >= reviewRoundTtlMs(round)) return false
409
439
  if (expiredReviewRoundKeys.has(githubReviewRoundKey(round))) return false
440
+ if (isGithubReviewRoundSuperseded(round, now)) return false
410
441
  const currentHead = await processHeadShaResolver({ workspace: round.workspace, prNumber: round.prNumber })
411
- return currentHead !== null && currentHead === round.headSha
442
+ if (currentHead === null || isGithubReviewRoundSuperseded(round, now)) return false
443
+ if (currentHead === round.headSha) return true
444
+ if (round.kind !== 'reply') return false
445
+ return landedCommitSha === undefined || sameSha(landedCommitSha ?? undefined, currentHead)
446
+ }
447
+
448
+ // Registering a round evicts every other round for the same PR, so a round that
449
+ // is no longer registered while a sibling round is has been replaced by a newer
450
+ // one (a later push, or a later reply generation). Re-registering it would evict
451
+ // that newer round in turn, so callers must check this BEFORE re-registration.
452
+ export function isGithubReviewRoundSuperseded(round: GithubReviewFollowupRound, now: () => number = Date.now): boolean {
453
+ const key = githubReviewRoundKey(round)
454
+ if (activeReviewRoundState(key, now) !== undefined) return false
455
+ expireReviewRounds(now)
456
+ return Array.from(reviewRounds.entries()).some(
457
+ ([candidateKey, state]) =>
458
+ candidateKey !== key && state.round.workspace === round.workspace && state.round.prNumber === round.prNumber,
459
+ )
460
+ }
461
+
462
+ function pendingPushRoundForPr(
463
+ target: { workspace: string; prNumber: number },
464
+ now: () => number = Date.now,
465
+ ): ReviewRoundState | undefined {
466
+ expireReviewRounds(now)
467
+ return Array.from(reviewRounds.values()).find(
468
+ (state) =>
469
+ state.status === 'pending' &&
470
+ state.round.kind === 'push' &&
471
+ state.round.workspace === target.workspace &&
472
+ state.round.prNumber === target.prNumber,
473
+ )
412
474
  }
413
475
 
414
476
  export async function guardGithubReviewRoundDismissal(args: {
@@ -594,7 +656,7 @@ export function createApproveIdempotencyGuard(deps: {
594
656
  if (args.verdict !== 'APPROVE' && args.verdict !== 'REQUEST_CHANGES') return null
595
657
  expireRecentLanded(now)
596
658
  expirePendingPublications(now, logger)
597
- const blocked = await evaluateRoundEligibility(args, deps.resolveHeadSha ?? processHeadShaResolver, now)
659
+ const blocked = await evaluateRoundEligibility(args, deps.resolveHeadSha ?? processHeadShaResolver, now, logger)
598
660
  if (blocked !== null) return blocked
599
661
  const key = prKey(args.workspace, args.prNumber)
600
662
 
@@ -763,18 +825,13 @@ async function evaluateRoundEligibility(
763
825
  prNumber: number
764
826
  round?: GithubReviewFollowupRound
765
827
  thread?: string | null
828
+ reviewedHeadSha?: string
766
829
  },
767
830
  resolveHeadSha: HeadShaResolver,
768
831
  now: () => number = Date.now,
832
+ logger: ReviewVerdictCoordinatorLogger = processLogger,
769
833
  ): Promise<ApproveBlock | null> {
770
- expireReviewRounds(now)
771
- const pendingRoundForPr = Array.from(reviewRounds.values()).find(
772
- (state) =>
773
- state.status === 'pending' &&
774
- state.round.kind === 'push' &&
775
- state.round.workspace === args.workspace &&
776
- state.round.prNumber === args.prNumber,
777
- )
834
+ const pendingRoundForPr = pendingPushRoundForPr(args, now)
778
835
  // Pushes invalidate the whole PR's prior verdict, so their round legitimately
779
836
  // owns every verdict attempt until one sibling carries it. Reply rounds only
780
837
  // coordinate the stamped siblings answering one blocking review: their
@@ -800,8 +857,34 @@ async function evaluateRoundEligibility(
800
857
  workspace: activeRound.workspace,
801
858
  prNumber: activeRound.prNumber,
802
859
  })
803
- if (currentRoundHead === null || currentRoundHead !== activeRound.headSha) {
804
- return { block: true, kind: 'round-ineligible', reason: ROUND_INELIGIBLE_REASON }
860
+ // This session IS the carrier here, so the sibling-carrier reason would be a
861
+ // lie that tells the model to stand down and strands the round. Name the
862
+ // actual cause instead: an unverified head (one retry, then diagnostics) or a moved head.
863
+ if (currentRoundHead === null) {
864
+ logger.warn(
865
+ `[github] review round head read failed pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} carrier=${activeRound.carrierThread ?? 'root'}`,
866
+ )
867
+ return { block: true, kind: 'round-ineligible', reason: ROUND_HEAD_UNVERIFIED_REASON }
868
+ }
869
+ // Re-read ownership after the await: a round registered meanwhile evicted this
870
+ // one, and the registration below would evict it right back.
871
+ const superseded = isGithubReviewRoundSuperseded(activeRound, now)
872
+ if (superseded || (currentRoundHead !== activeRound.headSha && activeRound.kind === 'push')) {
873
+ logger.warn(
874
+ `[github] review round head moved pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} round_head=${activeRound.headSha} current_head=${currentRoundHead}${superseded ? ' superseded=true' : ''}`,
875
+ )
876
+ return { block: true, kind: 'round-ineligible', reason: ROUND_HEAD_MOVED_REASON }
877
+ }
878
+ // A reply round's head is only the webhook snapshot at reply time, and no push
879
+ // round replaces it unless the adapter receives the push (never when
880
+ // `pull_request.synchronize` is off the event allowlist). So a moved reply round
881
+ // follows the head, but only for a verdict bound to the commit it describes:
882
+ // the carrier must name the head it reviewed, and it must still be current.
883
+ if (currentRoundHead !== activeRound.headSha && !sameSha(args.reviewedHeadSha, currentRoundHead)) {
884
+ logger.warn(
885
+ `[github] review round head moved without a matching reviewed head pr=${activeRound.workspace}#${activeRound.prNumber} round=${activeRound.roundId} current_head=${currentRoundHead} reviewed_head=${args.reviewedHeadSha ?? 'none'}`,
886
+ )
887
+ return { block: true, kind: 'round-ineligible', reason: reviewedHeadRequiredReason(currentRoundHead) }
805
888
  }
806
889
  registerGithubReviewRound(activeRound, now())
807
890
  return null
@@ -4,7 +4,10 @@ import { describeError } from './describe-error'
4
4
  // singleton would leak resolver state across tests. One instance is created in
5
5
  // run/index.ts and threaded to both the plugin loader and the channel manager.
6
6
 
7
- export type GithubTokenResolveResult = { kind: 'token'; token: string } | { kind: 'unavailable'; reason: string }
7
+ export type GithubTokenCredential = { token: string; accountIdentity?: string }
8
+ export type GithubTokenResolveResult =
9
+ | ({ kind: 'token' } & GithubTokenCredential)
10
+ | { kind: 'unavailable'; reason: string }
8
11
 
9
12
  export type ResolveGithubTokenForRepo = (repoSlug: string) => Promise<GithubTokenResolveResult>
10
13
 
@@ -16,7 +19,10 @@ export type GithubTokenBridge = {
16
19
  // process-wide GH_TOKEN, so brokered gh paths cannot rely on its prefix.
17
20
  hasAppTokenResolver: () => boolean
18
21
  getAppSelfLogin: () => string | null
19
- registerResolver: (resolver: (repoSlug: string) => Promise<string>, selfLogin?: () => string | null) => () => void
22
+ registerResolver: (
23
+ resolver: (repoSlug: string) => Promise<GithubTokenCredential>,
24
+ selfLogin?: () => string | null,
25
+ ) => () => void
20
26
  }
21
27
 
22
28
  const NO_RESOLVER_REASON =
@@ -24,7 +30,7 @@ const NO_RESOLVER_REASON =
24
30
  'Check `typeclaw logs` and `secrets.json#channels.github`.'
25
31
 
26
32
  export function createGithubTokenBridge(): GithubTokenBridge {
27
- let current: ((repoSlug: string) => Promise<string>) | null = null
33
+ let current: ((repoSlug: string) => Promise<GithubTokenCredential>) | null = null
28
34
  let currentSelfLogin: (() => string | null) | null = null
29
35
 
30
36
  return {
@@ -32,8 +38,8 @@ export function createGithubTokenBridge(): GithubTokenBridge {
32
38
  const resolver = current
33
39
  if (resolver === null) return { kind: 'unavailable', reason: NO_RESOLVER_REASON }
34
40
  try {
35
- const token = await resolver(repoSlug)
36
- return { kind: 'token', token }
41
+ const credential = await resolver(repoSlug)
42
+ return { kind: 'token', ...credential }
37
43
  } catch (err) {
38
44
  return { kind: 'unavailable', reason: describeError(err) }
39
45
  }