typeclaw 0.48.10 → 0.48.12

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 (68) hide show
  1. package/package.json +2 -2
  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 +86 -16
  5. package/src/agent/index.ts +11 -1
  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/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  12. package/src/bundled-plugins/github-cli-auth/index.ts +2 -1
  13. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  14. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  15. package/src/channels/adapters/github/inbound.ts +195 -25
  16. package/src/channels/adapters/github/index.ts +16 -18
  17. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  18. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  19. package/src/channels/adapters/github/review-submitter.ts +28 -0
  20. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  21. package/src/channels/adapters/kakaotalk.ts +7 -8
  22. package/src/channels/adapters/teams-classify.ts +21 -0
  23. package/src/channels/adapters/teams-edit.ts +2 -1
  24. package/src/channels/adapters/teams-format.ts +16 -0
  25. package/src/channels/adapters/teams.ts +12 -5
  26. package/src/channels/github-repo.ts +11 -0
  27. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  28. package/src/channels/github-verdict-activity.ts +10 -6
  29. package/src/channels/manager.ts +9 -0
  30. package/src/channels/persistence.ts +28 -2
  31. package/src/channels/router.ts +284 -61
  32. package/src/channels/schema.ts +18 -0
  33. package/src/channels/types.ts +1 -0
  34. package/src/cli/compose.ts +3 -3
  35. package/src/cli/docker-preflight.ts +8 -4
  36. package/src/cli/restart.ts +89 -23
  37. package/src/cli/start.ts +68 -16
  38. package/src/cli/status.ts +38 -6
  39. package/src/cli/stop.ts +5 -2
  40. package/src/compose/stop.ts +5 -4
  41. package/src/config/config.ts +9 -1
  42. package/src/container/build-cache.ts +807 -0
  43. package/src/container/compose-project.ts +4 -0
  44. package/src/container/docker-app.ts +74 -0
  45. package/src/container/log-archive.ts +33 -5
  46. package/src/container/memory-limit.ts +80 -0
  47. package/src/container/memory-oversubscription.ts +125 -0
  48. package/src/container/restart.ts +6 -1
  49. package/src/container/shared.ts +43 -16
  50. package/src/container/start.ts +313 -77
  51. package/src/container/stop.ts +19 -13
  52. package/src/container/verify-running.ts +12 -0
  53. package/src/cron/scheduler.ts +12 -4
  54. package/src/doctor/apparmor.ts +101 -0
  55. package/src/doctor/bounded-exec.ts +14 -0
  56. package/src/doctor/checks.ts +42 -15
  57. package/src/doctor/index.ts +14 -2
  58. package/src/doctor/plugin-bridge.ts +15 -3
  59. package/src/hostd/paths.ts +4 -0
  60. package/src/init/dockerfile.ts +7 -6
  61. package/src/init/windows-dev-link.ts +34 -2
  62. package/src/run/index.ts +17 -0
  63. package/src/run/resource-sample.ts +171 -0
  64. package/src/sandbox/availability.ts +7 -5
  65. package/src/sandbox/index.ts +8 -1
  66. package/src/sandbox/session-tmp.ts +26 -1
  67. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  68. package/typeclaw.schema.json +7 -0
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
3
3
  import { Type } from '@mariozechner/pi-ai'
4
4
  import { defineTool } from '@mariozechner/pi-coding-agent'
5
5
 
6
+ import { githubReviewerWorkKey } from '@/channels/github-repo'
6
7
  import type { PermissionService } from '@/permissions'
7
8
  import type { Stream } from '@/stream'
8
9
 
@@ -199,6 +200,10 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
199
200
  reviewKind: params.review_identity.review_kind,
200
201
  }
201
202
  }
203
+ const workKey =
204
+ params.review_identity === undefined
205
+ ? undefined
206
+ : githubReviewerWorkKey(params.review_identity.repo, params.review_identity.pull_request)
202
207
 
