typeclaw 0.48.10 → 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.
- package/package.json +1 -1
- package/scripts/apparmor/typeclaw-bwrap +43 -0
- package/scripts/verify-apparmor-signals.sh +161 -0
- package/scripts/verify-mask-fd-sandbox.sh +86 -16
- package/src/agent/live-subagents.ts +98 -0
- package/src/agent/session-origin.ts +5 -1
- package/src/agent/tools/channel-reply.ts +30 -2
- package/src/agent/tools/channel-send.ts +19 -2
- package/src/agent/tools/spawn-subagent.ts +37 -1
- package/src/bundled-plugins/github-cli-auth/index.ts +1 -0
- package/src/channels/adapters/github/inbound.ts +195 -25
- package/src/channels/adapters/github/index.ts +16 -18
- package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
- package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
- package/src/channels/adapters/github/review-submitter.ts +28 -0
- package/src/channels/github-repo.ts +11 -0
- package/src/channels/github-review-verdict-coordinator.ts +179 -29
- package/src/channels/github-verdict-activity.ts +10 -6
- package/src/channels/manager.ts +9 -0
- package/src/channels/persistence.ts +28 -2
- package/src/channels/router.ts +284 -61
- package/src/channels/schema.ts +18 -0
- package/src/channels/types.ts +1 -0
- package/src/config/config.ts +9 -1
- package/src/container/start.ts +33 -24
- package/src/doctor/apparmor.ts +101 -0
- package/src/doctor/checks.ts +2 -0
- package/src/init/dockerfile.ts +7 -6
- package/src/init/windows-dev-link.ts +34 -2
- package/src/run/index.ts +1 -0
- package/src/sandbox/availability.ts +7 -5
- package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
- 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
|
-
|
|
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,
|
|
@@ -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 }>()
|
|
@@ -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
|
|
99
|
-
// webhook and the recovery sweep can never both
|
|
100
|
-
//
|
|
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 (!
|
|
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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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<
|
|
1145
|
-
if (event !== 'pull_request_review_comment' || parent?.isSelf !== true
|
|
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)
|
|
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
|
|
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
|
|
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(
|
|
301
|
-
if (!allowed.has(
|
|
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
|
|
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 (
|
|
394
|
-
await runReconcile(
|
|
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(
|
|
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: {
|
|
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.
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { githubReviewerWorkKey } from '@/channels/github-repo'
|
|
1
2
|
import type {
|
|
2
3
|
ReviewFinding,
|
|
3
4
|
ReviewSubmitter,
|
|
@@ -8,9 +9,21 @@ import type {
|
|
|
8
9
|
|
|
9
10
|
import type { GithubAuthContext } from './auth'
|
|
10
11
|
import { GITHUB_API_BASE, githubJsonHeaders } from './auth-pat'
|
|
12
|
+
import { createBoundedMap } from './dedup'
|
|
11
13
|
|
|
12
14
|
const MAX_HEAD_STABILITY_ATTEMPTS = 3
|
|
13
15
|
|
|
16
|
+
// Bounded because a long-lived container accumulates one entry per drafted PR
|
|
17
|
+
// forever otherwise. Eviction is fail-safe: a submission that captured a bumped
|
|
18
|
+
// generation sees the evicted key read back as 0, mismatches, and is denied —
|
|
19
|
+
// eviction can only cancel a submission, never resurrect a cancelled one.
|
|
20
|
+
const reviewSubmissionGenerations = createBoundedMap<string, number>()
|
|
21
|
+
|
|
22
|
+
export function invalidateGithubReviewSubmission(workspace: string, prNumber: number): void {
|
|
23
|
+
const key = githubReviewerWorkKey(workspace, prNumber)
|
|
24
|
+
reviewSubmissionGenerations.set(key, currentReviewSubmissionGeneration(workspace, prNumber) + 1)
|
|
25
|
+
}
|
|
26
|
+
|
|
14
27
|
export function createGithubReviewSubmitter(deps: {
|
|
15
28
|
token: (context?: GithubAuthContext) => Promise<string>
|
|
16
29
|
allowApprove: () => boolean
|
|
@@ -27,6 +40,7 @@ export function createGithubReviewSubmitter(deps: {
|
|
|
27
40
|
code: 'transient',
|
|
28
41
|
}
|
|
29
42
|
}
|
|
43
|
+
const submissionGeneration = currentReviewSubmissionGeneration(req.workspace, target.prNumber)
|
|
30
44
|
|
|
31
45
|
const token = await deps.token({ repoSlug: `${target.owner}/${target.repo}` })
|
|
32
46
|
const stable = await fetchStableAnchors(fetchImpl, token, target)
|
|
@@ -35,6 +49,16 @@ export function createGithubReviewSubmitter(deps: {
|
|
|
35
49
|
const { inline, reanchored } = partitionComments(req.comments, stable.anchors)
|
|
36
50
|
const downgraded = req.event === 'APPROVE' && !deps.allowApprove()
|
|
37
51
|
const event = downgraded ? 'COMMENT' : req.event
|
|
52
|
+
if (currentReviewSubmissionGeneration(req.workspace, target.prNumber) !== submissionGeneration) {
|
|
53
|
+
return {
|
|
54
|
+
ok: false,
|
|
55
|
+
error: 'PR converted to draft; review submission cancelled',
|
|
56
|
+
code: 'transient',
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
// Once this call dispatches fetch(), GitHub may already have accepted the
|
|
60
|
+
// review. Let posting, verification, and accounting settle after that
|
|
61
|
+
// boundary; cancelling mid-flight would leave duplicate/state ambiguity.
|
|
38
62
|
const posted = await postReview(fetchImpl, token, target, {
|
|
39
63
|
event,
|
|
40
64
|
body: appendReanchored(req.body, reanchored),
|
|
@@ -54,6 +78,10 @@ export function createGithubReviewSubmitter(deps: {
|
|
|
54
78
|
}
|
|
55
79
|
}
|
|
56
80
|
|
|
81
|
+
function currentReviewSubmissionGeneration(workspace: string, prNumber: number): number {
|
|
82
|
+
return reviewSubmissionGenerations.get(githubReviewerWorkKey(workspace, prNumber)) ?? 0
|
|
83
|
+
}
|
|
84
|
+
|
|
57
85
|
async function fetchStableAnchors(
|
|
58
86
|
fetchImpl: typeof fetch,
|
|
59
87
|
token: string,
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export function canonicalGithubRepo(repo: string): string {
|
|
2
|
+
return repo
|
|
3
|
+
.trim()
|
|
4
|
+
.replace(/\/+$/, '')
|
|
5
|
+
.replace(/\.git$/i, '')
|
|
6
|
+
.toLocaleLowerCase()
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function githubReviewerWorkKey(repo: string, prNumber: number): string {
|
|
10
|
+
return `reviewer:github:${canonicalGithubRepo(repo)}#${prNumber}`
|
|
11
|
+
}
|