typeclaw 0.48.9 → 0.48.11

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 (48) hide show
  1. package/package.json +1 -1
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +176 -0
  5. package/src/agent/index.ts +9 -0
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/agent/tools/subagent-cancel.ts +14 -2
  12. package/src/bundled-plugins/backup/README.md +4 -3
  13. package/src/bundled-plugins/backup/runner.ts +125 -32
  14. package/src/bundled-plugins/github-cli-auth/gh-command.ts +106 -9
  15. package/src/bundled-plugins/github-cli-auth/git-command.ts +94 -9
  16. package/src/bundled-plugins/github-cli-auth/index.ts +45 -5
  17. package/src/channels/adapters/github/inbound.ts +210 -27
  18. package/src/channels/adapters/github/index.ts +16 -18
  19. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  20. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  21. package/src/channels/adapters/github/review-submitter.ts +28 -0
  22. package/src/channels/adapters/instagram-continuity-store.ts +141 -0
  23. package/src/channels/adapters/instagram.ts +149 -4
  24. package/src/channels/github-repo.ts +11 -0
  25. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  26. package/src/channels/github-verdict-activity.ts +12 -6
  27. package/src/channels/manager.ts +10 -0
  28. package/src/channels/persistence.ts +28 -2
  29. package/src/channels/router.ts +371 -33
  30. package/src/channels/schema.ts +18 -0
  31. package/src/channels/types.ts +11 -0
  32. package/src/cli/compose.ts +7 -4
  33. package/src/compose/restart.ts +26 -16
  34. package/src/compose/start.ts +24 -14
  35. package/src/config/config.ts +9 -1
  36. package/src/container/restart.ts +4 -0
  37. package/src/container/shared.ts +30 -3
  38. package/src/container/start.ts +137 -56
  39. package/src/doctor/apparmor.ts +101 -0
  40. package/src/doctor/checks.ts +2 -0
  41. package/src/hostd/daemon.ts +40 -17
  42. package/src/init/dockerfile.ts +7 -6
  43. package/src/init/windows-dev-link.ts +34 -2
  44. package/src/run/channel-session-factory.ts +35 -15
  45. package/src/run/index.ts +1 -0
  46. package/src/sandbox/availability.ts +7 -5
  47. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  48. package/typeclaw.schema.json +7 -0
@@ -298,10 +298,58 @@ function parseMintableTarget(subcommand: RemoteSubcommand, args: readonly string
298
298
  if (subcommand === 'push') return parseMintablePush(args)
299
299
  if (subcommand === 'fetch') return parseMintableFetch(args)
300
300
  if (subcommand === 'pull') return parseSimpleRemote(args, false)
301
- if (subcommand === 'clone') return parseExplicitUrl(args, 2)
301
+ if (subcommand === 'clone') return parseCloneTarget(args)
302
302
  return parseExplicitUrl(args, Number.POSITIVE_INFINITY)
303
303
  }
304
304
 