203
208
  const coalesceKey = subagentCoalesceKey({
204
209
  parentSessionId,
@@ -216,6 +221,8 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
216
221
  coalesceKeyHeld = false
217
222
  coalescer.release(coalesceKey)
218
223
  }
224
+ const pendingWorkKeyRegistration =
225
+ workKey === undefined ? undefined : liveRegistry.beginWorkKeyRegistration(workKey)
219
226
 
220
227
  const startedAt = now()
221
228
  const spawnedByRole = permissions?.resolveRole(origin)
@@ -240,6 +247,9 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
240
247
  try {
241
248
  resolvedHandle = await handle
242
249
  } catch (err) {
250
+ if (pendingWorkKeyRegistration !== undefined) {
251
+ liveRegistry.abandonWorkKeyRegistration(pendingWorkKeyRegistration)
252
+ }
243
253
  releaseCoalesceKey()
244
254
  const message = err instanceof Error ? err.message : String(err)
245
255
  return errorResult(`failed to spawn ${subagentName}: ${message}`)
@@ -252,12 +262,36 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
252
262
  parentSessionId,
253
263
  ...(spawnedByRole !== undefined ? { spawnedByRole } : {}),
254
264
  background,
265
+ // Drafting a PR invalidates every reviewer job for it, regardless of
266
+ // commit or review kind. This is intentionally broader than the
267
+ // reviewer's head/base/kind-aware coalescing key.
268
+ ...(workKey !== undefined ? { workKey } : {}),
255
269
  startedAt,
256
270
  status: 'running' as const,
257
271
  abort: resolvedHandle.abort,
258
272
  releaseCoalesceKey,
259
273
  }
260
- liveRegistry.register(live)
274
+ const registered =
275
+ pendingWorkKeyRegistration === undefined
276
+ ? (liveRegistry.register(live), true)
277
+ : liveRegistry.registerIfWorkKeyActive(live, pendingWorkKeyRegistration)
278
+ let delayedCancellationError: string | undefined
279
+ if (!registered) {
280
+ void completion.then(releaseCoalesceKey)
281
+ try {
282
+ await resolvedHandle.abort()
283
+ } catch (err) {
284
+ const message = err instanceof Error ? err.message : String(err)
285
+ // The child is still live. Register it so later cancellation, status
286
+ // inspection, and completion settlement can still reach it.
287
+ liveRegistry.register(live)
288
+ delayedCancellationError = `reviewer cancellation failed before registration: ${message}`
289
+ }
290
+ if (delayedCancellationError === undefined) {
291
+ releaseCoalesceKey()
292
+ return errorResult('reviewer cancelled before registration: pull request converted to draft')
293
+ }
294
+ }
261
295
  if (capturedFinalMessage !== undefined) {
262
296
  liveRegistry.recordCapturedFinalMessageIfRunning(taskId, capturedFinalMessage)
263
297
  }
@@ -293,6 +327,8 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
293
327
  })
294
328
  })
295
329
 
