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.
Files changed (33) 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 +86 -16
  5. package/src/agent/live-subagents.ts +98 -0
  6. package/src/agent/session-origin.ts +5 -1
  7. package/src/agent/tools/channel-reply.ts +30 -2
  8. package/src/agent/tools/channel-send.ts +19 -2
  9. package/src/agent/tools/spawn-subagent.ts +37 -1
  10. package/src/bundled-plugins/github-cli-auth/index.ts +1 -0
  11. package/src/channels/adapters/github/inbound.ts +195 -25
  12. package/src/channels/adapters/github/index.ts +16 -18
  13. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  14. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  15. package/src/channels/adapters/github/review-submitter.ts +28 -0
  16. package/src/channels/github-repo.ts +11 -0
  17. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  18. package/src/channels/github-verdict-activity.ts +10 -6
  19. package/src/channels/manager.ts +9 -0
  20. package/src/channels/persistence.ts +28 -2
  21. package/src/channels/router.ts +284 -61
  22. package/src/channels/schema.ts +18 -0
  23. package/src/channels/types.ts +1 -0
  24. package/src/config/config.ts +9 -1
  25. package/src/container/start.ts +33 -24
  26. package/src/doctor/apparmor.ts +101 -0
  27. package/src/doctor/checks.ts +2 -0
  28. package/src/init/dockerfile.ts +7 -6
  29. package/src/init/windows-dev-link.ts +34 -2
  30. package/src/run/index.ts +1 -0
  31. package/src/sandbox/availability.ts +7 -5
  32. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  33. package/typeclaw.schema.json +7 -0
@@ -52,16 +52,19 @@ import {
52
52
  type EngagementDecision,
53
53
  } from './engagement'
54
54
  import { checkFalseReceipt } from './github-false-receipt'
55
+ import { githubReviewerWorkKey } from './github-repo'
55
56
  import { evaluateRereviewGuard } from './github-rereview-guard'
56
57
  import { resetReviewTurn, type ReviewOutputState, type ReviewRoundOutcome } from './github-review-turn-ledger'
