typeclaw 0.48.9 → 0.48.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +176 -0
  5. package/src/agent/index.ts +9 -0
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/agent/tools/subagent-cancel.ts +14 -2
  12. package/src/bundled-plugins/backup/README.md +4 -3
  13. package/src/bundled-plugins/backup/runner.ts +125 -32
  14. package/src/bundled-plugins/github-cli-auth/gh-command.ts +106 -9
  15. package/src/bundled-plugins/github-cli-auth/git-command.ts +94 -9
  16. package/src/bundled-plugins/github-cli-auth/index.ts +45 -5
  17. package/src/channels/adapters/github/inbound.ts +210 -27
  18. package/src/channels/adapters/github/index.ts +16 -18
  19. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  20. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  21. package/src/channels/adapters/github/review-submitter.ts +28 -0
  22. package/src/channels/adapters/instagram-continuity-store.ts +141 -0
  23. package/src/channels/adapters/instagram.ts +149 -4
  24. package/src/channels/github-repo.ts +11 -0
  25. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  26. package/src/channels/github-verdict-activity.ts +12 -6
  27. package/src/channels/manager.ts +10 -0
  28. package/src/channels/persistence.ts +28 -2
  29. package/src/channels/router.ts +371 -33
  30. package/src/channels/schema.ts +18 -0
  31. package/src/channels/types.ts +11 -0
  32. package/src/cli/compose.ts +7 -4
  33. package/src/compose/restart.ts +26 -16
  34. package/src/compose/start.ts +24 -14
  35. package/src/config/config.ts +9 -1
  36. package/src/container/restart.ts +4 -0
  37. package/src/container/shared.ts +30 -3
  38. package/src/container/start.ts +137 -56
  39. package/src/doctor/apparmor.ts +101 -0
  40. package/src/doctor/checks.ts +2 -0
  41. package/src/hostd/daemon.ts +40 -17
  42. package/src/init/dockerfile.ts +7 -6
  43. package/src/init/windows-dev-link.ts +34 -2
  44. package/src/run/channel-session-factory.ts +35 -15
  45. package/src/run/index.ts +1 -0
  46. package/src/sandbox/availability.ts +7 -5
  47. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  48. package/typeclaw.schema.json +7 -0