330
+ if (delayedCancellationError !== undefined) return errorResult(delayedCancellationError)
331
+
296
332
  if (background) {
297
333
  const details: SpawnSubagentToolDetails = {
298
334
  ok: true,
@@ -11,6 +11,7 @@ export type GhBlockCode =
11
11
  | 'repo-selector-conflict'
12
12
  | 'credential-display'
13
13
  | 'credential-exposure'
14
+ | 'pathname-expansion'
14
15
 
15
16
  export type GhCommandDecision =
16
17
  | { kind: 'pass-through' }
@@ -59,6 +60,11 @@ const CREDENTIAL_DISPLAY_REASON =
59
60
  'In particular, `gh auth token` and `gh auth status --show-token` would print the command-scoped credential. ' +
60
61
  'Use host-side authentication setup or a redacted diagnostic instead.'
61
62
 
63
+ const PATHNAME_EXPANSION_REASON =
64
+ 'An unquoted `*`, `?`, or `[` in a gh command is a shell pathname pattern: the shell could expand it into ' +
65
+ 'different arguments than the ones TypeClaw authorized, so no credential is minted for it. ' +
66
+ "Quote the argument that contains it, e.g. `gh api '/repos/owner/repo/contents/path?ref=<sha>'`."
67
+
62
68
  const CREDENTIAL_EXPOSURE_REASON =
63
69
  'This gh command is not in TypeClaw’s credential-safe allowlist. Model-driven gh receives a command-scoped credential only for operations whose argv cannot read arbitrary files, render process environment values, upload arbitrary files, select another host, or start extensions. Use a supported direct gh operation, a first-class TypeClaw tool, or run this command host-side.'
64
70
 
@@ -194,7 +200,7 @@ export function analyzeGhCommand(command: string, fallbackRepo?: string): GhComm
194
200
  const ghStarts = findGhInvocations(tokens)
195
201
  if (ghStarts.length === 0) return { kind: 'pass-through' }
196
202
  if (containsUnquotedPathnameExpansion(command)) {
197
- return { kind: 'block', code: 'credential-exposure', reason: CREDENTIAL_EXPOSURE_REASON }
203
+ return { kind: 'block', code: 'pathname-expansion', reason: PATHNAME_EXPANSION_REASON }
198
204
  }
199
205
 
200
206
  for (let i = 0; i < ghStarts.length; i++) {
@@ -229,6 +229,7 @@ export default definePlugin({
229
229
  configureReviewVerdictCoordinator({
230
230
  resolveEffectiveApproval,
231
231
  resolveHeadSha: createGithubHeadShaResolver({ resolveToken }),
232
+ logger: ctx.logger,
232
233
  })
233
234
  const verdictGuard = createSharedReviewVerdictGuard()
234
235
  const pendingDismissals = new Map<string, { workspace: string; prNumber: number }>()
@@ -310,7 +311,7 @@ export default definePlugin({
310
311
  return {
311
312
  block: true,
312
313
  reason:
313
- decision.code === 'credential-display'
314
+ decision.code === 'credential-display' || decision.code === 'pathname-expansion'
314
315
  ? decision.reason
315
316
  : decision.reason + buildGhBlockGuidance(decision.code, fallbackRepo, command),
316
317
  }
@@ -80,7 +80,15 @@ export async function prepareReviewerCheckout(options: {
80
80
  ],
81
81
  { env: baseEnv },
82
82
  )
83
- return { path: checkout, repoSlug: options.repoSlug, headSha: options.headSha.toLocaleLowerCase() }
83
+ // The checkout lives in the session's `/tmp` backing dir, but the model only
84
+ // ever sees that dir AS `/tmp` (bwrap binds it there; file tools re-map
85
+ // `/tmp/*` into it). Returning the backing path would be re-mapped a second
86
+ // time and never resolve, so hand back the model-facing path.
87
+ return {
88
+ path: path.posix.join('/tmp', path.basename(checkout)),
89
+ repoSlug: options.repoSlug,
90
+ headSha: options.headSha.toLocaleLowerCase(),
91
+ }
84
92
  } catch (error) {
85
93
  await rm(checkout, { recursive: true, force: true }).catch(() => {})
86
94
  throw error
@@ -1,7 +1,7 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { mkdir, readdir, readFile, unlink, writeFile } from 'node:fs/promises'
4
- import { basename, join } from 'node:path'
4
+ import { basename, dirname, join } from 'node:path'
5
5
 
6
6
  import { z } from 'zod'
7
7
 
@@ -33,6 +33,7 @@ import { loadAllReferences, type Reference } from './references/load-references'
33
33
  import { captureShardSnapshot, restoreShardSnapshot } from './shard-snapshot'
34
34
  import type { StreamEvent } from './stream-events'
35
35
  import { readEvents, writeEventsAtomic } from './stream-io'
36
+ import { VECTOR_INDEX_REL_PATH } from './vector/doctor'
36
37
  import { embed, EMBEDDING_MODEL_ID } from './vector/embedder'
37
38
  import type { EmbedFn } from './vector/hybrid'
38
39
  import { topicPassage } from './vector/passages'
@@ -734,7 +735,17 @@ function isEnoent(err: unknown): boolean {
734
735
  return typeof err === 'object' && err !== null && 'code' in err && err.code === 'ENOENT'
735
736
  }
736
737
 
737
- const SNAPSHOT_PATHS = ['memory/'] as const
738
+ // The vector index is generated, rebuildable cache state, not durable memory.
739
+ // Keep force-adding the broad memory/ root so new durable artifact types are
740
+ // snapshotted automatically, while Git's exclusion pathspec keeps the SQLite
741
+ // DB and its WAL/SHM sidecars out of history.
742
+ const EXCLUDE_PATHSPEC_PREFIX = ':(exclude)'
743
+ const VECTOR_INDEX_DIRECTORY_REL_PATH = dirname(VECTOR_INDEX_REL_PATH)
744
+ const SNAPSHOT_PATHS = ['memory/', `${EXCLUDE_PATHSPEC_PREFIX}${VECTOR_INDEX_DIRECTORY_REL_PATH}/`] as const
745
+
746
+ function isSnapshotExclusionPathspec(pathspec: string): boolean {
747
+ return pathspec.startsWith(EXCLUDE_PATHSPEC_PREFIX)
748
+ }
738
749
 
739
750
  async function ensureMemoryFiles(agentDir: string): Promise<void> {
740
751
  const memoryDir = join(agentDir, 'memory')
@@ -767,10 +778,14 @@ async function commitMemorySnapshotUnlocked(cwd: string): Promise<void> {
767
778
 
768
779
  await clearSkipWorktree(bun, cwd, repo)
769
780
 
770
- // `git add -- foo bar/` fails with exit 128 if any pathspec matches no
771
- // path on disk. Filter to existing paths before passing them in.
772
- const presentPaths = SNAPSHOT_PATHS.filter((p) => existsSync(join(cwd, p)))
773
- if (presentPaths.length === 0) {
781
+ // `git add -- foo bar/` fails with exit 128 if any ordinary pathspec matches
782
+ // no path on disk. Keep exclusion pathspecs: they are Git syntax rather than
783
+ // filesystem paths, and must accompany the broad memory/ root everywhere it
784
+ // flows. Still return early when no ordinary root is present, so an exclusion
785
+ // by itself never reaches `git add`.
786
+ const presentPaths = SNAPSHOT_PATHS.filter((p) => isSnapshotExclusionPathspec(p) || existsSync(join(cwd, p)))
787
+ const hasPresentSnapshotRoot = presentPaths.some((p) => !isSnapshotExclusionPathspec(p))
788
+ if (!hasPresentSnapshotRoot) {
774
789
  await applySkipWorktree(bun, cwd, repo)
775
790
  return
776
791
  }
@@ -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
@@ -1141,17 +1302,21 @@ async function resolveReplyReviewRound(
1141
1302
  selfLogin: string | null,
1142
1303
  parent: ReviewCommentParent | null,
1143
1304
  options: GithubWebhookHandlerOptions,
1144
- ): Promise<GithubReviewFollowupRound | null> {
1145
- 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
1146
1307
  const comment = readRecord(payload.comment)
1147
1308
  const parentId = readNumber(comment, 'in_reply_to_id')
1148
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 }
1149
1312
  const repository = readRepository(payload)
1150
1313
  const pr = readRecord(payload.pull_request)
1151
1314
  const prNumber = readNumber(pr, 'number')
1152
1315
  const headSha = readString(readRecord(pr?.head), 'sha')
1153
1316
  const authToken = options.authToken
1154
- 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
+ }
1155
1320
 
1156
1321
  const target = `${repository.owner}/${repository.name}#${prNumber}`
1157
1322
  try {
@@ -1166,20 +1331,25 @@ async function resolveReplyReviewRound(
1166
1331
  })
1167
1332
  if (!blocking.ok) {
1168
1333
  options.logger.warn(`[github] reply review-state lookup failed for ${target}: ${blocking.error}`)
1169
- 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
+ }),
1170
1349
  }
1171
- if (!blocking.selfBlocking || blocking.selfBlockingReviewId === null) return null
1172
- return registerOrJoinReplyReviewRound({
1173
- workspace: `${repository.owner}/${repository.name}`,
1174
- prNumber,
1175
- headSha,
1176
- blockingReviewId: blocking.selfBlockingReviewId,
1177
- thread: String(parentId),
1178
- generateRoundId: options.generateReviewRoundId ?? randomUUID,
1179
- })
1180
1350
  } catch (err) {
1181
1351
  options.logger.warn(`[github] reply review-state lookup failed for ${target}: ${describeError(err)}`)
1182
- return null
1352
+ return { kind: 'unknown', expiresAt }
1183
1353
  }
1184
1354
  }
1185
1355
 
@@ -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
  }
@@ -2,6 +2,7 @@ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
2
2
  import { dirname, join } from 'node:path'
3
3
 
4
4
  import { describeError } from '../../describe-error'
5
+ import { canonicalGithubRepo } from '../../github-repo'
5
6
 
6
7
  // Durable per-PR replay cooldown for the open-PR reconcile pass.
7
8
  //
@@ -66,7 +67,7 @@ export function reconcileCooldownPath(agentDir: string): string {
66
67
  }
67
68
 
68
69
  function markerKey(repo: string, prId: number): string {
69
- return `${repo}#${prId}`
70
+ return `${canonicalGithubRepo(repo)}#${prId}`
70
71
  }
71
72
 
72
73
  export type ReconcileCooldownStore = {
@@ -74,6 +75,7 @@ export type ReconcileCooldownStore = {
74
75
  // Flush BEFORE routing the synthetic inbound: a crash between marking and
75
76
  // session creation must not re-trigger a replay on the next restart.
76
77
  markReplayed: (repo: string, prId: number, now: number) => Promise<void>
78
+ clear: (repo: string, prId: number) => Promise<void>
77
79
  prune: (repo: string, openPrIds: ReadonlySet<number>, now: number) => Promise<void>
78
80
  }
79
81
 
@@ -116,6 +118,18 @@ export async function loadReconcileCooldownStore(
116
118
  throw err
117
119
  }
118
120
  },
121
+ async clear(repo, prId): Promise<void> {
122
+ const key = markerKey(repo, prId)
123
+ const previous = markers.get(key)
124
+ if (previous === undefined) return
125
+ markers.delete(key)
126
+ try {
127
+ await flush()
128
+ } catch (err) {
129
+ markers.set(key, previous)
130
+ throw err
131
+ }
132
+ },
119
133
  async prune(repo, openPrIds, now): Promise<void> {
120
134
  let changed = false
121
135
  for (const [key, marker] of markers) {
@@ -54,7 +54,12 @@ export type RecoverFailedDeliveriesOptions = {
54
54
  // The shared processVerifiedGithubDelivery, bound to the adapter's handler
55
55
  // options. `delivery` is the GUID; the core dedups, filters by allowlist,
56
56
  // drops self-authored, and routes exactly as the live path does.
57
- process: (input: { event: string; delivery: string; payload: Record<string, unknown> }) => Promise<void>
57
+ process: (input: {
58
+ event: string
59
+ delivery: string
60
+ payload: Record<string, unknown>
61
+ recovered: true
62
+ }) => Promise<void>
58
63
  // Fast-path skip backed by the LIVE delivery dedup (shared with the webhook
59
64
  // handler): a guid here was just routed live (or reserved by `process` on
60
65
  // entry), so skip it. Best-effort only — it is a 1000-entry LRU and may evict
@@ -145,7 +150,7 @@ async function recoverHook(
145
150
 
146
151
  const payload = await fetchDeliveryPayload(fetchImpl, token, target, hook.hookId, delivery.id)
147
152
  if (payload === null) continue
148
- await options.process({ event: delivery.event, delivery: guid, payload })
153
+ await options.process({ event: delivery.event, delivery: guid, payload, recovered: true })
149
154
  // Record AFTER process resolves: an unexpected throw leaves the guid
150
155
  // unrecorded so the next sweep retries it. A no-op classify still records
151
156
  // (process returned), so a non-routable failed delivery is not refetched.