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
@@ -25,6 +25,7 @@ export type EffectiveApprovalResolver = (target: {
25
25
  // differs from the pre-submit head) is recorded as the uncertainty sentinel so a
26
26
  // push-during-review still blocks a same-verdict duplicate for the lag window.
27
27
  export type HeadShaResolver = (target: { workspace: string; prNumber: number }) => Promise<string | null>
28
+ type ReviewVerdictCoordinatorLogger = { warn: (message: string) => void }
28
29
 
29
30
  export type ApproveBlock = {
30
31
  block: true
@@ -67,6 +68,7 @@ export type ApproveIdempotencyGuard = ReviewVerdictGuard
67
68
 
68
69
  let processEffectiveResolver: EffectiveApprovalResolver = async () => ({ ok: false })
69
70
  let processHeadShaResolver: HeadShaResolver = async () => null
71
+ let processLogger: ReviewVerdictCoordinatorLogger = console
70
72
 
71
73
  // Installs the auth-bearing resolvers used by every auth-neutral review surface
72
74
  // in this process. The bash interceptor and post_github_review each create a
@@ -75,15 +77,18 @@ let processHeadShaResolver: HeadShaResolver = async () => null
75
77
  export function configureReviewVerdictCoordinator(deps: {
76
78
  resolveEffectiveApproval: EffectiveApprovalResolver
77
79
  resolveHeadSha: HeadShaResolver
80
+ logger?: ReviewVerdictCoordinatorLogger
78
81
  }): void {
79
82
  processEffectiveResolver = deps.resolveEffectiveApproval
80
83
  processHeadShaResolver = deps.resolveHeadSha
84
+ processLogger = deps.logger ?? console
81
85
  }
82
86
 
83
87
  export function createSharedReviewVerdictGuard(): ReviewVerdictGuard {
84
88
  return createApproveIdempotencyGuard({
85
89
  resolveEffectiveApproval: (target) => processEffectiveResolver(target),
86
90
  resolveHeadSha: (target) => processHeadShaResolver(target),
91
+ logger: processLogger,
87
92
  })
88
93
  }
89
94
 
@@ -106,6 +111,10 @@ const CONCURRENT_REASON =
106
111
  'Another session in this agent is already submitting a formal review verdict for this pull request. ' +
107
112
  'Only one verdict may land per PR — do not submit a second review; the in-flight one will post.'
108
113
 
114
+ const PENDING_PUBLICATION_REASON =
115
+ 'A previous review submission for this pull request is still settling after the PR was converted to draft. ' +
116
+ 'Do not submit another verdict until its publication outcome is known.'
117
+
109
118
  const ROUND_INELIGIBLE_REASON =
110
119
  'This review follow-up round assigned the formal verdict to another sibling thread session. ' +
111
120
  'Do not submit a formal verdict from this session; wait for the designated sibling verdict activity, then close out only this thread.'
@@ -155,7 +164,7 @@ export const REPLY_REVIEW_ROUND_TTL_MS = 30 * 60_000
155
164
  // and a new-push head all bypass it, so a genuine re-review is never stranded. 5min
156
165
  // stays well under the lease TTL and short enough that a deliberate human-driven
157
166
  // re-approval of the identical commit is the only thing it can delay.
158
- const RECENT_LANDED_TTL_MS = 5 * 60_000
167
+ export const RECENT_LANDED_TTL_MS = 5 * 60_000
159
168
  const COMPLETED_REPLY_REVIEW_ROUND_GRACE_MS = 5 * 60_000
160
169
 
161
170
  type Reservation = {
@@ -185,6 +194,9 @@ type LandedVerdict = { verdict: ReviewVerdict; headSha: string | null; landedAt:
185
194
  // three sessions each landed an APPROVE on the same PR within ten seconds.
186
195
  const inFlightByPr = new Map<string, Reservation>()
187
196
  const reservationByCall = new Map<string, Reservation>()
197
+ const abortedReservationByCall = new Map<string, Reservation>()
198
+ type PendingPublication = { callId: string; reservation: Reservation; fencedAt: number }
199
+ const pendingPublicationsByPr = new Map<string, Map<number, PendingPublication>>()
188
200
  const recentLandedByPr = new Map<string, LandedVerdict>()
189
201
  type ReviewRoundState = {
190
202
  round: GithubReviewFollowupRound
@@ -275,8 +287,9 @@ export function restoreGithubReviewRound(
275
287
  dismissalAttempted = false,
276
288
  requestChangesAttempted = false,
277
289
  createdAt = Date.now(),
290
+ now: () => number = Date.now,
278
291
  ): GithubReviewFollowupRound | null {
279
- const registered = registerGithubReviewRound(round, createdAt)
292
+ const registered = registerGithubReviewRound(round, createdAt, now)
280
293
  if (registered === null) return null
281
294
  const key = githubReviewRoundKey(registered)
282
295
  // Restoration is monotonic: a persisted `pending` record must never overwrite
@@ -285,7 +298,7 @@ export function restoreGithubReviewRound(
285
298
  // it regress would re-arm failover and permit a second blocking review.
286
299
  // Expiry still wins — `activeReviewRoundState` drops the state first, so an
287
300
  // expired round is never resurrected by a late restore.
288
- const existing = activeReviewRoundState(key)
301
+ const existing = activeReviewRoundState(key, now)
289
302
  if (existing !== undefined && existing.status === 'completed' && status === 'pending') return registered
290
303
  reviewRounds.set(key, {
291
304
  round: registered,
@@ -298,14 +311,17 @@ export function restoreGithubReviewRound(
298
311
  return registered
299
312
  }
300
313
 
301
- export function githubReviewRoundPersistence(round: GithubReviewFollowupRound): {
314
+ export function githubReviewRoundPersistence(
315
+ round: GithubReviewFollowupRound,
316
+ now: () => number = Date.now,
317
+ ): {
302
318
  status: ReviewRoundState['status']
303
319
  createdAt: number
304
320
  attemptedCarriers: (string | null)[]
305
321
  dismissalAttempted?: true
306
322
  requestChangesAttempted?: true
307
323
  } | null {
308
- const state = activeReviewRoundState(githubReviewRoundKey(round))
324
+ const state = activeReviewRoundState(githubReviewRoundKey(round), now)
309
325
  if (state === undefined) return null
310
326
  return {
311
327
  status: state.status,
@@ -320,13 +336,13 @@ export function forgetGithubReviewRound(round: GithubReviewFollowupRound): void
320
336
  reviewRounds.delete(githubReviewRoundKey(round))
321
337
  }
322
338
 
323
- export function completeGithubReviewRound(round: GithubReviewFollowupRound): void {
339
+ export function completeGithubReviewRound(round: GithubReviewFollowupRound, now: () => number = Date.now): void {
324
340
  const key = githubReviewRoundKey(round)
325
- let current = activeReviewRoundState(key)
341
+ let current = activeReviewRoundState(key, now)
326
342
  if (current === undefined) {
327
- const registered = registerGithubReviewRound(round)
343
+ const registered = registerGithubReviewRound(round, now(), now)
328
344
  if (registered === null) return
329
- current = activeReviewRoundState(key)
345
+ current = activeReviewRoundState(key, now)
330
346
  if (current === undefined) return
331
347
  }
332
348
  reviewRounds.set(key, {
@@ -339,16 +355,24 @@ export function completeGithubReviewRound(round: GithubReviewFollowupRound): voi
339
355
  })
340
356
  }
341
357
 
342
- export function isGithubReviewRoundComplete(round: GithubReviewFollowupRound): boolean {
343
- return activeReviewRoundState(githubReviewRoundKey(round))?.status === 'completed'
358
+ export function isGithubReviewRoundComplete(round: GithubReviewFollowupRound, now: () => number = Date.now): boolean {
359
+ return activeReviewRoundState(githubReviewRoundKey(round), now)?.status === 'completed'
360
+ }
361
+
362
+ // This deliberately asks activeReviewRoundState instead of negating completion:
363
+ // lazy TTL expiry removes abandoned rounds, so an expired round is NOT pending and
364
+ // the close-out guard resumes before silence can strand its review thread forever.
365
+ export function isGithubReviewRoundPending(round: GithubReviewFollowupRound, now: () => number = Date.now): boolean {
366
+ return activeReviewRoundState(githubReviewRoundKey(round), now)?.status === 'pending'
344
367
  }
345
368
 
346
369
  export function promoteGithubReviewRound(
347
370
  round: GithubReviewFollowupRound,
348
371
  carrierThread: string | null,
372
+ now: () => number = Date.now,
349
373
  ): GithubReviewFollowupRound | null {
350
374
  const key = githubReviewRoundKey(round)
351
- const current = activeReviewRoundState(key)
375
+ const current = activeReviewRoundState(key, now)
352
376
  if (current === undefined || current.status === 'completed') return null
353
377
  const active = current.round
354
378
  if (active.carrierThread !== round.carrierThread) return null
@@ -367,16 +391,21 @@ export function promoteGithubReviewRound(
367
391
  return promoted
368
392
  }
369
393
 
370
- export function canPromoteGithubReviewRoundTo(round: GithubReviewFollowupRound, thread: string | null): boolean {
371
- const current = activeReviewRoundState(githubReviewRoundKey(round))
394
+ export function canPromoteGithubReviewRoundTo(
395
+ round: GithubReviewFollowupRound,
396
+ thread: string | null,
397
+ now: () => number = Date.now,
398
+ ): boolean {
399
+ const current = activeReviewRoundState(githubReviewRoundKey(round), now)
372
400
  return current !== undefined && current.status !== 'completed' && !current.attemptedCarriers.has(thread)
373
401
  }
374
402
 
375
403
  export async function validateGithubReviewRound(
376
404
  round: GithubReviewFollowupRound,
377
405
  createdAt?: number,
406
+ now: () => number = Date.now,
378
407
  ): Promise<boolean> {
379
- if (createdAt !== undefined && Date.now() - createdAt >= reviewRoundTtlMs(round)) return false
408
+ if (createdAt !== undefined && now() - createdAt >= reviewRoundTtlMs(round)) return false
380
409
  if (expiredReviewRoundKeys.has(githubReviewRoundKey(round))) return false
381
410
  const currentHead = await processHeadShaResolver({ workspace: round.workspace, prNumber: round.prNumber })
382
411
  return currentHead !== null && currentHead === round.headSha
@@ -431,12 +460,15 @@ export function releaseGithubReviewRoundDismissal(callId: string, attempted = tr
431
460
  releaseReservation(callId, reservation)
432
461
  }
433
462
 
434
- export function hasGithubReviewRoundDismissalAttempt(round: GithubReviewFollowupRound): boolean {
435
- return activeReviewRoundState(githubReviewRoundKey(round))?.dismissalAttempted === true
463
+ export function hasGithubReviewRoundDismissalAttempt(
464
+ round: GithubReviewFollowupRound,
465
+ now: () => number = Date.now,
466
+ ): boolean {
467
+ return activeReviewRoundState(githubReviewRoundKey(round), now)?.dismissalAttempted === true
436
468
  }
437
469
 
438
- export function resetGithubReviewRoundCompletion(round: GithubReviewFollowupRound): void {
439
- const state = activeReviewRoundState(githubReviewRoundKey(round))
470
+ export function resetGithubReviewRoundCompletion(round: GithubReviewFollowupRound, now: () => number = Date.now): void {
471
+ const state = activeReviewRoundState(githubReviewRoundKey(round), now)
440
472
  if (state === undefined || state.status === 'completed') return
441
473
  // A verified mutation may outlive its publishing session or hit a transient
442
474
  // head read before the observer can record completion. Release operation
@@ -449,8 +481,9 @@ export function resetGithubReviewRoundCompletion(round: GithubReviewFollowupRoun
449
481
  export function resetGithubReviewRoundCompletionForPr(
450
482
  workspace: string,
451
483
  prNumber: number,
484
+ now: () => number = Date.now,
452
485
  ): GithubReviewFollowupRound | null {
453
- expireReviewRounds()
486
+ expireReviewRounds(now)
454
487
  const state = Array.from(reviewRounds.values()).find(
455
488
  (candidate) =>
456
489
  candidate.status === 'pending' &&
@@ -458,12 +491,57 @@ export function resetGithubReviewRoundCompletionForPr(
458
491
  candidate.round.prNumber === prNumber,
459
492
  )
460
493
  if (state === undefined) return null
461
- resetGithubReviewRoundCompletion(state.round)
494
+ resetGithubReviewRoundCompletion(state.round, now)
462
495
  return state.round
463
496
  }
464
497
 
498
+ export function abortGithubReviewStateForPr(
499
+ workspace: string,
500
+ prNumber: number,
501
+ now: () => number = Date.now,
502
+ ): { releasedReservations: number; deletedRounds: number } {
503
+ const key = prKey(workspace, prNumber)
504
+ const reservations = new Set<Reservation>()
505
+ const matchingCalls: Array<[string, Reservation]> = []
506
+ const held = inFlightByPr.get(key)
507
+ if (held !== undefined) reservations.add(held)
508
+ for (const entry of reservationByCall) {
509
+ const [callId, reservation] = entry
510
+ if (reservation.workspace !== workspace || reservation.prNumber !== prNumber) continue
511
+ reservations.add(reservation)
512
+ matchingCalls.push([callId, reservation])
513
+ }
514
+ for (const reservation of reservations) resetRoundAttempt(reservation)
515
+ for (const [callId, reservation] of matchingCalls) {
516
+ reservationByCall.delete(callId)
517
+ // Release active ownership now, but retain a decisive call's accounting
518
+ // record because a POST already past dispatch may still verify afterward.
519
+ if (reservation.verdict !== 'DISMISSED') {
520
+ abortedReservationByCall.set(callId, reservation)
521
+ addPendingPublication(callId, reservation, now())
522
+ }
523
+ }
524
+ inFlightByPr.delete(key)
525
+
526
+ let deletedRounds = 0
527
+ for (const [roundKey, state] of reviewRounds) {
528
+ if (state.status !== 'pending') continue
529
+ if (state.round.workspace !== workspace || state.round.prNumber !== prNumber) continue
530
+ reviewRounds.delete(roundKey)
531
+ deletedRounds++
532
+ }
533
+ for (const [generationKey, generation] of replyReviewRoundGenerations) {
534
+ if (generation.round.workspace !== workspace || generation.round.prNumber !== prNumber) continue
535
+ replyReviewRoundGenerations.delete(generationKey)
536
+ }
537
+
538
+ // A draft abort abandons local work, not output already observed on GitHub.
539
+ // Keeping recentLandedByPr prevents a later ready event from duplicating it.
540
+ return { releasedReservations: reservations.size, deletedRounds }
541
+ }
542
+
465
543
  // Makes a formal `gh ... event=APPROVE|REQUEST_CHANGES` idempotent per PR across
466
- // turns, sessions, and (in-process) concurrent fan-out. Three layers, in order:
544
+ // turns, sessions, and (in-process) concurrent fan-out. Four layers, in order:
467
545
  //
468
546
  // 1. A process-wide in-flight lease keyed by `workspace#prNumber`, held from
469
547
  // tool.before through tool.after. While one verdict is mid-flight, every
@@ -472,14 +550,19 @@ export function resetGithubReviewRoundCompletionForPr(
472
550
  // closure-local Set could not provide: separate plugin instances meant
473
551
  // separate Sets, so concurrent sessions never saw each other.
474
552
  //
475
- // 2. The authoritative GitHub effective-state read, consulted AFTER the lease.
553
+ // 2. A pending-publication fence retained when a draft abort releases the live
554
+ // lease. It blocks only a same-head publication while the already-dispatched
555
+ // call settles; round state remains deleted and independently registrable.
556
+ // The fence expires after RECENT_LANDED_TTL_MS and logs before failing open.
557
+ //
558
+ // 3. The authoritative GitHub effective-state read, consulted AFTER the lease.
476
559
  // It is the SOLE source of truth for a standing verdict and for supersession:
477
560
  // a later CHANGES_REQUESTED/DISMISSED demotes an earlier APPROVED, so a
478
561
  // genuine re-verdict is allowed (the 35287f99 invariant — never block a
479
562
  // re-verdict on stale LOCAL memory). A standing same verdict blocks; DISMISSED
480
563
  // and the opposite decisive verdict pass. Reads fail OPEN.
481
564
  //
482
- // 3. A read-after-write-lag shield, consulted ONLY when layer 2 returns a raw
565
+ // 4. A read-after-write-lag shield, consulted ONLY when layer 3 returns a raw
483
566
  // NONE. The lease (layer 1) covers two OVERLAPPING in-flight commands, but a
484
567
  // second engagement turn ~10s later starts after the first's lease released,
485
568
  // and GitHub's reviews list still lags the write (reports NONE). A short-lived
@@ -493,21 +576,24 @@ export function resetGithubReviewRoundCompletionForPr(
493
576
  // NONE, a real DISMISSED/CHANGES_REQUESTED already allowed the re-verdict at
494
577
  // layer 2, so this cannot re-strand a supersession.
495
578
  //
496
- // The lease is released only in release() (tool.after) or on a terminal block,
497
- // never after the remote read — releasing early reopens the TOCTOU the lease
498
- // exists to close. Release is keyed by a per-call token so a late/stale
499
- // tool.after for a superseded reservation cannot drop a newer session's lease.
579
+ // Outside a draft abort, the lease is released only in release() (tool.after) or
580
+ // on a terminal block, never after the remote read. A draft abort replaces it with
581
+ // the bounded pending-publication fence above. Cleanup is keyed by a per-call
582
+ // token so a late/stale tool.after cannot drop a newer session's state.
500
583
  export function createApproveIdempotencyGuard(deps: {
501
584
  resolveEffectiveApproval: EffectiveApprovalResolver
502
585
  resolveHeadSha?: HeadShaResolver
503
586
  now?: () => number
587
+ logger?: ReviewVerdictCoordinatorLogger
504
588
  }): ReviewVerdictGuard {
505
589
  const now = deps.now ?? Date.now
590
+ const logger = deps.logger ?? processLogger
506
591
 
507
592
  return {
508
593
  async guard(args): Promise<ApproveBlock | null> {
509
594
  if (args.verdict !== 'APPROVE' && args.verdict !== 'REQUEST_CHANGES') return null
510
595
  expireRecentLanded(now)
596
+ expirePendingPublications(now, logger)
511
597
  const blocked = await evaluateRoundEligibility(args, deps.resolveHeadSha ?? processHeadShaResolver, now)
512
598
  if (blocked !== null) return blocked
513
599
  const key = prKey(args.workspace, args.prNumber)
@@ -545,6 +631,12 @@ export function createApproveIdempotencyGuard(deps: {
545
631
  const headSha = (await deps.resolveHeadSha?.({ workspace: args.workspace, prNumber: args.prNumber })) ?? null
546
632
  reservation.headSha = headSha
547
633
 
634
+ if (hasPendingPublicationOnHead(key, headSha, now, logger)) {
635
+ resetRoundRequestChangesAttempt(reservation)
636
+ releaseReservation(args.callId, reservation)
637
+ return { block: true, kind: 'concurrent', reason: PENDING_PUBLICATION_REASON }
638
+ }
639
+
548
640
  // Layer 2: GitHub is the authoritative, sole source of truth for a standing
549
641
  // verdict. A standing same verdict is a real duplicate except for the one
550
642
  // carrier REQUEST_CHANGES required to complete a new-head follow-up round;
@@ -612,7 +704,7 @@ export function createApproveIdempotencyGuard(deps: {
612
704
  },
613
705
 
614
706
  async release(args): Promise<void> {
615
- const reservation = reservationByCall.get(args.callId)
707
+ const reservation = reservationByCall.get(args.callId) ?? abortedReservationByCall.get(args.callId)
616
708
  if (reservation === undefined) return
617
709
  try {
618
710
  // A FORMAL review's pre-submit head can go stale: if the PR head advanced
@@ -735,18 +827,73 @@ function recentlyLandedSame(key: string, verdict: ReviewVerdict, headSha: string
735
827
  // newer session) must not yank the live session's lease.
736
828
  function releaseReservation(callId: string, reservation: Reservation): void {
737
829
  reservationByCall.delete(callId)
830
+ abortedReservationByCall.delete(callId)
831
+ removePendingPublication(reservation)
738
832
  const current = inFlightByPr.get(reservation.key)
739
833
  if (current !== undefined && current.token === reservation.token) {
740
834
  inFlightByPr.delete(reservation.key)
741
835
  }
742
836
  }
743
837
 
838
+ function addPendingPublication(callId: string, reservation: Reservation, fencedAt: number): void {
839
+ const pending = pendingPublicationsByPr.get(reservation.key) ?? new Map<number, PendingPublication>()
840
+ pending.set(reservation.token, { callId, reservation, fencedAt })
841
+ pendingPublicationsByPr.set(reservation.key, pending)
842
+ }
843
+
844
+ function hasPendingPublicationOnHead(
845
+ key: string,
846
+ headSha: string | null,
847
+ now: () => number,
848
+ logger: ReviewVerdictCoordinatorLogger,
849
+ ): boolean {
850
+ expirePendingPublications(now, logger)
851
+ const pending = pendingPublicationsByPr.get(key)
852
+ if (pending === undefined) return false
853
+ for (const publication of pending.values()) {
854
+ if (headSha === null || publication.reservation.headSha === null || publication.reservation.headSha === headSha) {
855
+ return true
856
+ }
857
+ }
858
+ return false
859
+ }
860
+
861
+ function removePendingPublication(reservation: Reservation): void {
862
+ const pending = pendingPublicationsByPr.get(reservation.key)
863
+ if (pending === undefined) return
864
+ pending.delete(reservation.token)
865
+ if (pending.size === 0) pendingPublicationsByPr.delete(reservation.key)
866
+ }
867
+
868
+ function expirePendingPublications(now: () => number, logger: ReviewVerdictCoordinatorLogger): void {
869
+ const currentTime = now()
870
+ for (const [key, pending] of pendingPublicationsByPr) {
871
+ for (const [token, publication] of pending) {
872
+ if (currentTime - publication.fencedAt < RECENT_LANDED_TTL_MS) continue
873
+ pending.delete(token)
874
+ abortedReservationByCall.delete(publication.callId)
875
+ logger.warn(
876
+ `[github] pending review publication fence lapsed without release pr=${publication.reservation.workspace}#${publication.reservation.prNumber}`,
877
+ )
878
+ }
879
+ if (pending.size === 0) pendingPublicationsByPr.delete(key)
880
+ }
881
+ }
882
+
744
883
  function resetRoundRequestChangesAttempt(reservation: Reservation): void {
745
884
  if (reservation.verdict !== 'REQUEST_CHANGES' || reservation.roundKey === undefined) return
746
885
  const state = activeReviewRoundState(reservation.roundKey)
747
886
  if (state !== undefined && state.status === 'pending') state.requestChangesAttempted = false
748
887
  }
749
888
 
889
+ function resetRoundAttempt(reservation: Reservation): void {
890
+ if (reservation.roundKey === undefined) return
891
+ const state = activeReviewRoundState(reservation.roundKey)
892
+ if (state === undefined || state.status !== 'pending') return
893
+ if (reservation.verdict === 'DISMISSED') state.dismissalAttempted = false
894
+ if (reservation.verdict === 'REQUEST_CHANGES') state.requestChangesAttempted = false
895
+ }
896
+
750
897
  function prKey(workspace: string, prNumber: number): string {
751
898
  return `${workspace}#${prNumber}`
752
899
  }
@@ -786,6 +933,8 @@ export function __recentLandedRecordCountForTest(): number {
786
933
  export function __resetReviewVerdictGuardForTest(): void {
787
934
  inFlightByPr.clear()
788
935
  reservationByCall.clear()
936
+ abortedReservationByCall.clear()
937
+ pendingPublicationsByPr.clear()
789
938
  recentLandedByPr.clear()
790
939
  reviewRounds = new Map<string, ReviewRoundState>()
791
940
  expiredReviewRoundKeys = new Set<string>()
@@ -793,4 +942,5 @@ export function __resetReviewVerdictGuardForTest(): void {
793
942
  tokenSeq = 0
794
943
  processEffectiveResolver = async () => ({ ok: false })
795
944
  processHeadShaResolver = async () => null
945
+ processLogger = console
796
946
  }
@@ -52,20 +52,24 @@ export function renderPrVerdictStandDownReminder(args: { prNumber: number; verdi
52
52
  if (args.verdict === 'DISMISSED') {
53
53
  return (
54
54
  `<system-reminder>\n` +
55
- `The designated carrier verified that its blocking review for PR #${args.prNumber} is DISMISSED. ` +
56
- `Do not submit another formal verdict for this follow-up round. Close out this session's addressed ` +
57
- `review thread as normal; leave it open if its concern remains unresolved.\n` +
55
+ `The blocking review for PR #${args.prNumber} is verified as DISMISSED. Do not submit another formal verdict ` +
56
+ `unless fresh evidence warrants one. This does not discharge the inline review-thread obligation: send exactly ` +
57
+ `one participant-facing close-out, resolving with a short substantive acknowledgement if addressed or leaving ` +
58
+ `it open with the specific technical reason it remains. Do not describe review rounds, carriers, sessions, ` +
59
+ `verdict registration, or sticky review state.\n` +
58
60
  `</system-reminder>`
59
61
  )
60
62
  }
61
63
  return (
62
64
  `<system-reminder>\n` +
63
- `Another session in this agent has already posted a formal ${args.verdict} review for PR #${args.prNumber}. ` +
65
+ `A formal ${args.verdict} review has already landed for PR #${args.prNumber}. ` +
64
66
  `This notice applies ONLY to formal PR-level verdicts. Do not submit your own ${args.verdict} (or any redundant ` +
65
67
  `verdict) for this PR this turn unless new ` +
66
68
  `information genuinely invalidates that result (e.g. new commits, or a different verdict warranted by ` +
67
- `fresh evidence). It does NOT discharge this session's inline review-thread close-out: you must still reply to ` +
68
- `the inline thread as normal, resolving it if addressed or leaving it open with an explanation.\n` +
69
+ `fresh evidence). It does NOT discharge the inline review-thread obligation: send exactly one participant-facing ` +
70
+ `close-out, resolving with a short substantive acknowledgement if addressed or leaving it open with the specific ` +
71
+ `technical reason it remains. Do not describe review rounds, carriers, sessions, verdict registration, or sticky ` +
72
+ `review state.\n` +
69
73
  `</system-reminder>`
70
74
  )
71
75
  }
@@ -139,6 +139,12 @@ export type ChannelManagerOptions = {
139
139
  // background subagents a session was still awaiting. Same wiring shape as
140
140
  // newestRunningChildSubagentStartedAt; tests omit it.
141
141
  listRunningBackgroundSubagentNames?: (sessionId: string) => string[]
142
+ // Forwarded to the router so an adapter-triggered work invalidation can stop
143
+ // independent background sessions that a parent AgentSession abort cannot reach.
144
+ cancelRunningSubagentsByWorkKey?: (
145
+ workKey: string,
146
+ reason: string,
147
+ ) => Promise<{ matched: number; cancelled: number; failures: number }>
142
148
  // Persistent messenger SDKs usually reconnect themselves, but a host sleep/offline
143
149
  // cycle can leave a socket half-dead forever. The manager watches live adapters
144
150
  // and restarts one that stays disconnected past this grace period. Test seams are
@@ -258,6 +264,9 @@ export function createChannelManager(options: ChannelManagerOptions): ChannelMan
258
264
  ...(options.listRunningBackgroundSubagentNames
259
265
  ? { listRunningBackgroundSubagentNames: options.listRunningBackgroundSubagentNames }
260
266
  : {}),
267
+ ...(options.cancelRunningSubagentsByWorkKey
268
+ ? { cancelRunningSubagentsByWorkKey: options.cancelRunningSubagentsByWorkKey }
269
+ : {}),
261
270
  })
262
271
  const createDiscordBot = options.createDiscordAdapter ?? createDiscordBotAdapter
263
272
  const createDiscordUser = options.createDiscordUserAdapter ?? createDiscordAdapter
@@ -6,7 +6,7 @@ import type { ChannelParticipant } from '@/agent/session-origin'
6
6
  import { toRef } from './adapters/webex-id-ref'
7
7
  import { describeError } from './describe-error'
8
8
  import type { AdapterId } from './schema'
9
- import type { ChannelKey, GithubReviewFollowupRound } from './types'
9
+ import type { ChannelKey, GithubReviewFollowupRound, GithubReviewThreadCloseout } from './types'
10
10
 
11
11
  const FILE_VERSION = 7
12
12
 
@@ -36,6 +36,7 @@ export type ChannelSessionRecord = {
36
36
  dismissalAttempted?: true
37
37
  requestChangesAttempted?: true
38
38
  }
39
+ githubReviewThreadCloseout?: GithubReviewThreadCloseout & { deferred: true }
39
40
  }
40
41
 
41
42
  type FileV4 = {
@@ -246,7 +247,32 @@ function isValidRecord(v: unknown): v is ChannelSessionRecord {
246
247
  (r.sessionFile === undefined || typeof r.sessionFile === 'string') &&
247
248
  (r.lastInboundAt === undefined || typeof r.lastInboundAt === 'number') &&
248
249
  Array.isArray(r.participants) &&
249
- (r.githubReviewRound === undefined || isValidGithubReviewRound(r.githubReviewRound, r))
250
+ (r.githubReviewRound === undefined || isValidGithubReviewRound(r.githubReviewRound, r)) &&
251
+ (r.githubReviewThreadCloseout === undefined || isValidGithubReviewThreadCloseout(r.githubReviewThreadCloseout, r))
252
+ )
253
+ }
254
+
255
+ function isValidGithubReviewThreadCloseout(value: unknown, record: Record<string, unknown>): boolean {
256
+ if (!isObject(value)) return false
257
+ const deferUntil = value.deferUntil
258
+ return (
259
+ record.adapter === 'github' &&
260
+ typeof value.workspace === 'string' &&
261
+ value.workspace === record.workspace &&
262
+ typeof value.prNumber === 'number' &&
263
+ Number.isInteger(value.prNumber) &&
264
+ value.prNumber > 0 &&
265
+ record.chat === `pr:${value.prNumber}` &&
266
+ typeof value.rootCommentId === 'string' &&
267
+ value.rootCommentId.length > 0 &&
268
+ value.rootCommentId === record.thread &&
269
+ (deferUntil === undefined ||
270
+ (isObject(deferUntil) &&
271
+ deferUntil.kind === 'review-state-unknown' &&
272
+ typeof deferUntil.expiresAt === 'number' &&
273
+ Number.isFinite(deferUntil.expiresAt) &&
274
+ deferUntil.expiresAt >= 0)) &&
275
+ value.deferred === true
250
276
  )
251
277
  }
252
278