305
+ // Value-less clone flags that cannot redirect the fetch to another repo/host, run a
306
+ // command, or read/write a path outside the destination. Deliberately EXCLUDES
307
+ // --recurse-submodules (fetches other repos with the token live), --upload-pack and
308
+ // -c/--config (command execution / url.insteadOf rewriting), and --template,
309
+ // --reference, --separate-git-dir (arbitrary path read/write).
310
+ const SAFE_CLONE_FLAGS = new Set([
311
+ '-q',
312
+ '--quiet',
313
+ '--progress',
314
+ '-n',
315
+ '--no-checkout',
316
+ '--single-branch',
317
+ '--no-single-branch',
318
+ '--no-tags',
319
+ '--bare',
320
+ '--sparse',
321
+ ])
322
+
323
+ // Clone flags that consume the NEXT argv word as their value.
324
+ const SAFE_CLONE_VALUE_FLAGS = new Set(['--depth', '-b', '--branch'])
325
+
326
+ // `--flag=value` forms whose value is inert (a count, ref, date, or filter spec).
327
+ const SAFE_CLONE_INLINE_PREFIXES = ['--depth=', '--branch=', '--filter=', '--shallow-since=', '--shallow-exclude=']
328
+
329
+ // git clone's URL is a POSITIONAL, so the previous fixed-index parse rejected every
330
+ // flagged clone — `--depth 1`, the most common shape in code-analysis workflows, got
331
+ // no credential and failed on a private repo with git's opaque "could not read
332
+ // Username". Skipping a conservative flag allowlist finds the same positional while
333
+ // any unrecognized flag still falls through to no-credential (fails safe).
334
+ function parseCloneTarget(args: readonly string[]): TargetSpec | null {
335
+ const positionals: string[] = []
336
+ for (let i = 0; i < args.length; i++) {
337
+ const arg = args[i] as string
338
+ if (SAFE_CLONE_FLAGS.has(arg)) continue
339
+ if (SAFE_CLONE_VALUE_FLAGS.has(arg)) {
340
+ const value = args[++i]
341
+ if (value === undefined || !isOptionValue(value)) return null
342
+ continue
343
+ }
344
+ if (SAFE_CLONE_INLINE_PREFIXES.some((prefix) => arg.startsWith(prefix))) continue
345
+ if (!isOptionValue(arg)) return null
346
+ positionals.push(arg)
347
+ }
348
+ if (positionals.length === 0 || positionals.length > 2) return null
349
+ const url = positionals[0] as string
350
+ return looksLikeUrl(url) ? { kind: 'single', value: url, forPush: false } : null
351
+ }
352
+
305
353
  function parseMintablePush(args: readonly string[]): TargetSpec | null {
306
354
  const positionals: string[] = []
307
355
  let repository: string | null = null
@@ -798,7 +846,10 @@ function analyzeCloneThenInspect(command: string): GitCommandDecision | null {
798
846
  const parsed = parseStrictCloneHead(split.head)
799
847
  if (parsed === null) return isNonGithubCloneHead(split.head) ? { kind: 'pass-through' } : null
800
848
 
801
- const canonicalHead = `/usr/bin/git clone ${posixSingleQuote(parsed.url)} ${posixSingleQuote(parsed.destination)}`
849
+ const flagPart = parsed.flags.map(posixSingleQuote).join(' ')
850
+ const canonicalHead =
851
+ `/usr/bin/git clone ${flagPart === '' ? '' : `${flagPart} `}` +
852
+ `${posixSingleQuote(parsed.url)} ${posixSingleQuote(parsed.destination)}`
802
853
  return {
803
854
  kind: 'inject',
804
855
  repoSlug: parsed.repoSlug,
@@ -811,19 +862,53 @@ function tailContainsGitInvocation(tail: string): boolean {
811
862
  return extractEvidenceGitSegments(tail).length > 0
812
863
  }
813
864
 
814
- type StrictCloneHead = { repoSlug: string; url: string; destination: string }
865
+ type StrictCloneHead = { repoSlug: string; url: string; destination: string; flags: string[] }
815
866
 
816
- const STRICT_CLONE_HEAD_RE =
817
- /^[ \t]*git[ \t]+clone[ \t]+(https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?)[ \t]+([A-Za-z0-9._/-]+)[ \t]*$/
867
+ const STRICT_CLONE_URL_RE = /^(https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+?)(?:\.git)?)$/
868
+ const STRICT_CLONE_DESTINATION_RE = /^[A-Za-z0-9._/-]+$/
869
+ const SAFE_CLONE_FLAG_VALUE_RE = /^[A-Za-z0-9._:@/-]+$/
818
870
 
871
+ // The executed head is REBUILT from these parts rather than passed through, so the
872
+ // grammar stays tiny even though it now admits flags: every accepted token comes from
873
+ // the SAFE_CLONE_* allowlists, every value is charset-constrained, and each is
874
+ // re-emitted single-quoted. Without this a plain `git clone --depth 1 <url> <dir> &&
875
+ // <inspect>` — the natural code-analysis command — blocks outright.
819
876
  function parseStrictCloneHead(head: string): StrictCloneHead | null {
820
- const match = STRICT_CLONE_HEAD_RE.exec(head)
877
+ const words = tokenizeStandalone(head)
878
+ if (words === null || words[0] !== 'git' || words[1] !== 'clone') return null
879
+
880
+ const flags: string[] = []
881
+ const positionals: string[] = []
882
+ for (let i = 2; i < words.length; i++) {
883
+ const word = words[i] as string
884
+ if (SAFE_CLONE_FLAGS.has(word)) {
885
+ flags.push(word)
886
+ continue
887
+ }
888
+ if (SAFE_CLONE_VALUE_FLAGS.has(word)) {
889
+ const value = words[++i]
890
+ if (value === undefined || !SAFE_CLONE_FLAG_VALUE_RE.test(value)) return null
891
+ flags.push(word, value)
892
+ continue
893
+ }
894
+ const prefix = SAFE_CLONE_INLINE_PREFIXES.find((candidate) => word.startsWith(candidate))
895
+ if (prefix !== undefined) {
896
+ if (!SAFE_CLONE_FLAG_VALUE_RE.test(word.slice(prefix.length))) return null
897
+ flags.push(word)
898
+ continue
899
+ }
900
+ if (word.startsWith('-')) return null
901
+ positionals.push(word)
902
+ }
903
+
904
+ if (positionals.length !== 2) return null
905
+ const [rawUrl, destination] = positionals as [string, string]
906
+ const match = STRICT_CLONE_URL_RE.exec(rawUrl)
821
907
  if (match === null) return null
822
- const url = match[1] as string
823
908
  const repoSlug = match[2] as string
824
- const destination = match[3] as string
909
+ if (!STRICT_CLONE_DESTINATION_RE.test(destination)) return null
825
910
  if (destination.startsWith('-') || repoSlug.startsWith('/') || repoSlug.endsWith('/')) return null
826
- return { repoSlug, url, destination }
911
+ return { repoSlug, url: match[1] as string, destination, flags }
827
912
  }
828
913
 
829
914
  function isNonGithubCloneHead(head: string): boolean {
@@ -42,6 +42,35 @@ import { checkGraphqlAuthNudge } from './graphql-auth-nudge'
42
42
  import { commitReviewIfSucceeded, dismissalMutationSucceeded, noteReviewCommand } from './review-recorder'
43
43
  import { classifyGhToken, shouldMintAppToken } from './token-class'
44
44
 
45
+ const REPO_LIST_RE = /\bgh\s+repo\s+list\b/
46
+ const GH_API_RE = /\bgh\s+api\b/
47
+ const GH_REPO_VIEW_RE = /\bgh\s+repo\s+view\b/
48
+
49
+ // `gh api` rejects `-R`, and `gh repo view` takes a positional slug — so the
50
+ // blanket "-R owner/repo" advice is unrunnable for exactly the commands an agent
51
+ // reaches for when exploring an unfamiliar repo. A denial that suggests a command
52
+ // which cannot parse burns a turn and teaches the agent the repo is unreachable.
53
+ function ghRewriteExample(command: string, slug: string): string {
54
+ if (GH_API_RE.test(command)) return `\`gh api /repos/${slug}/...\``
55
+ if (GH_REPO_VIEW_RE.test(command)) return `\`gh repo view ${slug}\``
56
+ return `\`gh <cmd> -R ${slug}\``
57
+ }
58
+
59
+ // The shapes an agent reaches for when it wants to READ SOURCE. None is brokerable:
60
+ // `repo clone` is absent from SAFE_GH_OPERATIONS, and archive/search endpoints can
61
+ // write or exfiltrate. Brokered `git clone` IS supported for any allowlisted repo, so
62
+ // name it — otherwise the agent concludes the source is unreachable and says so.
63
+ const SOURCE_READ_RE = /\bgh\s+repo\s+clone\b|\bgh\s+search\s+code\b|\/(?:tarball|zipball|contents)\b/
64
+
65
+ function sourceReadRecovery(command: string, slug: string): string {
66
+ if (!SOURCE_READ_RE.test(command)) return ''
67
+ return (
68
+ ` To read this repository's source, clone it as its own standalone command:` +
69
+ ` \`git clone --depth 1 https://github.com/${slug}.git <dir>\` — TypeClaw brokers that clone for any` +
70
+ ' repo in `channels.github.repos[]`. Inspect the working copy with a separate command afterwards.'
71
+ )
72
+ }
73
+
45
74
  export default definePlugin({
46
75
  plugin: async (ctx) => {
47
76
  const resolveTokenForRepo = ctx.github.resolveTokenForRepo
@@ -200,6 +229,7 @@ export default definePlugin({
200
229
  configureReviewVerdictCoordinator({
201
230
  resolveEffectiveApproval,
202
231
  resolveHeadSha: createGithubHeadShaResolver({ resolveToken }),
232
+ logger: ctx.logger,
203
233
  })
204
234
  const verdictGuard = createSharedReviewVerdictGuard()
205
235
  const pendingDismissals = new Map<string, { workspace: string; prNumber: number }>()
@@ -224,15 +254,25 @@ export default definePlugin({
224
254
  // exact single-bare rewrite so the agent recovers in one step instead of
225
255
  // guessing. Composition blocks get a split-the-script instruction. The
226
256
  // returned text is appended to the block reason (synchronous, always seen).
227
- const buildGhBlockGuidance = (code: string, fallbackRepo: string | undefined): string => {
257
+ const buildGhBlockGuidance = (code: string, fallbackRepo: string | undefined, command: string): string => {
228
258
  const slug = fallbackRepo ?? 'owner/repo'
259
+ const example = ghRewriteExample(command, slug)
260
+ const sourceRead = sourceReadRecovery(command, slug)
229
261
  if (code === 'composition') {
230
262
  return (
231
- ` Run each gh as its own single bare command, e.g. \`gh label edit <name> -R ${slug} --name ...\` —` +
232
- ' not inside a function, `if`/`then`, `&&`, `;`, or `$(...)`.'
263
+ ` Run each gh as its own single bare command, e.g. ${example} —` +
264
+ ' not inside a function, `if`/`then`, `&&`, `;`, or `$(...)`.' +
265
+ sourceRead
266
+ )
267
+ }
268
+ if (REPO_LIST_RE.test(command)) {
269
+ return (
270
+ ' `gh repo list` targets an owner rather than one repository, so there is no per-repo' +
271
+ ` rewrite that can mint a token. Name a concrete repo instead, e.g. \`gh repo view ${slug}\`.` +
272
+ sourceRead
233
273
  )
234
274
  }
235
- return ` For example: \`gh <cmd> -R ${slug}\` as a single bare command.`
275
+ return ` For example: ${example} as a single bare command.` + sourceRead
236
276
  }
237
277
 
238
278
  // 'fall-through' means "not a repo-targeting gh command" so the caller can
@@ -273,7 +313,7 @@ export default definePlugin({
273
313
  reason:
274
314
  decision.code === 'credential-display'
275
315
  ? decision.reason
276
- : decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo),
316
+ : decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo, command),
277
317
  }
278
318
  }
279
319
 
@@ -2,7 +2,7 @@ import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto'
2
2
 
3
3
  import { registerOrJoinReplyReviewRound } from '@/channels/github-review-verdict-coordinator'
4
4
  import type { GithubReviewOn } from '@/channels/schema'
5
- import type { GithubReviewFollowupRound, InboundMessage } from '@/channels/types'
5
+ import type { GithubReviewFollowupRound, GithubReviewThreadCloseout, InboundMessage } from '@/channels/types'
6
6
 
7
7
  import { describeError } from '../../describe-error'
8
8
  import type { GithubAuthContext } from './auth'
@@ -12,6 +12,7 @@ import { createBoundedMap, type BoundedMap, type DeliveryDedup } from './dedup'
12
12
  import { isGithubEventAllowed } from './event-allowlist'
13
13
  import { encodeGithubReactionRef, type GithubReactionTarget } from './reactions'
14
14
  import { fetchSelfReviewBlocking } from './review-state'
15
+ import { invalidateGithubReviewSubmission } from './review-submitter'
15
16
  import { listUnresolvedSelfReviewThreads, type UnresolvedSelfReviewThread } from './review-thread-resolver'
16
17
 
17
18
  export type GithubInboundLogger = { info: (m: string) => void; warn: (m: string) => void; error: (m: string) => void }
@@ -52,8 +53,25 @@ export type GithubWebhookHandlerOptions = {
52
53
  sleepImpl?: (ms: number) => Promise<void>
53
54
  fetchImpl?: typeof fetch
54
55
  generateReviewRoundId?: () => string
56
+ now?: () => number
57
+ abortGithubPrTurn?: (
58
+ workspace: string,
59
+ prNumber: number,
60
+ reason: string,
61
+ ) => Promise<
62
+ | { kind: 'aborted'; matchedSessions: number; matchedReviewers: number; abortFailures: number }
63
+ | { kind: 'no-live-session' }
64
+ >
65
+ clearReconcileCooldown?: (workspace: string, prId: number) => Promise<'cleared' | 'not-initialized'>
55
66
  }
56
67
 
68
+ export const GITHUB_REVIEW_STATE_UNKNOWN_TTL_MS = 2 * 60_000
69
+
70
+ type ReplyReviewRoundResolution =
71
+ | { kind: 'round'; round: GithubReviewFollowupRound }
72
+ | { kind: 'clear' }
73
+ | { kind: 'unknown'; expiresAt: number }
74
+
57
75
  export function createGithubWebhookHandler(options: GithubWebhookHandlerOptions): (req: Request) => Promise<Response> {
58
76
  return async (req: Request): Promise<Response> => {
59
77
  if (req.method !== 'POST') return new Response('method not allowed', { status: 405 })
@@ -85,19 +103,35 @@ export function createGithubWebhookHandler(options: GithubWebhookHandlerOptions)
85
103
  // the live handler verifies the body; the sweep trusts the authenticated API.
86
104
  export async function processVerifiedGithubDelivery(
87
105
  options: GithubWebhookHandlerOptions,
88
- input: { event: string; delivery: string; payload: Record<string, unknown> },
106
+ input: { event: string; delivery: string; payload: Record<string, unknown>; recovered?: true },
89
107
  ): Promise<void> {
90
108
  const { event, delivery, payload } = input
91
109
  const action = readString(payload, 'action')
110
+ const eventAllowed = isGithubEventAllowed(options.allowlist(), event, action)
111
+ let staleRecoveredDraft = false
112
+ if (input.recovered === true && eventAllowed && event === 'pull_request' && action === 'converted_to_draft') {
113
+ const repository = readRepository(payload)
114
+ const prNumber = readNumber(readRecord(payload.pull_request), 'number')
115
+ if (repository !== null && prNumber !== null) {
116
+ staleRecoveredDraft = !(await recoveredPullRequestIsStillDraft(
117
+ options,
118
+ repository,
119
+ prNumber,
120
+ `${repository.owner}/${repository.name}`,
121
+ ))
122
+ }
123
+ }
92
124
  const isSynchronize = event === 'pull_request' && action === 'synchronize'
93
125
  if (!isSynchronize && delivery !== '') {
94
126
  if (options.dedup.has(delivery)) {
95
127
  options.logger.info(`[github] duplicate delivery ignored id=${delivery}`)
96
128
  return
97
129
  }
98
- // Reserve the delivery id synchronously, BEFORE the awaits below, so a live
99
- // webhook and the recovery sweep can never both clear the dedup gate for the
100
- // same event and route it twice. Synchronize uses its own synchronous,
130
+ // Reserve the delivery id synchronously before routing awaits so a live
131
+ // webhook and the recovery sweep can never both route the same event. A
132
+ // recovered draft's retryable freshness read is the sole earlier await; a
133
+ // concurrent live delivery reserves here first and wins this dedup check.
134
+ // Synchronize uses its own synchronous,
101
135
  // releasable head-SHA reservation so a failed redelivery can retry. JS is
102
136
  // single-threaded: nothing else runs between this has-check and add, so the
103
137
  // reservation is atomic. The awaits and classify that follow are all
@@ -105,7 +139,24 @@ export async function processVerifiedGithubDelivery(
105
139
  options.dedup.add(delivery)
106
140
  }
107
141
 
108
- if (!isGithubEventAllowed(options.allowlist(), event, action)) return
142
+ if (!eventAllowed || staleRecoveredDraft) return
143
+
144
+ // This control event must run before the self-author drop: a maintainer can
145
+ // draft the bot's PR, and the bot can draft its own PR. Either action must
146
+ // still stop review work instead of silently leaving the reviewer running.
147
+ if (event === 'pull_request' && action === 'converted_to_draft') {
148
+ const repository = readRepository(payload)
149
+ const pr = readRecord(payload.pull_request)
150
+ const prNumber = readNumber(pr, 'number')
151
+ if (repository === null || prNumber === null) {
152
+ options.logger.warn('[github] draft abort skipped: delivery missing repository or pull request number')
153
+ return
154
+ }
155
+ const workspace = `${repository.owner}/${repository.name}`
156
+ invalidateGithubReviewSubmission(workspace, prNumber)
157
+ scheduleDraftAbort({ workspace, prNumber, prId: readNumber(pr, 'id'), options })
158
+ return
159
+ }
109
160
 
110
161
  const selfId = options.selfId()
111
162
  const selfLogin = options.selfLogin()
@@ -142,12 +193,20 @@ export async function processVerifiedGithubDelivery(
142
193
  })
143
194
  if (classified === null) return
144
195
 
145
- options.route(
146
- withApprovalPolicy(
147
- replyReviewRound === null ? classified : { ...classified, githubReviewRound: replyReviewRound },
148
- options.allowApprove?.() ?? true,
149
- ),
150
- )
196
+ const routed =
197
+ replyReviewRound?.kind === 'round'
198
+ ? { ...classified, githubReviewRound: replyReviewRound.round }
199
+ : replyReviewRound?.kind === 'unknown' && classified.githubReviewThreadCloseout !== undefined
200
+ ? {
201
+ ...classified,
202
+ githubReviewThreadCloseout: {
203
+ ...classified.githubReviewThreadCloseout,
204
+ deferUntil: { kind: 'review-state-unknown' as const, expiresAt: replyReviewRound.expiresAt },
205
+ },
206
+ }
207
+ : classified
208
+
209
+ options.route(withApprovalPolicy(routed, options.allowApprove?.() ?? true))
151
210
  }
152
211
 
153
212
  export const PR_APPROVAL_DISABLED_NOTE =
@@ -238,6 +297,108 @@ function defaultScheduleBackgroundTask(task: () => Promise<void>): void {
238
297
  void task().catch(() => {})
239
298
  }
240
299
 
300
+ async function recoveredPullRequestIsStillDraft(
301
+ options: GithubWebhookHandlerOptions,
302
+ repository: { owner: string; name: string },
303
+ prNumber: number,
304
+ workspace: string,
305
+ ): Promise<boolean> {
306
+ if (options.authToken === undefined) {
307
+ throw new Error(`recovered draft freshness check unavailable for ${workspace}#${prNumber}: auth unavailable`)
308
+ }
309
+ try {
310
+ const token = await options.authToken({ repoSlug: workspace })
311
+ const response = await (options.fetchImpl ?? fetch)(
312
+ `${GITHUB_API_BASE}/repos/${repository.owner}/${repository.name}/pulls/${prNumber}`,
313
+ { headers: githubJsonHeaders(token) },
314
+ )
315
+ if (!response.ok) {
316
+ throw new Error(`pull request fetch returned ${response.status}`)
317
+ }
318
+ const current = readRecord(await response.json().catch(() => null))
319
+ const draft = readBoolean(current, 'draft')
320
+ if (draft === null) {
321
+ throw new Error('pull request response missing draft state')
322
+ }
323
+ if (!draft) {
324
+ options.logger.info(`[github] recovered draft abort skipped for ${workspace}#${prNumber}: pull request is ready`)
325
+ }
326
+ return draft
327
+ } catch (err) {
328
+ throw new Error(`recovered draft freshness check failed for ${workspace}#${prNumber}: ${describeError(err)}`)
329
+ }
330
+ }
331
+
332
+ function scheduleDraftAbort(input: {
333
+ workspace: string
334
+ prNumber: number
335
+ prId: number | null
336
+ options: GithubWebhookHandlerOptions
337
+ }): void {
338
+ const { workspace, prNumber, prId, options } = input
339
+ const target = `${workspace}#${prNumber}`
340
+ const schedule = options.scheduleBackgroundTask ?? defaultScheduleBackgroundTask
341
+ schedule(async () => {
342
+ const abortPromise = runGithubPrAbort(options, workspace, prNumber, target)
343
+ const cooldownPromise = clearDraftReconcileCooldown(options, workspace, prId, target)
344
+ const [outcome] = await Promise.all([abortPromise, cooldownPromise])
345
+ if (outcome === null) return
346
+ if (outcome.kind === 'no-live-session') {
347
+ options.logger.info(`[github] draft abort ${target}: no-live-session`)
348
+ return
349
+ }
350
+ options.logger.info(
351
+ `[github] draft abort ${target}: sessions=${outcome.matchedSessions} reviewers=${outcome.matchedReviewers} failures=${outcome.abortFailures}`,
352
+ )
353
+ })
354
+ }
355
+
356
+ async function runGithubPrAbort(
357
+ options: GithubWebhookHandlerOptions,
358
+ workspace: string,
359
+ prNumber: number,
360
+ target: string,
361
+ ): Promise<
362
+ | { kind: 'aborted'; matchedSessions: number; matchedReviewers: number; abortFailures: number }
363
+ | { kind: 'no-live-session' }
364
+ | null
365
+ > {
366
+ if (options.abortGithubPrTurn === undefined) {
367
+ options.logger.info(`[github] draft abort unavailable for ${target}: router callback not registered`)
368
+ return null
369
+ }
370
+ try {
371
+ return await options.abortGithubPrTurn(workspace, prNumber, 'pull request converted to draft')
372
+ } catch (err) {
373
+ options.logger.warn(`[github] draft abort failed for ${target}: ${describeError(err)}`)
374
+ return null
375
+ }
376
+ }
377
+
378
+ async function clearDraftReconcileCooldown(
379
+ options: GithubWebhookHandlerOptions,
380
+ workspace: string,
381
+ prId: number | null,
382
+ target: string,
383
+ ): Promise<void> {
384
+ if (prId === null) {
385
+ options.logger.warn(`[github] draft reconcile cooldown clear skipped for ${target}: pull request id missing`)
386
+ return
387
+ }
388
+ if (options.clearReconcileCooldown === undefined) {
389
+ options.logger.info(`[github] draft reconcile cooldown clear skipped for ${target}: store not initialized`)
390
+ return
391
+ }
392
+ try {
393
+ const outcome = await options.clearReconcileCooldown(workspace, prId)
394
+ if (outcome === 'not-initialized') {
395
+ options.logger.info(`[github] draft reconcile cooldown clear skipped for ${target}: store not initialized`)
396
+ }
397
+ } catch (err) {
398
+ options.logger.warn(`[github] draft reconcile cooldown clear failed for ${target}: ${describeError(err)}`)
399
+ }
400
+ }
401
+
241
402
  const MAX_REVIEW_FOLLOWUP_ATTEMPTS = 3
242
403
  const REVIEW_FOLLOWUP_RETRY_BASE_MS = 1000
243
404
  const REVIEW_FOLLOWUP_DEDUP_LIMIT = 1000
@@ -572,6 +733,10 @@ export function classifyGithubInbound(
572
733
  const parent =
573
734
  parentId !== null && options?.reviewCommentParent?.parentId === parentId ? options.reviewCommentParent : null
574
735
  const commenter = readUser(comment.user)
736
+ const githubReviewThreadCloseout: GithubReviewThreadCloseout | undefined =
737
+ parent?.isSelf === true && commenter !== null && !isBotUser(commenter)
738
+ ? { workspace: base.workspace, prNumber: number, rootCommentId: String(root) }
739
+ : undefined
575
740
  const directedAtBot =
576
741
  parentId === null &&
577
742
  isSelfPr(readUser(pr.user), selfLogin, options?.authType ?? 'pat') &&
@@ -591,6 +756,7 @@ export function classifyGithubInbound(
591
756
  ...(directedAtBot ? { forceBotMention: true } : {}),
592
757
  replyToBotMessageId: parent?.isSelf === true ? String(parent.parentId) : null,
593
758
  replyToOtherMessageId: parent?.isSelf === false ? String(parent.parentId) : null,
759
+ ...(githubReviewThreadCloseout !== undefined ? { githubReviewThreadCloseout } : {}),
594
760
  },
595
761
  )
596
762
  }
@@ -785,6 +951,7 @@ type BuildInboundOptions = {
785
951
  suppressSticky?: boolean
786
952
  replyToBotMessageId?: string | null
787
953
  replyToOtherMessageId?: string | null
954
+ githubReviewThreadCloseout?: GithubReviewThreadCloseout
788
955
  // Forces isBotMention=true with no @-handle in the body. A review (or
789
956
  // top-level review comment) on a PR the agent ITSELF authored is directed at
790
957
  // the bot — the inverse of review_requested — so it engages even though the
@@ -1009,9 +1176,12 @@ function buildInbound(
1009
1176
  ...(reactionTarget !== null ? { reactionRef: encodeGithubReactionRef(reactionTarget) } : {}),
1010
1177
  authorId: String(user.id),
1011
1178
  authorName: user.login,
1012
- authorIsBot: user.type === 'Bot',
1179
+ authorIsBot: isBotUser(user),
1013
1180
  isBotMention,
1014
1181
  ...(options?.suppressSticky === true ? { suppressSticky: true } : {}),
1182
+ ...(options?.githubReviewThreadCloseout !== undefined
1183
+ ? { githubReviewThreadCloseout: options.githubReviewThreadCloseout }
1184
+ : {}),
1015
1185
  replyToBotMessageId,
1016
1186
  replyToOtherMessageId,
1017
1187
  ts: typeof rawTs === 'string' ? Date.parse(rawTs) || 0 : 0,
@@ -1132,17 +1302,21 @@ async function resolveReplyReviewRound(
1132
1302
  selfLogin: string | null,
1133
1303
  parent: ReviewCommentParent | null,
1134
1304
  options: GithubWebhookHandlerOptions,
1135
- ): Promise<GithubReviewFollowupRound | null> {
1136
- if (event !== 'pull_request_review_comment' || parent?.isSelf !== true || selfLogin === null) return null
1305
+ ): Promise<ReplyReviewRoundResolution | null> {
1306
+ if (event !== 'pull_request_review_comment' || parent?.isSelf !== true) return null
1137
1307
  const comment = readRecord(payload.comment)
1138
1308
  const parentId = readNumber(comment, 'in_reply_to_id')
1139
1309
  if (parentId === null || parent.parentId !== parentId) return null
1310
+ const expiresAt = (options.now ?? Date.now)() + GITHUB_REVIEW_STATE_UNKNOWN_TTL_MS
1311
+ if (selfLogin === null) return { kind: 'unknown', expiresAt }
1140
1312
  const repository = readRepository(payload)
1141
1313
  const pr = readRecord(payload.pull_request)
1142
1314
  const prNumber = readNumber(pr, 'number')
1143
1315
  const headSha = readString(readRecord(pr?.head), 'sha')
1144
1316
  const authToken = options.authToken
1145
- if (repository === null || prNumber === null || headSha === null || authToken === undefined) return null
1317
+ if (repository === null || prNumber === null || headSha === null || authToken === undefined) {
1318
+ return { kind: 'unknown', expiresAt }
1319
+ }
1146
1320
 
1147
1321
  const target = `${repository.owner}/${repository.name}#${prNumber}`
1148
1322
  try {
@@ -1157,20 +1331,25 @@ async function resolveReplyReviewRound(
1157
1331
  })
1158
1332
  if (!blocking.ok) {
1159
1333
  options.logger.warn(`[github] reply review-state lookup failed for ${target}: ${blocking.error}`)
1160
- return null
1334
+ return { kind: 'unknown', expiresAt }
1335
+ }
1336
+ if (!blocking.selfBlocking) return { kind: 'clear' }
1337
+ if (blocking.selfBlockingReviewId === null) return { kind: 'unknown', expiresAt }
1338
+ return {
1339
+ kind: 'round',
1340
+ round: registerOrJoinReplyReviewRound({
1341
+ workspace: `${repository.owner}/${repository.name}`,
1342
+ prNumber,
1343
+ headSha,
1344
+ blockingReviewId: blocking.selfBlockingReviewId,
1345
+ thread: String(parentId),
1346
+ ...(options.now !== undefined ? { now: options.now } : {}),
1347
+ generateRoundId: options.generateReviewRoundId ?? randomUUID,
1348
+ }),
1161
1349
  }
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
1350
  } catch (err) {
1172
1351
  options.logger.warn(`[github] reply review-state lookup failed for ${target}: ${describeError(err)}`)
1173
- return null
1352
+ return { kind: 'unknown', expiresAt }
1174
1353
  }
1175
1354
  }
1176
1355
 
@@ -1242,6 +1421,10 @@ function isSelfAuthor(author: GithubUser, selfId: string | null, selfLogin: stri
1242
1421
  return false
1243
1422
  }
1244
1423
 
1424
+ function isBotUser(user: GithubUser): boolean {
1425
+ return user.type === 'Bot'
1426
+ }
1427
+
1245
1428
  // Whether the PR's OPENER is this agent. Distinct from isSelfAuthor (which
1246
1429
  // guards self-loops on the event ACTOR by id/login): here we have only the
1247
1430
  // `pull_request.user` from a review payload, no id to compare, and under App
@@ -6,6 +6,7 @@ import { resolveSecret } from '@/secrets/resolve'
6
6
  import type { GithubSecretsBlock } from '@/secrets/schema'
7
7
 
8
8
  import { describeError } from '../../describe-error'
9
+ import { canonicalGithubRepo } from '../../github-repo'
9
10
  import { buildAuthStrategy, type GithubAuthContext } from './auth'
10
11
  import { createGithubChannelNameResolver } from './channel-resolver'
11
12
  import { createDeliveryDedup } from './dedup'
@@ -130,6 +131,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
130
131
  let tokenRefreshTimer: { clear: () => void } | null = null
131
132
  let deliveryRecoveryTimer: { clear: () => void } | null = null
132
133
  let reconcileTimer: { clear: () => void } | null = null
134
+ let reconcileCooldownStore: ReconcileCooldownStore | null = null
133
135
  let unregisterTokenBridge: (() => void) | null = null
134
136
  const workspaceByChat = new Map<string, string>()
135
137
  const setIntervalFn =
@@ -224,6 +226,12 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
224
226
  fetchImpl,
225
227
  logger,
226
228
  route: routeInbound,
229
+ abortGithubPrTurn: options.router.abortGithubPrTurn,
230
+ clearReconcileCooldown: async (workspace, prId) => {
231
+ if (reconcileCooldownStore === null) return 'not-initialized'
232
+ await reconcileCooldownStore.clear(workspace, prId)
233
+ return 'cleared'
234
+ },
227
235
  }
228
236
  const handler = createGithubWebhookHandler(handlerOptions)
229
237
 
@@ -297,8 +305,8 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
297
305
  // the parser, because this adapter is the authority that owns repos[].
298
306
  unregisterTokenBridge = options.githubTokenBridge.registerResolver(
299
307
  (repoSlug) => {
300
- const allowed = new Set((options.configRef().repos ?? []).map(canonicalRepoSlug))
301
- if (!allowed.has(canonicalRepoSlug(repoSlug))) {
308
+ const allowed = new Set((options.configRef().repos ?? []).map(canonicalGithubRepo))
309
+ if (!allowed.has(canonicalGithubRepo(repoSlug))) {
302
310
  throw new Error(
303
311
  `repo \`${repoSlug}\` is not in this agent's configured \`channels.github.repos[]\`; ` +
304
312
  'refusing to mint a GitHub App token for it. Target a configured repo, ' +
@@ -370,8 +378,9 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
370
378
  // so the many restarts a churning tunnel causes don't re-review the same
371
379
  // PRs; the periodic tick below retries genuinely-missed PRs after the
372
380
  // cooldown without needing a restart.
373
- const reconcileCooldownStore =
381
+ const loadedReconcileCooldownStore =
374
382
  repos.length > 0 ? await loadReconcileCooldownStore(options.agentDir, logger) : null
383
+ reconcileCooldownStore = loadedReconcileCooldownStore
375
384
  // Resolve review.on per call, not from the captured startup cfg: review.on
376
385
  // is live-reloadable, so a periodic tick must honor a change to `off`
377
386
  // (reconcileOpenPrs short-circuits on `off`) instead of scanning forever.
@@ -390,11 +399,11 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
390
399
  }).catch((err: unknown) => {
391
400
  logger.warn(`[github] reconcile pass failed: ${describeError(err)}`)
392
401
  })
393
- if (reconcileCooldownStore !== null) {
394
- await runReconcile(reconcileCooldownStore)
402
+ if (loadedReconcileCooldownStore !== null) {
403
+ await runReconcile(loadedReconcileCooldownStore)
395
404
  const reconcileIntervalMs = options.reconcileIntervalMs ?? DEFAULT_RECONCILE_INTERVAL_MS
396
405
  if (reconcileIntervalMs > 0) {
397
- reconcileTimer = setIntervalFn(() => void runReconcile(reconcileCooldownStore), reconcileIntervalMs)
406
+ reconcileTimer = setIntervalFn(() => void runReconcile(loadedReconcileCooldownStore), reconcileIntervalMs)
398
407
  }
399
408
  }
400
409
  // Periodically recover inbound deliveries that failed at the tunnel and
@@ -479,6 +488,7 @@ export function createGithubAdapter(options: GithubAdapterOptions): GithubAdapte
479
488
  server = null
480
489
  selfId = null
481
490
  selfLogin = null
491
+ reconcileCooldownStore = null
482
492
  },
483
493
  isConnected(): boolean {
484
494
  return started && selfLogin !== null
@@ -608,18 +618,6 @@ function logDeregistrationOutcome(
608
618
  }
609
619
  }
610
620
 
611
- // Canonical form for repos[] allowlist comparison so the gate can't be bypassed
612
- // by case, a trailing slash, or a `.git` suffix (GitHub treats owner/name
613
- // case-insensitively). Applied identically to both configured repos[] and the
614
- // runtime slug before exact Set membership.
615
- function canonicalRepoSlug(repo: string): string {
616
- return repo
617
- .trim()
618
- .replace(/\/+$/, '')
619
- .replace(/\.git$/i, '')
620
- .toLowerCase()
621
- }
622
-
623
621
  function defaultSleep(ms: number): Promise<void> {
624
622
  return new Promise((resolve) => setTimeout(resolve, ms))
625
623
  }