@@ -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,
@@ -114,6 +117,7 @@ import type {
114
117
  HistoryCallback,
115
118
  InboundAttachment,
116
119
  GithubReviewFollowupRound,
120
+ GithubReviewThreadCloseout,
117
121
  InboundMessage,
118
122
  InboundReferenceContext,
119
123
  ListCallback,
@@ -419,6 +423,8 @@ export const STRANDED_TOOLUSE_CONTINUATION_NUDGE = [
419
423
  // drop so the human is never left staring at dead air after a degenerate turn.
420
424
  export const EMPTY_TURN_FALLBACK_TEXT =
421
425
  "⚠️ I got stuck putting together a reply and couldn't finish. Could you rephrase or try again?"
426
+ export const GITHUB_REVIEW_THREAD_CLOSEOUT_FALLBACK_TEXT =
427
+ "I wasn't able to complete this follow-up. Leaving this thread open for manual review."
422
428
  // Distinct from EMPTY_TURN_RETRY_NUDGE: that one diagnoses budget exhaustion
423
429
  // ("ran out of output budget"), which is FALSE for a clean `stop` with empty
424
430
  // text. This nudge names the real failure — a turn that ended sending nothing
@@ -770,6 +776,7 @@ type QueuedInbound = {
770
776
  // prefix for those).
771
777
  ts: number
772
778
  githubReviewRound?: GithubReviewFollowupRound
779
+ githubReviewThreadCloseout?: GithubReviewThreadCloseout
773
780
  }
774
781
 
775
782
  type ObservedInbound = {
@@ -878,6 +885,16 @@ type LiveSession = {
878
885
  resolvedNames: ResolvedChannelNames
879
886
  originRef: { current: SessionOrigin | undefined }
880
887
  githubReviewRound: GithubReviewFollowupRound | null
888
+ // A real-user reply to one of this agent's own review-thread roots must end
889
+ // with a reply on that exact thread. This spans reminder-only retry iterations.
890
+ githubReviewThreadCloseout:
891
+ | (GithubReviewThreadCloseout & {
892
+ startedAt: number
893
+ correctionAttempts: number
894
+ deferred: boolean
895
+ })
896
+ | null
897
+ githubReviewThreadCloseoutDecisionTurn: number | null
881
898
  // Round key of a close-out that arrived while the round was still pending
882
899
  // completion. Replayed once the round completes; see replayPendingRoundCloseouts.
883
900
  pendingGithubReviewRoundCloseout: string | null
@@ -1566,17 +1583,26 @@ export type ChannelRouter = {
1566
1583
  verdict: ReviewRoundOutcome
1567
1584
  sessionId: string
1568
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
+ >
1569
1594
  completeGithubReviewRound?: (args: {
1570
1595
  workspace: string
1571
1596
  prNumber: number
1572
1597
  verdict: ReviewRoundOutcome
1573
1598
  sessionId: string
1574
1599
  }) => Promise<{ kind: 'completed' | 'no-round' }>
1575
- finishGithubReviewRoundCloseout?: (args: {
1600
+ finishGithubReviewThreadCloseout?: (args: {
1576
1601
  sessionId: string
1577
1602
  workspace: string
1578
1603
  prNumber: number
1579
1604
  thread: string | null
1605
+ decision: 'resolved' | 'left-open'
1580
1606
  }) => void
1581
1607
  noteGithubReviewOutput: (args: {
1582
1608
  sessionId: string
@@ -1584,6 +1610,7 @@ export type ChannelRouter = {
1584
1610
  prNumber: number
1585
1611
  state: ReviewOutputState
1586
1612
  }) => { kind: 'stamped' | 'no-live-session' }
1613
+ hasOutstandingGithubReviewThreadCloseout?: (sessionId: string) => boolean
1587
1614
  // Record that the agent invoked `skip_response` during the current turn
1588
1615
  // for the channel session identified by `parentSessionId`. The reason is
1589
1616
  // logged at INFO level inside `validateChannelTurn` (single log line per
@@ -1810,6 +1837,10 @@ export type CreateChannelRouterOptions = {
1810
1837
  // work in the resume greeting. Background-only: a foreground child returns its
1811
1838
  // result inline, so it is not orphaned by the bounce. Omitted means none.
1812
1839
  listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
1840
+ cancelRunningSubagentsByWorkKey?: (
1841
+ workKey: string,
1842
+ reason: string,
1843
+ ) => Promise<{ matched: number; cancelled: number; failures: number }>
1813
1844
  }
1814
1845
 
1815
1846
  export type RestartCommandContext = {
@@ -1942,7 +1973,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1942
1973
  handler: async ({ live }) => {
1943
1974
  // requiresLiveSession:true guarantees the dispatch layer resolved a
1944
1975
  // session before running this handler, so `live` is non-null here.
1945
- await stopCurrentChannelTurn(live!)
1976
+ await stopCurrentChannelTurn(live!, 'user_stop')
1946
1977
  return { reply: 'Stopped the current turn.' }
1947
1978
  },
1948
1979
  },
@@ -2045,7 +2076,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2045
2076
  void _removed
2046
2077
  mappings[idx] = rest
2047
2078
  } else {
2048
- const state = githubReviewRoundPersistence(round)
2079
+ const state = githubReviewRoundPersistence(round, now)
2049
2080
  if (state === null) {
2050
2081
  const { githubReviewRound: _expired, ...rest } = record
2051
2082
  void _expired
@@ -2057,6 +2088,32 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2057
2088
  void persist()
2058
2089
  }
2059
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
+
2060
2117
  const createForChannel: CreateSessionForChannel =
2061
2118
  options.createSessionForChannel ??
2062
2119
  (async ({ key, existingSessionId, existingSessionFile, origin, originRef }) => {
@@ -2217,9 +2274,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2217
2274
  // still run. Session scope would let one long-running child silence every
2218
2275
  // subsequent turn, and a wedged child would strand them with nothing to revisit
2219
2276
  // them after the backstop expires.
2220
- const isAwaitingBackgroundChild = (live: LiveSession, label: string): boolean => {
2277
+ const isAwaitingBackgroundChild = (
2278
+ live: LiveSession,
2279
+ label: string,
2280
+ startedAt = live.logicalTurnStartedAt,
2281
+ ): boolean => {
2221
2282
  const childStartedAt = newestRunningChildSubagentStartedAt(live.sessionId)
2222
- if (childStartedAt === null || childStartedAt < live.logicalTurnStartedAt) return false
2283
+ if (childStartedAt === null || childStartedAt < startedAt) return false
2223
2284
  return isPinnedByRunningChild(live.sessionId, live.keyId, label)
2224
2285
  }
2225
2286
 
@@ -2447,6 +2508,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2447
2508
  thread: prev.thread,
2448
2509
  participants: prev.participants,
2449
2510
  lastInboundAt: 0,
2511
+ ...(prev.githubReviewThreadCloseout !== undefined && prev.githubReviewRound !== undefined
2512
+ ? { githubReviewRound: prev.githubReviewRound }
2513
+ : {}),
2514
+ ...(prev.githubReviewThreadCloseout !== undefined
2515
+ ? { githubReviewThreadCloseout: prev.githubReviewThreadCloseout }
2516
+ : {}),
2450
2517
  }
2451
2518
  await persist()
2452
2519
  }
@@ -2493,6 +2560,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2493
2560
  participants: record.participants,
2494
2561
  lastInboundAt: 0,
2495
2562
  ...(record.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
2563
+ ...(record.githubReviewThreadCloseout !== undefined
2564
+ ? { githubReviewThreadCloseout: record.githubReviewThreadCloseout }
2565
+ : {}),
2496
2566
  }
2497
2567
  if (mappings) {
2498
2568
  const idx = mappings.findIndex(
@@ -2521,13 +2591,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2521
2591
  sessionFile: resumeTarget.sessionFile,
2522
2592
  participants: (record?.participants ?? []) as ChannelParticipant[],
2523
2593
  lastInboundAt: now(),
2594
+ ...(record?.githubReviewRound !== undefined ? { githubReviewRound: record.githubReviewRound } : {}),
2595
+ ...(record?.githubReviewThreadCloseout !== undefined
2596
+ ? { githubReviewThreadCloseout: record.githubReviewThreadCloseout }
2597
+ : {}),
2524
2598
  }
2525
2599
  }
2600
+ const restoredDeferredCloseout = resolvedRecord?.githubReviewThreadCloseout ?? null
2526
2601
  let restoredRound: GithubReviewFollowupRound | null = null
2527
2602
  let restoredRoundStatus: 'pending' | 'completed' | null = null
2528
2603
  if (resolvedRecord?.githubReviewRound !== undefined) {
2529
2604
  if (
2530
- await validateGithubReviewRound(resolvedRecord.githubReviewRound, resolvedRecord.githubReviewRound.createdAt)
2605
+ await validateGithubReviewRound(
2606
+ resolvedRecord.githubReviewRound,
2607
+ resolvedRecord.githubReviewRound.createdAt,
2608
+ now,
2609
+ )
2531
2610
  ) {
2532
2611
  restoredRoundStatus = resolvedRecord.githubReviewRound.status
2533
2612
  restoredRound = restoreGithubReviewRound(
@@ -2537,6 +2616,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2537
2616
  resolvedRecord.githubReviewRound.dismissalAttempted === true,
2538
2617
  resolvedRecord.githubReviewRound.requestChangesAttempted === true,
2539
2618
  resolvedRecord.githubReviewRound.createdAt,
2619
+ now,
2540
2620
  )
2541
2621
  } else {
2542
2622
  logger.info(
@@ -2617,10 +2697,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2617
2697
  participants,
2618
2698
  ...(restoredRound !== null && restoredRoundStatus !== null
2619
2699
  ? (() => {
2620
- const state = githubReviewRoundPersistence(restoredRound)
2700
+ const state = githubReviewRoundPersistence(restoredRound, now)
2621
2701
  return state === null ? {} : { githubReviewRound: { ...restoredRound, ...state } }
2622
2702
  })()
2623
2703
  : {}),
2704
+ ...(restoredDeferredCloseout !== null ? { githubReviewThreadCloseout: restoredDeferredCloseout } : {}),
2624
2705
  }
2625
2706
  if (mappings) {
2626
2707
  const idx = mappings.findIndex(
@@ -2660,6 +2741,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2660
2741
  resolvedNames,
2661
2742
  originRef,
2662
2743
  githubReviewRound: restoredRound,
2744
+ githubReviewThreadCloseout:
2745
+ restoredDeferredCloseout === null
2746
+ ? null
2747
+ : {
2748
+ ...restoredDeferredCloseout,
2749
+ startedAt: now(),
2750
+ correctionAttempts: 0,
2751
+ deferred: true,
2752
+ },
2753
+ githubReviewThreadCloseoutDecisionTurn: null,
2663
2754
  pendingGithubReviewRoundCloseout: null,
2664
2755
  promptQueue: [],
2665
2756
  pendingSystemReminders: [],
@@ -3393,6 +3484,89 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3393
3484
  }
3394
3485
  }
3395
3486
 
3487
+ const postGithubReviewThreadCloseoutFallback = async (live: LiveSession): Promise<void> => {
3488
+ const obligation = live.githubReviewThreadCloseout
3489
+ if (obligation === null) return
3490
+ // Consume before sending so adapter failure cannot turn this one-shot
3491
+ // fallback into a reminder/fallback loop.
3492
+ clearGithubReviewThreadCloseout(live)
3493
+ logger.warn(
3494
+ `[channels] ${live.keyId} github_thread_closeout_fallback pr=${obligation.prNumber} root=${obligation.rootCommentId}`,
3495
+ )
3496
+ const result = await send(
3497
+ {
3498
+ adapter: 'github',
3499
+ workspace: obligation.workspace,
3500
+ chat: `pr:${obligation.prNumber}`,
3501
+ thread: obligation.rootCommentId,
3502
+ text: GITHUB_REVIEW_THREAD_CLOSEOUT_FALLBACK_TEXT,
3503
+ },
3504
+ { source: 'system', outputKind: 'meta' },
3505
+ )
3506
+ if (!result.ok) {
3507
+ logger.warn(`[channels] ${live.keyId}: github review-thread closeout fallback send failed: ${result.error}`)
3508
+ }
3509
+ }
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
+
3521
+ const enforceGithubReviewThreadCloseout = async (live: LiveSession): Promise<void> => {
3522
+ const closeout = live.githubReviewThreadCloseout
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
+ )
3547
+ return
3548
+ }
3549
+ if (live.skippedTurn?.turnSeq === live.turnSeq) live.skippedTurn = null
3550
+ if (closeout.correctionAttempts === 0) {
3551
+ closeout.correctionAttempts++
3552
+ logger.warn(
3553
+ `[channels] ${live.keyId} github_thread_closeout_retry attempt=1/1 pr=${closeout.prNumber} root=${closeout.rootCommentId}`,
3554
+ )
3555
+ live.pendingSystemReminders.push(
3556
+ retryReminder(
3557
+ `<system-reminder>\nThis session still owes a close-out on GitHub PR #${closeout.prNumber}, ` +
3558
+ `review thread root comment ${closeout.rootCommentId}. Your previous turn sent no reply to that thread. ` +
3559
+ `Call channel_reply now with an explicit resolve_review_thread choice: true if the concern is addressed, ` +
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>`,
3563
+ ),
3564
+ )
3565
+ return
3566
+ }
3567
+ await postGithubReviewThreadCloseoutFallback(live)
3568
+ }
3569
+
3396
3570
  // Resolve a fallback STAGED by a willingness-ack exhaustion path, run AFTER
3397
3571
  // maybeContinueTodosChannel so the idle/todo continuation has already had its
3398
3572
  // chance to queue a re-prompt (the mechanism that self-recovers the promised
@@ -3505,8 +3679,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3505
3679
 
3506
3680
  const failoverGithubReviewRound = async (live: LiveSession): Promise<void> => {
3507
3681
  const round = live.githubReviewRound
3508
- if (round === null || isGithubReviewRoundComplete(round)) return
3509
- if (hasGithubReviewRoundDismissalAttempt(round)) {
3682
+ if (round === null || isGithubReviewRoundComplete(round, now)) return
3683
+ if (hasGithubReviewRoundDismissalAttempt(round, now)) {
3510
3684
  const key = githubReviewRoundKey(round)
3511
3685
  for (const sibling of liveSessions.values()) {
3512
3686
  if (sibling.githubReviewRound !== null && githubReviewRoundKey(sibling.githubReviewRound) === key) {
@@ -3532,10 +3706,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3532
3706
  candidate.key.thread !== round.carrierThread,
3533
3707
  )
3534
3708
  const waiter = candidates
3535
- .filter((candidate) => canPromoteGithubReviewRoundTo(round, candidate.key.thread))
3709
+ .filter((candidate) => canPromoteGithubReviewRoundTo(round, candidate.key.thread, now))
3536
3710
  .sort((a, b) => a.keyId.localeCompare(b.keyId))[0]
3537
3711
  if (waiter === undefined) {
3538
- const state = githubReviewRoundPersistence(round)
3712
+ const state = githubReviewRoundPersistence(round, now)
3539
3713
  if (candidates.length === 0) {
3540
3714
  logger.warn(
3541
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`,
@@ -3548,7 +3722,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3548
3722
  return
3549
3723
  }
3550
3724
 
3551
- const promoted = promoteGithubReviewRound(round, waiter.key.thread)
3725
+ const promoted = promoteGithubReviewRound(round, waiter.key.thread, now)
3552
3726
  if (promoted === null) return
3553
3727
  for (const sibling of liveSessions.values()) {
3554
3728
  if (
@@ -3605,11 +3779,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3605
3779
  }
3606
3780
  }
3607
3781
 
3608
- const stopCurrentChannelTurn = async (live: LiveSession): Promise<void> => {
3782
+ const stopCurrentChannelTurn = async (live: LiveSession, reason: string): Promise<boolean> => {
3609
3783
  live.userStoppedTurnSeq = live.turnSeq
3610
3784
  live.lastTerminalReplyCompletion = null
3611
3785
  live.pendingTerminalReplyStop = null
3612
- live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason: 'user_stop' }
3786
+ live.abortReasonThisTurn = { turnSeq: live.turnSeq, reason }
3613
3787
  if (live.debounceTimer) clearTimeout(live.debounceTimer)
3614
3788
  live.debounceTimer = null
3615
3789
  live.firstUnprocessedAt = 0
@@ -3624,15 +3798,30 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3624
3798
  stopReason: 'aborted',
3625
3799
  })
3626
3800
  await stopTypingHeartbeat(live)
3801
+ let aborted = true
3627
3802
  try {
3628
3803
  await live.session.abort()
3629
- logger.info(
3630
- `[channels] ${live.keyId}: command /stop aborted current turn site=user_stop session=${live.sessionId} reason=user_stop`,
3631
- )
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
+ }
3632
3813
  } catch (err) {
3633
- 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
+ }
3634
3822
  }
3635
3823
  await awaitLatestTodoOutcomeWrite(live)
3824
+ return aborted
3636
3825
  }
3637
3826
 
3638
3827
  // ensureLive() installs a session BEFORE the engage/observe decision, so a
@@ -3643,6 +3832,69 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3643
3832
  const hasStoppableWork = (live: LiveSession): boolean =>
3644
3833
  live.draining || live.promptQueue.length > 0 || live.pendingSystemReminders.length > 0
3645
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
+
3646
3898
  const hasPendingContinueReply = (live: LiveSession): boolean => {
3647
3899
  const progressReply = live.continueReplyTurn
3648
3900
  return (
@@ -3826,7 +4078,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3826
4078
  live.currentTurnReactionRef = batch[batch.length - 1]!.reactionRef ?? null
3827
4079
  const trigger = batch[batch.length - 1]!
3828
4080
  if (trigger.githubReviewRound !== undefined) {
3829
- live.githubReviewRound = registerGithubReviewRound(trigger.githubReviewRound)
4081
+ live.githubReviewRound = registerGithubReviewRound(trigger.githubReviewRound, now(), now)
3830
4082
  }
3831
4083
  live.currentTurnExplicitlyAddressed =
3832
4084
  trigger.isDm || trigger.isBotMention || trigger.replyToBotMessageId !== null
@@ -3849,6 +4101,32 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3849
4101
  live.emptyStopAfterToolWorkArmed = false
3850
4102
  live.willingnessNudges = 0
3851
4103
  live.logicalTurnStartedAt = now()
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
4111
+ live.githubReviewThreadCloseout =
4112
+ stampedCloseout?.githubReviewThreadCloseout !== undefined
4113
+ ? {
4114
+ ...stampedCloseout.githubReviewThreadCloseout,
4115
+ startedAt: live.logicalTurnStartedAt,
4116
+ correctionAttempts: 0,
4117
+ deferred: false,
4118
+ }
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
3852
4130
  // A fresh batch supersedes a still-pending staged fallback. That staged
3853
4131
  // turn produced no usable reply, so it must not leave the PRIOR turn's
3854
4132
  // committed lastQuestionSignal behind — otherwise the new question would
@@ -4076,6 +4354,10 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4076
4354
  sentReplyThisTurn && !live.promisedWorkOutstandingThisLogicalTurn,
4077
4355
  retryQueuedThisTurn,
4078
4356
  )
4357
+ // Provider notices own the first terminal output opportunity. A notice
4358
+ // that lands on the owed thread clears the obligation through send();
4359
+ // a suppressed or failed notice leaves it intact for this bounded net.
4360
+ await enforceGithubReviewThreadCloseout(live)
4079
4361
  await fireSessionTurnEnd(live)
4080
4362
  }
4081
4363
  await fireSessionIdle(live)
@@ -4609,11 +4891,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4609
4891
  isDm: event.isDm,
4610
4892
  ...(event.typingThread !== undefined ? { typingThread: event.typingThread } : {}),
4611
4893
  ...(event.githubReviewRound !== undefined ? { githubReviewRound: event.githubReviewRound } : {}),
4894
+ ...(event.githubReviewThreadCloseout !== undefined
4895
+ ? { githubReviewThreadCloseout: event.githubReviewThreadCloseout }
4896
+ : {}),
4612
4897
  receivedAt: now(),
4613
4898
  ts: event.ts,
4614
4899
  })
4615
4900
  if (event.githubReviewRound !== undefined) {
4616
- live.githubReviewRound = registerGithubReviewRound(event.githubReviewRound)
4901
+ live.githubReviewRound = registerGithubReviewRound(event.githubReviewRound, now(), now)
4617
4902
  persistGithubReviewRound(live, live.githubReviewRound)
4618
4903
  }
4619
4904
  // Make the typing anchor live BEFORE startTypingHeartbeat fires (route()
@@ -5541,6 +5826,9 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5541
5826
  const record = live.lastTerminalReplyCompletion
5542
5827
  live.lastTerminalReplyCompletion = null
5543
5828
  if (record === null || record.turnSeq !== live.turnSeq) return
5829
+ if (live.githubReviewThreadCloseout !== null || live.githubReviewThreadCloseoutDecisionTurn === live.turnSeq) {
5830
+ return
5831
+ }
5544
5832
  if (live.willingnessNudges >= MAX_WILLINGNESS_NUDGES) return
5545
5833
  if (live.promptQueue.length > 0) return
5546
5834
  if (record.text === undefined) return
@@ -5727,6 +6015,8 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5727
6015
  if (
5728
6016
  live.promptQueue.length === 0 &&
5729
6017
  live.currentTurnAuthorId !== null &&
6018
+ live.githubReviewThreadCloseout === null &&
6019
+ live.githubReviewThreadCloseoutDecisionTurn !== live.turnSeq &&
5730
6020
  live.continueReplyTurn?.turnSeq === live.turnSeq &&
5731
6021
  live.continueReplyTurn.sendCount === live.successfulChannelSends &&
5732
6022
  isFreshEmptyStopAfterSend(live) &&
@@ -5767,7 +6057,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
5767
6057
  // batch — so injecting a stale recovery nudge would prepend it to a live user
5768
6058
  // message. Skip the nudge AND the fallback in that case and let the trailing
5769
6059
  // recovery below run; the queued inbound supersedes this turn's silence.
5770
- 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
+ ) {
5771
6067
  if (live.willingnessNudges < MAX_WILLINGNESS_NUDGES) {
5772
6068
  live.willingnessNudges++
5773
6069
  logger.warn(
@@ -6283,6 +6579,29 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6283
6579
 
6284
6580
  const runIdleGc = async (): Promise<void> => {
6285
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
+ }
6286
6605
  const t = now()
6287
6606
  const victims: LiveSession[] = []
6288
6607
  for (const live of liveSessions.values()) {
@@ -6804,7 +7123,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6804
7123
  )
6805
7124
  const round = publisher?.githubReviewRound ?? persistedPublisher?.githubReviewRound
6806
7125
  if (round === null || round === undefined) {
6807
- const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber)
7126
+ const resetRound = resetGithubReviewRoundCompletionForPr(args.workspace, args.prNumber, now)
6808
7127
  if (resetRound !== null) persistMatchingGithubReviewRound(resetRound)
6809
7128
  logger.warn(
6810
7129
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: no publisher session with round state session=${args.sessionId}`,
@@ -6812,7 +7131,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6812
7131
  return { kind: 'no-round' }
6813
7132
  }
6814
7133
 
6815
- const activeRound = registerGithubReviewRound(round)
7134
+ const activeRound = registerGithubReviewRound(round, now(), now)
6816
7135
  if (activeRound === null) {
6817
7136
  logger.warn(
6818
7137
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: round expired`,
@@ -6821,22 +7140,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6821
7140
  }
6822
7141
  const publisherThread = publisher?.key.thread ?? persistedPublisher?.thread ?? null
6823
7142
  if (activeRound.carrierThread !== publisherThread) {
6824
- resetGithubReviewRoundCompletion(activeRound)
7143
+ resetGithubReviewRoundCompletion(activeRound, now)
6825
7144
  persistMatchingGithubReviewRound(activeRound)
6826
7145
  logger.warn(
6827
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'}`,
6828
7147
  )
6829
7148
  return { kind: 'no-round' }
6830
7149
  }
6831
- if (!(await validateGithubReviewRound(activeRound))) {
6832
- resetGithubReviewRoundCompletion(activeRound)
7150
+ if (!(await validateGithubReviewRound(activeRound, undefined, now))) {
7151
+ resetGithubReviewRoundCompletion(activeRound, now)
6833
7152
  persistMatchingGithubReviewRound(activeRound)
6834
7153
  logger.warn(
6835
7154
  `[channels] github review round completion rejected pr=${args.workspace}#${args.prNumber} verdict=${args.verdict}: head mismatch or unavailable expected=${activeRound.headSha}`,
6836
7155
  )
6837
7156
  return { kind: 'no-round' }
6838
7157
  }
6839
- completeGithubReviewRound(activeRound)
7158
+ completeGithubReviewRound(activeRound, now)
6840
7159
  const key = githubReviewRoundKey(round)
6841
7160
  for (const live of liveSessions.values()) {
6842
7161
  if (live.githubReviewRound === null || githubReviewRoundKey(live.githubReviewRound) !== key) continue
@@ -6858,7 +7177,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6858
7177
  const persistMatchingGithubReviewRound = (round: GithubReviewFollowupRound): void => {
6859
7178
  if (mappings === null) return
6860
7179
  const key = githubReviewRoundKey(round)
6861
- const state = githubReviewRoundPersistence(round)
7180
+ const state = githubReviewRoundPersistence(round, now)
6862
7181
  let changed = false
6863
7182
  for (const [idx, record] of mappings.entries()) {
6864
7183
  if (record.githubReviewRound === undefined) continue
@@ -6876,7 +7195,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6876
7195
  }
6877
7196
 
6878
7197
  // A close-out can land while completion is still awaiting head validation, so
6879
- // `finishGithubReviewRoundCloseout` sees a pending round and returns without
7198
+ // `finishGithubReviewThreadCloseout` sees a pending round and returns without
6880
7199
  // clearing. Nothing else retries it, which would strand round metadata on the
6881
7200
  // session and reject its later verdicts — so the close-out is recorded and
6882
7201
  // replayed here once the round actually completes.
@@ -6885,20 +7204,22 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6885
7204
  for (const live of liveSessions.values()) {
6886
7205
  if (live.pendingGithubReviewRoundCloseout !== key) continue
6887
7206
  live.pendingGithubReviewRoundCloseout = null
6888
- finishGithubReviewRoundCloseout({
7207
+ finishGithubReviewThreadCloseout({
6889
7208
  sessionId: live.sessionId,
6890
7209
  workspace: live.key.workspace,
6891
7210
  prNumber: Number(live.key.chat.slice('pr:'.length)),
6892
7211
  thread: live.key.thread ?? null,
7212
+ decision: 'resolved',
6893
7213
  })
6894
7214
  }
6895
7215
  }
6896
7216
 
6897
- const finishGithubReviewRoundCloseout = (args: {
7217
+ const finishGithubReviewThreadCloseout = (args: {
6898
7218
  sessionId: string
6899
7219
  workspace: string
6900
7220
  prNumber: number
6901
7221
  thread: string | null
7222
+ decision: 'resolved' | 'left-open'
6902
7223
  }): void => {
6903
7224
  const chat = `pr:${args.prNumber}`
6904
7225
  const live = Array.from(liveSessions.values()).find(
@@ -6910,9 +7231,16 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6910
7231
  candidate.key.chat === chat &&
6911
7232
  candidate.key.thread === args.thread,
6912
7233
  )
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
+ }
6913
7241
  if (live?.githubReviewRound === null || live?.githubReviewRound === undefined) return
6914
7242
  const round = live.githubReviewRound
6915
- if (!isGithubReviewRoundComplete(round)) {
7243
+ if (!isGithubReviewRoundComplete(round, now)) {
6916
7244
  live.pendingGithubReviewRoundCloseout = githubReviewRoundKey(round)
6917
7245
  return
6918
7246
  }
@@ -6986,6 +7314,14 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
6986
7314
  return { kind: 'no-live-session' }
6987
7315
  }
6988
7316
 
7317
+ const hasOutstandingGithubReviewThreadCloseout = (sessionId: string): boolean => {
7318
+ for (const live of liveSessions.values()) {
7319
+ if (live.destroyed || live.sessionId !== sessionId) continue
7320
+ return live.githubReviewThreadCloseout !== null
7321
+ }
7322
+ return false
7323
+ }
7324
+
6989
7325
  const clearSticky = (key: ChannelKey): { keyId: string; cleared: number } => {
6990
7326
  const keyId = channelKeyId(key)
6991
7327
  const cleared = stickyLedger.clear(keyId)
@@ -7224,9 +7560,11 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
7224
7560
  getSelfAliases: computeSelfAliases,
7225
7561
  injectSubagentCompletionReminder,
7226
7562
  injectPrVerdictActivity,
7563
+ abortGithubPrTurn,
7227
7564
  completeGithubReviewRound: completeRoundForVerifiedVerdict,
7228
- finishGithubReviewRoundCloseout,
7565
+ finishGithubReviewThreadCloseout,
7229
7566
  noteGithubReviewOutput,
7567
+ hasOutstandingGithubReviewThreadCloseout,
7230
7568
  markTurnSkipped,
7231
7569
  clearSticky,
7232
7570
  reserveRestartHandoff,