57
58
  import {
58
59
  canPromoteGithubReviewRoundTo,
60
+ abortGithubReviewStateForPr,
59
61
  completeGithubReviewRound,
60
62
  forgetGithubReviewRound,
61
63
  githubReviewRoundKey,
62
64
  githubReviewRoundPersistence,
63
65
  hasGithubReviewRoundDismissalAttempt,
64
66
  isGithubReviewRoundComplete,
67
+ isGithubReviewRoundPending,
65
68
  promoteGithubReviewRound,
66
69
  registerGithubReviewRound,
67
70
  restoreGithubReviewRound,
@@ -886,11 +889,12 @@ type LiveSession = {
886
889
  // with a reply on that exact thread. This spans reminder-only retry iterations.
887
890
  githubReviewThreadCloseout:
888
891
  | (GithubReviewThreadCloseout & {
889
- sendCountAtStart: number
890
892
  startedAt: number
891
893
  correctionAttempts: number
894
+ deferred: boolean
892
895
  })
893
896
  | null
897
+ githubReviewThreadCloseoutDecisionTurn: number | null
894
898
  // Round key of a close-out that arrived while the round was still pending
895
899
  // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
896
900
  pendingGithubReviewRoundCloseout: string | null
@@ -1579,17 +1583,26 @@ export type ChannelRouter = {
1579
1583
  verdict: ReviewRoundOutcome
1580
1584
  sessionId: string
1581
1585
  }) => { kind: 'delivered'; count: number }
1586
+ abortGithubPrTurn?: (
1587
+ workspace: string,
1588
+ prNumber: number,
1589
+ reason: string,
1590
+ ) => Promise<
1591
+ | { kind: 'aborted'; matchedSessions: number; matchedReviewers: number; abortFailures: number }
1592
+ | { kind: 'no-live-session' }
1593
+ >
1582
1594
  completeGithubReviewRound?: (args: {
1583
1595
  workspace: string
1584
1596
  prNumber: number
1585
1597
  verdict: ReviewRoundOutcome
1586
1598
  sessionId: string
1587
1599
  }) => Promise<{ kind: 'completed' | 'no-round' }>
1588
- finishGithubReviewRoundCloseout?: (args: {
1600
+ finishGithubReviewThreadCloseout?: (args: {
1589
1601
  sessionId: string
1590
1602
  workspace: string
1591
1603
  prNumber: number
1592
1604
  thread: string | null
1605
+ decision: 'resolved' | 'left-open'
1593
1606
  }) => void
1594
1607
  noteGithubReviewOutput: (args: {
1595
1608
  sessionId: string
@@ -1824,6 +1837,10 @@ export type CreateChannelRouterOptions = {
1824
1837
  // work in the resume greeting. Background-only: a foreground child returns its
1825
1838
  // result inline, so it is not orphaned by the bounce. Omitted means none.
1826
1839
  listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
1840
+ cancelRunningSubagentsByWorkKey?: (
1841
+ workKey: string,
1842
+ reason: string,
1843
+ ) => Promise<{ matched: number; cancelled: number; failures: number }>
1827
1844
  }
1828
1845
 
1829
1846
  export type RestartCommandContext = {
@@ -1956,7 +1973,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1956
1973
  handler: async ({ live }) => {
1957
1974
  // requiresLiveSession:true guarantees the dispatch layer resolved a
1958
1975
  // session before running this handler, so `live` is non-null here.
1959
- await stopCurrentChannelTurn(live!)
1976
+ await stopCurrentChannelTurn(live!, 'user_stop')
1960
1977
  return { reply: 'Stopped the current turn.' }
1961
1978
  },
1962
1979
  },
@@ -2059,7 +2076,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2059
2076
  void _removed
2060
2077
  mappings[idx] = rest
2061
2078
  } else {
2062
- const state = githubReviewRoundPersistence(round)
2079
+ const state = githubReviewRoundPersistence(round, now)
2063
2080
  if (state === null) {
2064
2081
  const { githubReviewRound: _expired, ...rest } = record
2065
2082
  void _expired
@@ -2071,6 +2088,32 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2071
2088
  void persist()
2072
2089
  }
2073
2090
 
2091
+ const persistGithubReviewThreadCloseout = (live: LiveSession, closeout: GithubReviewThreadCloseout | null): void => {
2092
+ if (mappings === null) return
2093
+ const idx = mappings.findIndex(
2094
+ (record) =>
2095
+ record.adapter === live.key.adapter &&
2096
+ record.workspace === live.key.workspace &&
2097
+ record.chat === live.key.chat &&
2098
+ (record.thread ?? null) === (live.key.thread ?? null),
2099
+ )
2100
+ if (idx < 0) return
2101
+ const record = mappings[idx]!
2102
+ if (closeout === null) {
2103
+ const { githubReviewThreadCloseout: _removed, ...rest } = record
2104
+ void _removed
2105
+ mappings[idx] = rest
2106
+ } else {
2107
+ mappings[idx] = { ...record, githubReviewThreadCloseout: { ...closeout, deferred: true } }
2108
+ }
2109
+ void persist()
2110
+ }
2111
+
2112
+ const clearGithubReviewThreadCloseout = (live: LiveSession): void => {
2113
+ live.githubReviewThreadCloseout = null
2114
+ persistGithubReviewThreadCloseout(live, null)
2115
+ }
2116
+
2074
2117
  const createForChannel: CreateSessionForChannel =
2075
2118
  options.createSessionForChannel ??
2076
2119
  (async ({ key, existingSessionId, existingSessionFile, origin, originRef }) => {
@@ -2465,6 +2508,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2465
2508
  thread: prev.thread,
2466
2509
  participants: prev.participants,
2467
2510
  lastInboundAt: 0,
2511
+ ...(prev.githubReviewThreadCloseout !== undefined && prev.githubReviewRound !== undefined
2512
+ ? { githubReviewRound: prev.githubReviewRound }
2513
+ : {}),
2514
+ ...(prev.githubReviewThreadCloseout !== undefined
2515
+ ? { githubReviewThreadCloseout: prev.githubReviewThreadCloseout }
2516
+ : {}),
2468
2517
  }
2469
2518
  await persist()
2470
2519
  }
@@ -2511,6 +2560,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2511
2560
  participants: record.participants,
2512
2561
  lastInboundAt: 0,
2513
2562
  ...(record.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
2563
+ ...(record.githubReviewThreadCloseout !== undefined
2564
+ ? { githubReviewThreadCloseout: record.githubReviewThreadCloseout }
2565
+ : {}),
2514
2566
  }
2515
2567
  if (mappings) {
2516
2568
  const idx = mappings.findIndex(
@@ -2539,13 +2591,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2539
2591
  sessionFile: resumeTarget.sessionFile,
2540
2592
  participants: (record?.participants ?? []) as ChannelParticipant[],
2541
2593
  lastInboundAt: now(),
2594
+ ...(record?.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
2595
+ ...(record?.githubReviewThreadCloseout !== undefined
2596
+ ? { githubReviewThreadCloseout: record.githubReviewThreadCloseout }
2597
+ : {}),
2542
2598
  }
2543
2599
  }
2600
+ const restoredDeferredCloseout = resolvedRecord?.githubReviewThreadCloseout ?? null
2544
2601
  let restoredRound: GithubReviewFollowupRound | null = null
2545
2602
  let restoredRoundStatus: 'pending' | 'completed' | null = null
2546
2603
  if (resolvedRecord?.githubReviewRound !== undefined) {
2547
2604
  if (
2548
- await validateGithubReviewRound(resolvedRecord.githubReviewRound, resolvedRecord.githubReviewRound.createdAt)
2605
+ await validateGithubReviewRound(
2606
+ resolvedRecord.githubReviewRound,
2607
+ resolvedRecord.githubReviewRound.createdAt,
2608
+ now,
2609
+ )
2549
2610
  ) {
2550
2611
  restoredRoundStatus = resolvedRecord.githubReviewRound.status
2551
2612
  restoredRound = restoreGithubReviewRound(
@@ -2555,6 +2616,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2555
2616
  resolvedRecord.githubReviewRound.dismissalAttempted === true,
2556
2617
  resolvedRecord.githubReviewRound.requestChangesAttempted === true,
2557
2618
  resolvedRecord.githubReviewRound.createdAt,
2619
+ now,
2558
2620
  )
2559
2621
  } else {
2560
2622
  logger.info(
@@ -2635,10 +2697,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2635
2697
  participants,
2636
2698
  ...(restoredRound !== null && restoredRoundStatus !== null
2637
2699
  ? (() => {
2638
- const state = githubReviewRoundPersistence(restoredRound)
2700
+ const state = githubReviewRoundPersistence(restoredRound, now)
2639
2701
  return state === null ? {} : { githubReviewRound: { ...restoredRound, ...state } }
2640
2702
  })()
2641
2703
  : {}),
2704
+ ...(restoredDeferredCloseout !== null ? { githubReviewThreadCloseout: restoredDeferredCloseout } : {}),
2642
2705
  }
2643
2706
  if (mappings) {
2644
2707
  const idx = mappings.findIndex(
@@ -2678,7 +2741,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2678
2741
  resolvedNames,
2679
2742
  originRef,
2680
2743
  githubReviewRound: restoredRound,
2681
- githubReviewThreadCloseout: null,
2744
+ githubReviewThreadCloseout:
2745
+ restoredDeferredCloseout === null
2746
+ ? null
2747
+ : {
2748
+ ...restoredDeferredCloseout,
2749
+ startedAt: now(),
2750
+ correctionAttempts: 0,
2751
+ deferred: true,
2752
+ },
2753
+ githubReviewThreadCloseoutDecisionTurn: null,
2682
2754
  pendingGithubReviewRoundCloseout: null,
2683
2755
  promptQueue: [],
2684
2756
  pendingSystemReminders: [],
@@ -3417,7 +3489,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3417
3489
  if (obligation === null) return
3418
3490
  // Consume before sending so adapter failure cannot turn this one-shot
3419
3491
  // fallback into a reminder/fallback loop.
3420
- live.githubReviewThreadCloseout = null
3492
+ clearGithubReviewThreadCloseout(live)
3421
3493
  logger.warn(
3422
3494
  `[channels] ${live.keyId} github_thread_closeout_fallback pr=${obligation.prNumber} root=${obligation.rootCommentId}`,
3423
3495
  )
@@ -3436,13 +3508,42 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3436
3508
  }
3437
3509
  }
3438
3510
 
3511
+ const deferredPendingReviewRound = (live: LiveSession): GithubReviewFollowupRound | null => {
3512
+ const round = live.githubReviewRound
3513
+ if (round === null) return null
3514
+ if (round.carrierThread === live.key.thread) return null
3515
+ return isGithubReviewRoundPending(round, now) ? round : null
3516
+ }
3517
+
3518
+ const isReviewStateUnknownDeferralActive = (closeout: GithubReviewThreadCloseout): boolean =>
3519
+ closeout.deferUntil?.kind === 'review-state-unknown' && closeout.deferUntil.expiresAt > now()
3520
+
3439
3521
  const enforceGithubReviewThreadCloseout = async (live: LiveSession): Promise<void> => {
3440
3522
  const closeout = live.githubReviewThreadCloseout
3441
- if (
3442
- closeout === null ||
3443
- live.successfulChannelSends !== closeout.sendCountAtStart ||
3444
- isAwaitingBackgroundChild(live, 'github-thread-closeout', closeout.startedAt)
3445
- ) {
3523
+ if (closeout === null || isAwaitingBackgroundChild(live, 'github-thread-closeout', closeout.startedAt)) {
3524
+ return
3525
+ }
3526
+ if (isReviewStateUnknownDeferralActive(closeout)) {
3527
+ if (!closeout.deferred) {
3528
+ closeout.deferred = true
3529
+ persistGithubReviewThreadCloseout(live, closeout)
3530
+ }
3531
+ logger.info(
3532
+ `[channels] ${live.keyId} github_thread_closeout_deferred pr=${closeout.prNumber} root=${closeout.rootCommentId} reason=review_state_unknown expires_at=${closeout.deferUntil?.expiresAt}`,
3533
+ )
3534
+ return
3535
+ }
3536
+ const deferredRound = deferredPendingReviewRound(live)
3537
+ if (deferredRound !== null) {
3538
+ if (!closeout.deferred) {
3539
+ closeout.deferred = true
3540
+ persistGithubReviewThreadCloseout(live, closeout)
3541
+ }
3542
+ // Preserve the anti-strand obligation while the elected carrier acts, but
3543
+ // do not convert a legitimate wait into participant-facing process noise.
3544
+ logger.info(
3545
+ `[channels] ${live.keyId} github_thread_closeout_deferred pr=${closeout.prNumber} root=${closeout.rootCommentId} round=${deferredRound.roundId}`,
3546
+ )
3446
3547
  return
3447
3548
  }
3448
3549
  if (live.skippedTurn?.turnSeq === live.turnSeq) live.skippedTurn = null
@@ -3456,8 +3557,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3456
3557
  `<system-reminder>\nThis session still owes a close-out on GitHub PR #${closeout.prNumber}, ` +
3457
3558
  `review thread root comment ${closeout.rootCommentId}. Your previous turn sent no reply to that thread. ` +
3458
3559
  `Call channel_reply now with an explicit resolve_review_thread choice: true if the concern is addressed, ` +
3459
- `or false to leave it open with an explanation. Do not treat a PR-level verdict stand-down as satisfying ` +
3460
- `this thread-level obligation.\n</system-reminder>`,
3560
+ `or false to leave it open with the specific technical reason. Send exactly ONE participant-facing ` +
3561
+ `close-out message with no narration about internal review rounds, carriers, sessions, verdict registration, ` +
3562
+ `or sticky review state. Do not treat a PR-level verdict stand-down as satisfying this thread-level obligation.\n</system-reminder>`,
3461
3563
  ),
3462
3564
  )
3463
3565
  return
@@ -3577,8 +3679,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3577
3679
 
3578
3680
  const failoverGithubReviewRound = async (live: LiveSession): Promise<void> => {
3579
3681
  const round = live.githubReviewRound
3580
- if (round === null || isGithubReviewRoundComplete(round)) return
3581
- if (hasGithubReviewRoundDismissalAttempt(round)) {
3682
+ if (round === null || isGithubReviewRoundComplete(round, now)) return
3683
+ if (hasGithubReviewRoundDismissalAttempt(round, now)) {
3582
3684
  const key = githubReviewRoundKey(round)
3583
3685
  for (const sibling of liveSessions.values()) {
3584
3686
  if (sibling.githubReviewRound !== null && githubReviewRoundKey(sibling.githubReviewRound) === key) {
@@ -3604,10 +3706,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3604
3706
  candidate.key.thread !== round.carrierThread,
3605
3707
  )
3606
3708
  const waiter = candidates
3607
- .filter((candidate) => canPromoteGithubReviewRoundTo(round, candidate.key.thread))
3709
+ .filter((candidate) => canPromoteGithubReviewRoundTo(round, candidate.key.thread, now))
3608
3710
  .sort((a, b) => a.keyId.localeCompare(b.keyId))[0]
3609
3711
  if (waiter === undefined) {
3610
- const state = githubReviewRoundPersistence(round)
3712
+ const state = githubReviewRoundPersistence(round, now)
3611
3713
  if (candidates.length === 0) {
3612
3714
  logger.warn(
3613
3715
  `[channels] github review round failover found no live waiter pr=${round.workspace}#${round.prNumber} head=${round.headSha} carrier=${round.carrierThread ?? 'root'}; retry the review after the round expires`,
@@ -3620,7 +3722,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3620
3722
  return
3621
3723
  }
3622
3724
 
3623
- const promoted = promoteGithubReviewRound(round, waiter.key.thread)
3725
+ const promoted = promoteGithubReviewRound(round, waiter.key.thread, now)
3624
3726
  if (promoted === null) return
3625
3727
  for (const sibling of liveSessions.values()) {
3626
3728
  if (
@@ -3677,11 +3779,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3677
3779
  }
3678
3780
  }
3679
3781
 
3680
- const stopCurrentChannelTurn = async (live: LiveSession): Promise<void> => {
3782
+ const stopCurrentChannelTurn = async (live: LiveSession, reason: string): Promise<boolean> => {
3681
3783
  live.userStoppedTurnSeq = live.turnSeq
3682
3784
  live.lastTerminalReplyCompletion = null
3683
3785
  live.pendingTerminalReplyStop = null
3684
- live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'user_stop' }
3786
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason }
3685
3787
  if (live.debounceTimer) clearTimeout(live.debounceTimer)
3686
3788
  live.debounceTimer = null
3687
3789
  live.firstUnprocessedAt = 0
@@ -3696,15 +3798,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3696
3798
  stopReason: 'aborted',
3697
3799
  })
3698
3800
  await stopTypingHeartbeat(live)
3801
+ let aborted = true
3699
3802
  try {
3700
3803
  await live.session.abort()
3701
- logger.info(
3702
- `[channels] ${live.keyId}: command /stop aborted current turn site=user_stop session=${live.sessionId} reason=user_stop`,
3703
- )
3804
+ if (reason === 'user_stop') {
3805
+ logger.info(
3806
+ `[channels] ${live.keyId}: command /stop aborted current turn site=user_stop session=${live.sessionId} reason=user_stop`,
3807
+ )
3808
+ } else {
3809
+ logger.info(
3810
+ `[channels] ${live.keyId}: github PR turn aborted site=github_pr_abort session=${live.sessionId} reason=${JSON.stringify(reason)}`,
3811
+ )
3812
+ }
3704
3813
  } catch (err) {
3705
- logger.warn(`[channels] ${live.keyId}: command /stop abort failed: ${describeError(err)}`)
3814
+ aborted = false
3815
+ if (reason === 'user_stop') {
3816
+ logger.warn(`[channels] ${live.keyId}: command /stop abort failed: ${describeError(err)}`)
3817
+ } else {
3818
+ logger.warn(
3819
+ `[channels] ${live.keyId}: github PR turn abort failed reason=${JSON.stringify(reason)}: ${describeError(err)}`,
3820
+ )
3821
+ }
3706
3822
  }
3707
3823
  await awaitLatestTodoOutcomeWrite(live)
3824
+ return aborted
3708
3825
  }
3709
3826
 
3710
3827
  // ensureLive() installs a session BEFORE the engage/observe decision, so a
@@ -3715,6 +3832,69 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3715
3832
  const hasStoppableWork = (live: LiveSession): boolean =>
3716
3833
  live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0
3717
3834
 
3835
+ const abortGithubPrTurn = async (
3836
+ workspace: string,
3837
+ prNumber: number,
3838
+ reason: string,
3839
+ ): Promise<
3840
+ | { kind: 'aborted'; matchedSessions: number; matchedReviewers: number; abortFailures: number }
3841
+ | { kind: 'no-live-session' }
3842
+ > => {
3843
+ const chat = `pr:${prNumber}`
3844
+ const matchesPr = (live: LiveSession): boolean =>
3845
+ !live.destroyed && live.key.adapter === 'github' && live.key.workspace === workspace && live.key.chat === chat
3846
+ const allPrSessions = Array.from(liveSessions.values()).filter(matchesPr)
3847
+ const stoppableSessions = allPrSessions.filter(hasStoppableWork)
3848
+
3849
+ abortGithubReviewStateForPr(workspace, prNumber)
3850
+ for (const live of allPrSessions) {
3851
+ live.githubReviewRound = null
3852
+ live.pendingGithubReviewRoundCloseout = null
3853
+ }
3854
+
3855
+ const subagentAbort = (
3856
+ options.cancelRunningSubagentsByWorkKey?.(githubReviewerWorkKey(workspace, prNumber), reason) ??
3857
+ Promise.resolve({ matched: 0, cancelled: 0, failures: 0 })
3858
+ ).catch((err) => {
3859
+ logger.warn(
3860
+ `[channels] github reviewer abort failed pr=${workspace}#${prNumber} reason=${JSON.stringify(reason)}: ${describeError(err)}`,
3861
+ )
3862
+ return { matched: 0, cancelled: 0, failures: 1 }
3863
+ })
3864
+ const sessionAborts = Promise.all(stoppableSessions.map((live) => stopCurrentChannelTurn(live, reason)))
3865
+ const persistedRoundClear = (async (): Promise<void> => {
3866
+ await ensureLoaded()
3867
+ if (mappings === null) return
3868
+ let changed = false
3869
+ for (const [index, record] of mappings.entries()) {
3870
+ if (record.adapter !== 'github' || record.workspace !== workspace || record.chat !== chat) continue
3871
+ if (record.githubReviewRound === undefined) continue
3872
+ const { githubReviewRound: _removed, ...rest } = record
3873
+ void _removed
3874
+ mappings[index] = rest
3875
+ changed = true
3876
+ }
3877
+ if (changed) await persist()
3878
+ })().catch((err) => {
3879
+ logger.warn(`[channels] github review round clear failed pr=${workspace}#${prNumber}: ${describeError(err)}`)
3880
+ })
3881
+
3882
+ const [sessionResults, subagentResult] = await Promise.all([sessionAborts, subagentAbort, persistedRoundClear])
3883
+ const abortFailures = sessionResults.filter((succeeded) => !succeeded).length + subagentResult.failures
3884
+ logger.info(
3885
+ `[channels] github PR abort pr=${workspace}#${prNumber} sessions=${stoppableSessions.length} ` +
3886
+ `reviewers=${subagentResult.matched} failures=${abortFailures} reason=${JSON.stringify(reason)}`,
3887
+ )
3888
+ return stoppableSessions.length === 0 && subagentResult.matched === 0
3889
+ ? { kind: 'no-live-session' }
3890
+ : {
3891
+ kind: 'aborted',
3892
+ matchedSessions: stoppableSessions.length,
3893
+ matchedReviewers: subagentResult.matched,
3894
+ abortFailures,
3895
+ }
3896
+ }
3897
+
3718
3898
  const hasPendingContinueReply = (live: LiveSession): boolean => {
3719
3899
  const progressReply = live.continueReplyTurn
3720
3900
  return (
@@ -3898,7 +4078,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3898
4078
  live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
3899
4079
  const trigger = batch[batch.length - 1]!
3900
4080
  if (trigger.githubReviewRound !== undefined) {
3901
- live.githubReviewRound = registerGithubReviewRound(trigger.githubReviewRound)
4081
+ live.githubReviewRound = registerGithubReviewRound(trigger.githubReviewRound, now(), now)
3902
4082
  }
3903
4083
  live.currentTurnExplicitlyAddressed =
3904
4084
  trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
@@ -3922,15 +4102,31 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3922
4102
  live.willingnessNudges = 0
3923
4103
  live.logicalTurnStartedAt = now()
3924
4104
  const stampedCloseout = batch.findLast((item) => item.githubReviewThreadCloseout !== undefined)
4105
+ const deferredCloseout =
4106
+ stampedCloseout?.githubReviewThreadCloseout === undefined &&
4107
+ live.githubReviewThreadCloseout !== null &&
4108
+ live.githubReviewThreadCloseout.deferred
4109
+ ? live.githubReviewThreadCloseout
4110
+ : null
3925
4111
  live.githubReviewThreadCloseout =
3926
4112
  stampedCloseout?.githubReviewThreadCloseout !== undefined
3927
4113
  ? {
3928
4114
  ...stampedCloseout.githubReviewThreadCloseout,
3929
- sendCountAtStart: live.successfulChannelSends,
3930
4115
  startedAt: live.logicalTurnStartedAt,
3931
4116
  correctionAttempts: 0,
4117
+ deferred: false,
3932
4118
  }
3933
- : null
4119
+ : deferredCloseout === null
4120
+ ? null
4121
+ : {
4122
+ ...deferredCloseout,
4123
+ startedAt: live.logicalTurnStartedAt,
4124
+ correctionAttempts: 0,
4125
+ }
4126
+ if (stampedCloseout?.githubReviewThreadCloseout !== undefined) {
4127
+ persistGithubReviewThreadCloseout(live, null)
4128
+ }
4129
+ live.githubReviewThreadCloseoutDecisionTurn = null
3934
4130
  // A fresh batch supersedes a still-pending staged fallback. That staged
3935
4131
  // turn produced no usable reply, so it must not leave the PRIOR turn's
3936
4132
  // committed lastQuestionSignal behind — otherwise the new question would
@@ -4702,7 +4898,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4702
4898
  ts: event.ts,
4703
4899
  })
4704
4900
  if (event.githubReviewRound !== undefined) {
4705
- live.githubReviewRound = registerGithubReviewRound(event.githubReviewRound)
4901
+ live.githubReviewRound = registerGithubReviewRound(event.githubReviewRound, now(), now)
4706
4902
  persistGithubReviewRound(live, live.githubReviewRound)
4707
4903
  }
4708
4904
  // Make the typing anchor live BEFORE startTypingHeartbeat fires (route()
@@ -5548,21 +5744,6 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5548
5744
 
5549
5745
  if (live) {
5550
5746
  live.successfulChannelSends++
5551
- const closeout = live.githubReviewThreadCloseout
5552
- if (closeout !== null) {
5553
- const landedOnOwedThread =
5554
- msg.adapter === 'github' &&
5555
- msg.workspace === closeout.workspace &&
5556
- msg.chat === `pr:${closeout.prNumber}` &&
5557
- (msg.thread ?? null) === closeout.rootCommentId
5558
- if (landedOnOwedThread) {
5559
- live.githubReviewThreadCloseout = null
5560
- } else {
5561
- // successfulChannelSends is session-wide. Advance the baseline for an
5562
- // unrelated delivery so equality continues to mean no owed-thread send.
5563
- closeout.sendCountAtStart++
5564
- }
5565
- }
5566
5747
  // Promise fulfillment follows OUTPUT KIND, never source:
5567
5748
  // (a) ordinary substantive tool output clears;
5568
5749
  // (b) multilingual continuation-willingness/status output preserves;
@@ -5645,6 +5826,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5645
5826
  const record = live.lastTerminalReplyCompletion
5646
5827
  live.lastTerminalReplyCompletion = null
5647
5828
  if (record === null || record.turnSeq !== live.turnSeq) return
5829
+ if (live.githubReviewThreadCloseout !== null || live.githubReviewThreadCloseoutDecisionTurn === live.turnSeq) {
5830
+ return
5831
+ }
5648
5832
  if (live.willingnessNudges >= MAX_WILLINGNESS_NUDGES) return
5649
5833
  if (live.promptQueue.length > 0) return
5650
5834
  if (record.text === undefined) return
@@ -5831,6 +6015,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5831
6015
  if (
5832
6016
  live.promptQueue.length === 0 &&
5833
6017
  live.currentTurnAuthorId !== null &&
6018
+ live.githubReviewThreadCloseout === null &&
6019
+ live.githubReviewThreadCloseoutDecisionTurn !== live.turnSeq &&
5834
6020
  live.continueReplyTurn?.turnSeq === live.turnSeq &&
5835
6021
  live.continueReplyTurn.sendCount === live.successfulChannelSends &&
5836
6022
  isFreshEmptyStopAfterSend(live) &&
@@ -5871,7 +6057,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5871
6057
  // batch — so injecting a stale recovery nudge would prepend it to a live user
5872
6058
  // message. Skip the nudge AND the fallback in that case and let the trailing
5873
6059
  // recovery below run; the queued inbound supersedes this turn's silence.
5874
- if (live.promptQueue.length === 0 && live.currentTurnAuthorId !== null && isEmptyStopAfterWillingnessAck(live)) {
6060
+ if (
6061
+ live.promptQueue.length === 0 &&
6062
+ live.currentTurnAuthorId !== null &&
6063
+ live.githubReviewThreadCloseout === null &&
6064
+ live.githubReviewThreadCloseoutDecisionTurn !== live.turnSeq &&
6065
+ isEmptyStopAfterWillingnessAck(live)
6066
+ ) {
5875
6067
  if (live.willingnessNudges < MAX_WILLINGNESS_NUDGES) {
5876
6068
  live.willingnessNudges++
5877
6069
  logger.warn(
@@ -6387,6 +6579,29 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6387
6579
 
6388
6580
  const runIdleGc = async (): Promise<void> => {
6389
6581
  await expirePendingReloadHandoffs()
6582
+ for (const live of liveSessions.values()) {
6583
+ const closeout = live.githubReviewThreadCloseout
6584
+ const round = live.githubReviewRound
6585
+ if (live.destroyed || closeout === null) continue
6586
+ const unknownStateExpired =
6587
+ closeout.deferUntil?.kind === 'review-state-unknown' && closeout.deferUntil.expiresAt <= now()
6588
+ if (round === null && !unknownStateExpired) continue
6589
+ if (round?.carrierThread === live.key.thread) continue
6590
+ if (live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0) continue
6591
+ if (deferredPendingReviewRound(live) !== null) continue
6592
+ if (isAwaitingBackgroundChild(live, 'github-thread-closeout-release', closeout.startedAt)) continue
6593
+ const reason =
6594
+ round === null
6595
+ ? 'review_state_unknown_expired'
6596
+ : isGithubReviewRoundComplete(round, now)
6597
+ ? 'round_completed'
6598
+ : 'round_expired'
6599
+ logger.info(
6600
+ `[channels] ${live.keyId} github_thread_closeout_released pr=${closeout.prNumber} root=${closeout.rootCommentId}${round === null ? '' : ` round=${round.roundId}`} reason=${reason}`,
6601
+ )
6602
+ await enforceGithubReviewThreadCloseout(live)
6603
+ if (!live.draining && live.pendingSystemReminders.length > 0) void drain(live)
6604
+ }
6390
6605
  const t = now()
6391
6606
  const victims: LiveSession[] = []
6392
6607
  for (const live of liveSessions.values()) {
@@ -6908,7 +7123,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6908
7123
  )
6909
7124
  const round = publisher?.githubReviewRound ?? persistedPublisher?.githubReviewRound
6910
7125
  if (round === null || round === undefined) {
6911
- const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber)
7126
+ const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber, now)
6912
7127
  if (resetRound !== null) persistMatchingGithubReviewRound(resetRound)
6913
7128
  logger.warn(
6914
7129
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: no publisher session with round state session=${args.sessionId}`,
@@ -6916,7 +7131,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6916
7131
  return { kind: 'no-round' }
6917
7132
  }
6918
7133
 
6919
- const activeRound = registerGithubReviewRound(round)
7134
+ const activeRound = registerGithubReviewRound(round, now(), now)
6920
7135
  if (activeRound === null) {
6921
7136
  logger.warn(
6922
7137
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: round expired`,
@@ -6925,22 +7140,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6925
7140
  }
6926
7141
  const publisherThread = publisher?.key.thread ?? persistedPublisher?.thread ?? null
6927
7142
  if (activeRound.carrierThread !== publisherThread) {
6928
- resetGithubReviewRoundCompletion(activeRound)
7143
+ resetGithubReviewRoundCompletion(activeRound, now)
6929
7144
  persistMatchingGithubReviewRound(activeRound)
6930
7145
  logger.warn(
6931
7146
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: publisher thread=${publisherThread ?? 'root'} is not carrier=${activeRound.carrierThread ?? 'root'}`,
6932
7147
  )
6933
7148
  return { kind: 'no-round' }
6934
7149
  }
6935
- if (!(await validateGithubReviewRound(activeRound))) {
6936
- resetGithubReviewRoundCompletion(activeRound)
7150
+ if (!(await validateGithubReviewRound(activeRound, undefined, now))) {
7151
+ resetGithubReviewRoundCompletion(activeRound, now)
6937
7152
  persistMatchingGithubReviewRound(activeRound)
6938
7153
  logger.warn(
6939
7154
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: head mismatch or unavailable expected=${activeRound.headSha}`,
6940
7155
  )
6941
7156
  return { kind: 'no-round' }
6942
7157
  }
6943
- completeGithubReviewRound(activeRound)
7158
+ completeGithubReviewRound(activeRound, now)
6944
7159
  const key = githubReviewRoundKey(round)
6945
7160
  for (const live of liveSessions.values()) {
6946
7161
  if (live.githubReviewRound === null || githubReviewRoundKey(live.githubReviewRound) !== key) continue
@@ -6962,7 +7177,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6962
7177
  const persistMatchingGithubReviewRound = (round: GithubReviewFollowupRound): void => {
6963
7178
  if (mappings === null) return
6964
7179
  const key = githubReviewRoundKey(round)
6965
- const state = githubReviewRoundPersistence(round)
7180
+ const state = githubReviewRoundPersistence(round, now)
6966
7181
  let changed = false
6967
7182
  for (const [idx, record] of mappings.entries()) {
6968
7183
  if (record.githubReviewRound === undefined) continue
@@ -6980,7 +7195,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6980
7195
  }
6981
7196
 
6982
7197
  // A close-out can land while completion is still awaiting head validation, so
6983
- // `finishGithubReviewRoundCloseout` sees a pending round and returns without
7198
+ // `finishGithubReviewThreadCloseout` sees a pending round and returns without
6984
7199
  // clearing. Nothing else retries it, which would strand round metadata on the
6985
7200
  // session and reject its later verdicts — so the close-out is recorded and
6986
7201
  // replayed here once the round actually completes.
@@ -6989,20 +7204,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6989
7204
  for (const live of liveSessions.values()) {
6990
7205
  if (live.pendingGithubReviewRoundCloseout !== key) continue
6991
7206
  live.pendingGithubReviewRoundCloseout = null
6992
- finishGithubReviewRoundCloseout({
7207
+ finishGithubReviewThreadCloseout({
6993
7208
  sessionId: live.sessionId,
6994
7209
  workspace: live.key.workspace,
6995
7210
  prNumber: Number(live.key.chat.slice('pr:'.length)),
6996
7211
  thread: live.key.thread ?? null,
7212
+ decision: 'resolved',
6997
7213
  })
6998
7214
  }
6999
7215
  }
7000
7216
 
7001
- const finishGithubReviewRoundCloseout = (args: {
7217
+ const finishGithubReviewThreadCloseout = (args: {
7002
7218
  sessionId: string
7003
7219
  workspace: string
7004
7220
  prNumber: number
7005
7221
  thread: string | null
7222
+ decision: 'resolved' | 'left-open'
7006
7223
  }): void => {
7007
7224
  const chat = `pr:${args.prNumber}`
7008
7225
  const live = Array.from(liveSessions.values()).find(
@@ -7014,10 +7231,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7014
7231
  candidate.key.chat === chat &&
7015
7232
  candidate.key.thread === args.thread,
7016
7233
  )
7017
- if (live !== undefined) live.githubReviewThreadCloseout = null
7234
+ if (live !== undefined) {
7235
+ live.githubReviewThreadCloseoutDecisionTurn = live.turnSeq
7236
+ clearGithubReviewThreadCloseout(live)
7237
+ logger.info(
7238
+ `[channels] ${live.keyId} github_thread_closeout_decided decision=${args.decision} turn=${live.turnSeq}`,
7239
+ )
7240
+ }
7018
7241
  if (live?.githubReviewRound === null || live?.githubReviewRound === undefined) return
7019
7242
  const round = live.githubReviewRound
7020
- if (!isGithubReviewRoundComplete(round)) {
7243
+ if (!isGithubReviewRoundComplete(round, now)) {
7021
7244
  live.pendingGithubReviewRoundCloseout = githubReviewRoundKey(round)
7022
7245
  return
7023
7246
  }
@@ -7094,8 +7317,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7094
7317
  const hasOutstandingGithubReviewThreadCloseout = (sessionId: string): boolean => {
7095
7318
  for (const live of liveSessions.values()) {
7096
7319
  if (live.destroyed || live.sessionId !== sessionId) continue
7097
- const obligation = live.githubReviewThreadCloseout
7098
- return obligation !== null && live.successfulChannelSends === obligation.sendCountAtStart
7320
+ return live.githubReviewThreadCloseout !== null
7099
7321
  }
7100
7322
  return false
7101
7323
  }
@@ -7338,8 +7560,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7338
7560
  getSelfAliases: computeSelfAliases,
7339
7561
  injectSubagentCompletionReminder,
7340
7562
  injectPrVerdictActivity,
7563
+ abortGithubPrTurn,
7341
7564
  completeGithubReviewRound: completeRoundForVerifiedVerdict,
7342
- finishGithubReviewRoundCloseout,
7565
+ finishGithubReviewThreadCloseout,
7343
7566
  noteGithubReviewOutput,
7344
7567
  hasOutstandingGithubReviewThreadCloseout,
7345
7568
  markTurnSkipped,