typeclaw 0.48.5 → 0.48.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.5",
3
+ "version": "0.48.7",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -38,6 +38,20 @@ export type LiveSubagent = {
38
38
  export const MAX_EVENTS_PER_SUBAGENT = 100
39
39
  export const MESSAGE_PREVIEW_CHARS = 200
40
40
 
41
+ // Newest — not oldest — so a long-running child that crossed a caller's backstop
42
+ // cannot unpin a parent while a more recently spawned sibling is still inside its
43
+ // window. Foreground children are excluded on purpose: they return inline, so a
44
+ // parent is never left waiting on one.
45
+ export function newestRunningBackgroundChildStartedAt(children: readonly LiveSubagent[]): number | null {
46
+ return children.reduce<number | null>(
47
+ (newest, child) =>
48
+ child.status === 'running' && child.background === true && (newest === null || child.startedAt > newest)
49
+ ? child.startedAt
50
+ : newest,
51
+ null,
52
+ )
53
+ }
54
+
41
55
  type AgentSessionEvent =
42
56
  | { type: 'message_update'; assistantMessageEvent: { type: string; delta?: string } }
43
57
  | { type: 'message_end'; message: unknown }
@@ -1038,7 +1038,7 @@ function spreadSandboxEnv(policy: ReturnType<typeof buildSandboxEnvPolicy>): {
1038
1038
 
1039
1039
  function resolveExposableBashEnvNames(agentDir: string): { exposable: string[]; withheld: string[] } {
1040
1040
  const declaredEnv = readEnvFile(agentDir)
1041
- const exposable = resolveExposableEnvNames(declaredEnv)
1041
+ const exposable = resolveExposableEnvNames(declaredEnv, process.env)
1042
1042
  const exposableSet = new Set(exposable)
1043
1043
  const withheld = [...declaredEnv]
1044
1044
  .filter(([name, value]) => value.length > 0 && !exposableSet.has(name))
@@ -14,6 +14,9 @@ type PostGithubReviewDetails = {
14
14
  ok: boolean
15
15
  error?: string
16
16
  code?: string
17
+ fallback?: 'comment'
18
+ messageId?: string
19
+ messageIds?: readonly string[]
17
20
  reviewId?: number
18
21
  state?: string
19
22
  downgraded?: boolean
@@ -63,8 +66,32 @@ export function createPostGithubReviewTool(options: {
63
66
  workspace: origin.workspace,
64
67
  prNumber,
65
68
  verdict,
69
+ retainDuplicateLease: params.event === 'REQUEST_CHANGES',
66
70
  })
67
- if (blocked !== null) return denied(logger, blocked.reason)
71
+ if (blocked !== null) {
72
+ if (
73
+ params.event === 'REQUEST_CHANGES' &&
74
+ blocked.kind === 'duplicate' &&
75
+ blocked.duplicateSource === 'standing'
76
+ ) {
77
+ try {
78
+ return await postDuplicateRequestChangesComment({
79
+ router,
80
+ origin,
81
+ sessionId,
82
+ prNumber,
83
+ body: params.body,
84
+ comments: (params.comments ?? []).map(toReviewFinding),
85
+ logger,
86
+ })
87
+ } finally {
88
+ if (blocked.leaseRetained === true) {
89
+ await verdictGuard.release({ callId: coordinationCallId, succeeded: false })
90
+ }
91
+ }
92
+ }
93
+ return denied(logger, blocked.reason)
94
+ }
68
95
  }
69
96
  const request: SubmitReviewRequest = {
70
97
  adapter: 'github',
@@ -113,6 +140,79 @@ export function createPostGithubReviewTool(options: {
113
140
  })
114
141
  }
115
142
 
143
+ async function postDuplicateRequestChangesComment(args: {
144
+ router: ChannelRouter
145
+ origin: ChannelReplyOrigin
146
+ sessionId: string
147
+ prNumber: number
148
+ body: string
149
+ comments: readonly ReviewFinding[]
150
+ logger: ChannelToolLogger
151
+ }) {
152
+ const result = await args.router.send(
153
+ {
154
+ adapter: 'github',
155
+ workspace: args.origin.workspace,
156
+ chat: args.origin.chat,
157
+ thread: null,
158
+ text: renderFallbackComment(args.body, args.comments),
159
+ },
160
+ { accountingTarget: args.origin },
161
+ )
162
+ if (!result.ok) return denied(args.logger, result.error, result.code)
163
+
164
+ recordReviewOutput({
165
+ sessionId: args.sessionId,
166
+ workspace: args.origin.workspace,
167
+ prNumber: args.prNumber,
168
+ state: 'COMMENT',
169
+ })
170
+
171
+ const details: PostGithubReviewDetails = {
172
+ ok: true,
173
+ fallback: 'comment',
174
+ ...(result.messageId !== undefined ? { messageId: result.messageId } : {}),
175
+ ...(result.messageIds !== undefined ? { messageIds: result.messageIds } : {}),
176
+ }
177
+ return {
178
+ content: [
179
+ {
180
+ type: 'text' as const,
181
+ text: fenceToolResult(
182
+ 'GitHub PR comment posted because the existing CHANGES_REQUESTED review is still active.',
183
+ ),
184
+ },
185
+ ],
186
+ details,
187
+ }
188
+ }
189
+
190
+ function renderFallbackComment(body: string, comments: readonly ReviewFinding[]): string {
191
+ if (comments.length === 0) return body
192
+ return [
193
+ body,
194
+ '',
195
+ '---',
196
+ '',
197
+ ...comments.flatMap((comment) => [`**${markdownCodeSpan(renderLocation(comment))}**`, '', comment.body, '']),
198
+ ]
199
+ .slice(0, -1)
200
+ .join('\n')
201
+ }
202
+
203
+ function renderLocation(comment: ReviewFinding): string {
204
+ const lines = comment.startLine !== undefined ? `${comment.startLine}-${comment.line}` : String(comment.line)
205
+ const side = comment.side === 'LEFT' ? ' (old revision)' : ''
206
+ return `${comment.path.replace(/[\r\n]+/g, ' ')}:${lines}${side}`
207
+ }
208
+
209
+ function markdownCodeSpan(value: string): string {
210
+ const longestRun = Math.max(0, ...Array.from(value.matchAll(/`+/g), (match) => match[0].length))
211
+ const delimiter = '`'.repeat(longestRun + 1)
212
+ const padded = value.startsWith('`') || value.endsWith('`') ? ` ${value} ` : value
213
+ return `${delimiter}${padded}${delimiter}`
214
+ }
215
+
116
216
  function parsePrNumber(chat: string): number | null {
117
217
  const match = /^pr:(\d+)$/.exec(chat)
118
218
  if (match?.[1] === undefined) return null
@@ -1,6 +1,8 @@
1
1
  // Plain-`git` analog of analyzeGhCommand. Git names its target indirectly, so
2
2
  // this analyzer resolves configured remotes before selecting a per-repo token.
3
3
 
4
+ import { mapVirtualTmpPath } from '@/sandbox'
5
+
4
6
  export type GitCommandDecision =
5
7
  | { kind: 'pass-through' }
6
8
  | { kind: 'block'; reason: string }
@@ -41,6 +43,27 @@ export const defaultGitResolvers: GitResolvers = {
41
43
  resolveCurrentBranch: (cwd) => runGit(cwd, ['symbolic-ref', '--short', 'HEAD']),
42
44
  }
43
45
 
46
+ // Sandboxed bash sees the per-session scratch dir bound over `/tmp`
47
+ // (applyBashSandbox), but these resolvers spawn `git` from the runtime process
48
+ // against the REAL container `/tmp` — so a repo the model cloned to `/tmp/foo`
49
+ // resolves to nothing here and the command falls through UNBROKERED, leaving git
50
+ // to die on a credential prompt it can never answer. Same class of bug the file
51
+ // tools solve with TMP_REDIRECT_TOOLS. Only the filesystem probe is redirected:
52
+ // the analyzer must keep reasoning in model-facing paths so `rewrittenCommand`
53
+ // stays valid inside the sandbox.
54
+ export function createSessionTmpGitResolvers(
55
+ agentDir: string,
56
+ sessionId: string,
57
+ base: GitResolvers = defaultGitResolvers,
58
+ ): GitResolvers {
59
+ const backing = (cwd: string): string => mapVirtualTmpPath(agentDir, sessionId, cwd) ?? cwd
60
+ return {
61
+ resolveRemoteUrl: (cwd, remote, forPush) => base.resolveRemoteUrl(backing(cwd), remote, forPush),
62
+ resolveConfig: (cwd, key) => base.resolveConfig(backing(cwd), key),
63
+ resolveCurrentBranch: (cwd) => base.resolveCurrentBranch(backing(cwd)),
64
+ }
65
+ }
66
+
44
67
  const MULTI_OWNER_REASON =
45
68
  'This git command targets more than one repository; a single minted GitHub App ' +
46
69
  'token is scoped to one repo and cannot authenticate all of them. Split it into ' +
@@ -16,7 +16,12 @@ import {
16
16
  usesGhApiGraphqlEndpoint,
17
17
  } from './gh-command'
18
18
  import { ensureGitAskPassHelper, resolveSandboxGitAskPassPath } from './git-askpass'
19
- import { analyzeGitCommand, defaultGitResolvers, resolveGhDefaultRepoFromCwd } from './git-command'
19
+ import {
20
+ analyzeGitCommand,
21
+ createSessionTmpGitResolvers,
22
+ defaultGitResolvers,
23
+ resolveGhDefaultRepoFromCwd,
24
+ } from './git-command'
20
25
  import { checkGraphqlAuthNudge } from './graphql-auth-nudge'
21
26
  import { commitReviewIfSucceeded, noteReviewCommand } from './review-recorder'
22
27
  import { classifyGhToken, shouldMintAppToken } from './token-class'
@@ -351,9 +356,13 @@ export default definePlugin({
351
356
  event: { args: Record<string, unknown> }
352
357
  command: string
353
358
  agentDir: string
359
+ sessionId: string
354
360
  }): Promise<HookResult> => {
355
- const { event, command, agentDir } = params
356
- const decision = await analyzeGitCommand(command, { cwd: agentDir, resolvers: defaultGitResolvers })
361
+ const { event, command, agentDir, sessionId } = params
362
+ const decision = await analyzeGitCommand(command, {
363
+ cwd: agentDir,
364
+ resolvers: createSessionTmpGitResolvers(agentDir, sessionId),
365
+ })
357
366
  if (decision.kind === 'pass-through') return
358
367
  if (decision.kind === 'block') return { block: true, reason: decision.reason }
359
368
 
@@ -410,7 +419,7 @@ export default definePlugin({
410
419
  }
411
420
 
412
421
  if (command.includes('git')) {
413
- return await handleGitCommand({ event, command, agentDir: ctx.agentDir })
422
+ return await handleGitCommand({ event, command, agentDir: ctx.agentDir, sessionId: event.sessionId })
414
423
  }
415
424
  return
416
425
  },
@@ -745,8 +745,9 @@ async function ensureMemoryFiles(agentDir: string): Promise<void> {
745
745
 
746
746
  // Force-add gitignored memory artifacts so the agent folder's git history
747
747
  // captures consolidation as a single recoverable snapshot. Skips silently when
748
- // the folder is not a git repo or bun is unavailable. Uses the user's global
749
- // git config for authorship.
748
+ // the folder is not a git repo or bun is unavailable. Uses Git's ambient
749
+ // identity: host config in host-stage calls, or the agent repo identity
750
+ // injected into the container process at start.
750
751
  //
751
752
  // After committing, the tracked memory artifacts get the `skip-worktree` index
752
753
  // flag set so manual `git status` / `git diff` ignore future runtime edits.
@@ -23,7 +23,13 @@ export type EffectiveApprovalResolver = (target: {
23
23
  // push-during-review still blocks a same-verdict duplicate for the lag window.
24
24
  export type HeadShaResolver = (target: { workspace: string; prNumber: number }) => Promise<string | null>
25
25
 
26
- export type ApproveBlock = { block: true; reason: string }
26
+ export type ApproveBlock = {
27
+ block: true
28
+ kind: 'concurrent' | 'duplicate'
29
+ reason: string
30
+ duplicateSource?: 'standing' | 'recent'
31
+ leaseRetained?: boolean
32
+ }
27
33
 
28
34
  export type ReviewVerdictGuard = {
29
35
  guard: (args: {
@@ -31,6 +37,7 @@ export type ReviewVerdictGuard = {
31
37
  workspace: string
32
38
  prNumber: number
33
39
  verdict: ReviewVerdict
40
+ retainDuplicateLease?: boolean
34
41
  }) => Promise<ApproveBlock | null>
35
42
  release: (args: { callId: string; succeeded: boolean }) => Promise<void>
36
43
  // Arms the read-after-write lag shield for a verdict that landed WITHOUT a prior
@@ -203,7 +210,7 @@ export function createApproveIdempotencyGuard(deps: {
203
210
  // reclaimable so a crash cannot permanently strand the PR.
204
211
  const held = inFlightByPr.get(key)
205
212
  if (held !== undefined && now() - held.createdAt < LEASE_TTL_MS) {
206
- return { block: true, reason: CONCURRENT_REASON }
213
+ return { block: true, kind: 'concurrent', reason: CONCURRENT_REASON }
207
214
  }
208
215
  const reservation: Reservation = {
209
216
  key,
@@ -232,8 +239,14 @@ export function createApproveIdempotencyGuard(deps: {
232
239
  // now: a blocked command never reaches tool.after, so release() won't run
233
240
  // for this callId. Leaving the lease set would resurrect the strand bug —
234
241
  // the GitHub read is authoritative for the standing case.
235
- releaseReservation(args.callId, reservation)
236
- return { block: true, reason: duplicateReason(args.verdict) }
242
+ if (args.retainDuplicateLease !== true) releaseReservation(args.callId, reservation)
243
+ return {
244
+ block: true,
245
+ kind: 'duplicate',
246
+ reason: duplicateReason(args.verdict),
247
+ duplicateSource: 'standing',
248
+ ...(args.retainDuplicateLease === true ? { leaseRetained: true } : {}),
249
+ }
237
250
  }
238
251
 
239
252
  // Layer 3 — duplicate-review cooldown. A recently-landed SAME verdict on the
@@ -254,7 +267,12 @@ export function createApproveIdempotencyGuard(deps: {
254
267
  recentlyLandedSame(key, args.verdict, headSha, now)
255
268
  ) {
256
269
  releaseReservation(args.callId, reservation)
257
- return { block: true, reason: duplicateReason(args.verdict) }
270
+ return {
271
+ block: true,
272
+ kind: 'duplicate',
273
+ reason: duplicateReason(args.verdict),
274
+ duplicateSource: 'recent',
275
+ }
258
276
  }
259
277
 
260
278
  return null
@@ -214,7 +214,12 @@ export function disengageReactionEmojiFor(adapter: AdapterId): string {
214
214
  return DISENGAGE_REACTION_EMOJI_OVERRIDES[adapter] ?? DISENGAGE_REACTION_EMOJI
215
215
  }
216
216
 
217
- type SilentAckReason = 'skip_response' | 'no_reply' | 'skip_response_text_leak' | 'github_review_output'
217
+ type SilentAckReason =
218
+ | 'skip_response'
219
+ | 'no_reply'
220
+ | 'skip_response_text_leak'
221
+ | 'github_review_output'
222
+ | 'awaiting_background_child'
218
223
 
219
224
  // Wake nudge pushed into a resumed channel session at boot so drain() has a
220
225
  // non-empty batch and fires a turn. The substantive instruction the model acts
@@ -1004,6 +1009,13 @@ type LiveSession = {
1004
1009
  // counter is purely monotonic; the matching comparison is what protects
1005
1010
  // against stale state.
1006
1011
  turnSeq: number
1012
+ // Clock time the current LOGICAL turn opened — stamped only on a real user
1013
+ // batch, so the reminder-only iterations a retry queues stay inside the same
1014
+ // logical turn. Unlike `turnSeq` (which increments per drain iteration) this
1015
+ // gives background-child checks a boundary they can compare a child's
1016
+ // `startedAt` against, to tell "this turn spawned it" from "it was already
1017
+ // running when unrelated work arrived".
1018
+ logicalTurnStartedAt: number
1007
1019
  // Snapshot of `successfulChannelSends` taken at turn start (same
1008
1020
  // moment `turnSeq` increments). Lets `markTurnSkipped` detect "a
1009
1021
  // channel send already landed in this turn" and reject the skip,
@@ -1286,6 +1298,10 @@ export type SendSource = 'tool' | 'system'
1286
1298
 
1287
1299
  export type SendOptions = {
1288
1300
  source?: SendSource
1301
+ // Apply tool-send accounting to the originating conversation while delivering
1302
+ // elsewhere. The outbound target remains unchanged; only per-turn cap/dedup,
1303
+ // output bookkeeping, and continuation state use this key.
1304
+ accountingTarget?: ChannelKey
1289
1305
  // Classifies what the human saw, independently of which router path sent it.
1290
1306
  // Tool calls omit this: substantive text is the default, while the shared
1291
1307
  // multilingual willingness detector recognizes status updates. System paths
@@ -2046,6 +2062,23 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2046
2062
  return false
2047
2063
  }
2048
2064
 
2065
+ // Same question as the GC/rollover pin, asked for a different decision: while a
2066
+ // background child is still working (and inside the stuck backstop), an empty
2067
+ // completion from the parent is the subagent contract being honored, not the
2068
+ // provider degeneration the turn-recovery ladder exists to repair.
2069
+ //
2070
+ // Turn-scoped, unlike the GC pin, which is deliberately session-scoped. Only
2071
+ // the logical turn that spawned the child is waiting on it; a later inbound is
2072
+ // unrelated work whose own recovery, todo continuation and staged fallback must
2073
+ // still run. Session scope would let one long-running child silence every
2074
+ // subsequent turn, and a wedged child would strand them with nothing to revisit
2075
+ // them after the backstop expires.
2076
+ const isAwaitingBackgroundChild = (live: LiveSession, label: string): boolean => {
2077
+ const childStartedAt = newestRunningChildSubagentStartedAt(live.sessionId)
2078
+ if (childStartedAt === null || childStartedAt < live.logicalTurnStartedAt) return false
2079
+ return isPinnedByRunningChild(live.sessionId, live.keyId, label)
2080
+ }
2081
+
2049
2082
  const shouldRolloverLive = (live: LiveSession, idleMs: number): boolean => {
2050
2083
  // A session mid-prompt looks idle by lastInboundAt (only bumped on engaged
2051
2084
  // inbounds) while session.prompt() is still in flight; rolling it over aborts
@@ -2333,6 +2366,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
2333
2366
  sendTimestamps: new Map(),
2334
2367
  successfulChannelSends: 0,
2335
2368
  turnSeq: 0,
2369
+ logicalTurnStartedAt: now(),
2336
2370
  successfulSendsAtTurnStart: 0,
2337
2371
  inFlightToolSends: new Map(),
2338
2372
  policyDeniedToolSendsThisTurn: new Map(),
@@ -3254,6 +3288,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3254
3288
  live.toolLeakRetries = 0
3255
3289
  live.emptyStopAfterToolWorkArmed = false
3256
3290
  live.willingnessNudges = 0
3291
+ live.logicalTurnStartedAt = now()
3257
3292
  // A fresh batch supersedes a still-pending staged fallback. That staged
3258
3293
  // turn produced no usable reply, so it must not leave the PRIOR turn's
3259
3294
  // committed lastQuestionSignal behind — otherwise the new question would
@@ -3483,10 +3518,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3483
3518
  logger.warn(`[channels] ${live.keyId}: skipping todo continuation after failed outcome write`)
3484
3519
  } else if (live.userStoppedTurnSeq === live.turnSeq) {
3485
3520
  logger.info(`[channels] ${live.keyId}: skipping todo continuation after user stop`)
3521
+ } else if (isAwaitingBackgroundChild(live, 'todo-continuation')) {
3522
+ // The outstanding todo is usually the very work the running child was
3523
+ // spawned to do, so continuing here re-wakes a session that is
3524
+ // deliberately waiting and asks the model to report progress it does
3525
+ // not have yet. The child's completion reminder is the correct wake.
3526
+ logger.info(`[channels] ${live.keyId}: skipping todo continuation while background child runs`)
3486
3527
  } else {
3487
3528
  await maybeContinueTodosChannel(live)
3488
3529
  }
3489
- await resolveStagedFallback(live)
3530
+ if (!isAwaitingBackgroundChild(live, 'staged-fallback')) {
3531
+ await resolveStagedFallback(live)
3532
+ }
3490
3533
  live.lastTurnAuthorIds = new Set(live.currentTurnAuthorIds)
3491
3534
  if (live.currentTurnAuthorId !== null) {
3492
3535
  live.lastTurnAuthorId = live.currentTurnAuthorId
@@ -4601,14 +4644,20 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4601
4644
  if (!flood.ok) return { ok: false, error: OUTBOUND_FLOOD_ERROR, code: 'outbound-flood' }
4602
4645
  }
4603
4646
 
4604
- const keyId = channelKeyId({
4647
+ const accountingTarget = opts?.accountingTarget ?? {
4605
4648
  adapter: msg.adapter,
4606
4649
  workspace: msg.workspace,
4607
4650
  chat: msg.chat,
4608
4651
  thread: msg.thread ?? null,
4609
- })
4652
+ }
4653
+ const deliveryMatchesAccounting =
4654
+ accountingTarget.adapter === msg.adapter &&
4655
+ accountingTarget.workspace === msg.workspace &&
4656
+ accountingTarget.chat === msg.chat &&
4657
+ accountingTarget.thread === (msg.thread ?? null)
4658
+ const keyId = channelKeyId(accountingTarget)
4610
4659
  const live = liveSessions.get(keyId)
4611
- const sendKey = consecutiveSendKey(msg.chat, msg.thread)
4660
+ const sendKey = consecutiveSendKey(accountingTarget.chat, accountingTarget.thread)
4612
4661
  // Tool-source sends consume the captured quote candidate exactly
4613
4662
  // once per turn — the intervening-observed check runs HERE against
4614
4663
  // the live buffer so the relevant signal is actual channel chatter
@@ -4618,7 +4667,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4618
4667
  // before the model's own first reply lands. Even when the decision
4619
4668
  // returns null (nothing intervened), the candidate is cleared — a
4620
4669
  // multi-part reply must not retroactively anchor chunk 2.
4621
- if (live && source === 'tool' && live.pendingQuoteCandidate !== null) {
4670
+ if (live && deliveryMatchesAccounting && source === 'tool' && live.pendingQuoteCandidate !== null) {
4622
4671
  const quoteCandidate = refreshQuoteCandidate(live.pendingQuoteCandidate, live.contextBuffer)
4623
4672
  const anchor = decideQuoteAnchor(quoteCandidate, now(), options.configForAdapter(msg.adapter))
4624
4673
  if (anchor !== null) {
@@ -4713,7 +4762,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4713
4762
  // The adapter needs the typing anchor to clear a flat-DM status (msg.thread
4714
4763
  // is null there, so a thread-keyed clear would no-op). Kept off msg.thread
4715
4764
  // to leave reply threading untouched.
4716
- if (live?.currentTurnTypingThread != null && msg.typingThread === undefined) {
4765
+ if (live?.currentTurnTypingThread != null && deliveryMatchesAccounting && msg.typingThread === undefined) {
4717
4766
  msg = { ...msg, typingThread: live.currentTurnTypingThread }
4718
4767
  }
4719
4768
 
@@ -4908,6 +4957,32 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4908
4957
  return
4909
4958
  }
4910
4959
 
4960
+ // A background child spawned by this session is still running, and the turn
4961
+ // produced no user-facing output. That is `spawn_subagent`'s contract being
4962
+ // honored ("you will receive a system-reminder when it completes"), not the
4963
+ // empty-completion degeneration every branch below exists to repair — so the
4964
+ // recovery ladder must not manufacture the status prose the model
4965
+ // deliberately withheld. Each nudge re-enters with the child STILL running,
4966
+ // so the budgets stack (MAX_EMPTY_TURN_RETRIES + MAX_WILLINGNESS_NUDGES) into
4967
+ // several "still working…" messages for one request; on GitHub, where a
4968
+ // channel reply IS a public PR comment, that shipped as duplicate review
4969
+ // acknowledgements. The completion reminder re-wakes this session with the
4970
+ // real result, so silence here is delivery deferred, not delivery dropped.
4971
+ // Bounded by the same stuck-child backstop as GC/rollover: a wedged child
4972
+ // stops pinning and the normal ladder resumes. A leaf carrying real text is
4973
+ // deliberately NOT covered — recovering an answer the model already wrote is
4974
+ // still correct while a child runs.
4975
+ const awaitLeaf = recoverableAssistantText(live.session)
4976
+ if (
4977
+ live.currentTurnAuthorId !== null &&
4978
+ (awaitLeaf === null || endsWithNoReplySignal(awaitLeaf.text)) &&
4979
+ isAwaitingBackgroundChild(live, 'empty_turn_recovery')
4980
+ ) {
4981
+ logger.info(`[channels] ${live.keyId} empty_turn_suppressed cause=awaiting_background_child`)
4982
+ armSilentTurnAck(live, 'awaiting_background_child')
4983
+ return
4984
+ }
4985
+
4911
4986
  // Suppress a leaked tool call (never post the plumbing) and, while budget
4912
4987
  // remains, push a self-correction reminder so the same logical turn
4913
4988
  // re-prompts and the model can redo it with a real tool call. On exhaustion
@@ -344,10 +344,10 @@ function itemHint(item: ViewerItem): { hint: string } {
344
344
  return { hint: '(no prompt)' }
345
345
  }
346
346
 
347
- function sessionRowLabel(s: SessionSummary): string {
347
+ export function sessionRowLabel(s: SessionSummary): string {
348
348
  const id = shortSessionId(s.sessionId)
349
349
  const label = s.origin === null ? '(unknown origin)' : originLabel(s.origin)
350
- const when = s.live === true ? c.green('live · replying') : c.dim(formatRelative(s.mtimeMs))
350
+ const when = s.live === true ? c.green('live') : c.dim(formatRelative(s.mtimeMs))
351
351
  return `${c.cyan(id)} ${label} ${when}`
352
352
  }
353
353
 
@@ -8,6 +8,7 @@ import { migrateAgentMessengerConfigDir, resolveAgentMessengerConfigPolicy } fro
8
8
  import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config, type PortForward } from '@/config'
9
9
  import { applyBoundGcConfig } from '@/git/bound-gc-config'
10
10
  import { commitGitignoreWithUntracks, untrackTrulyIgnoredFiles } from '@/git/reconcile-ignored'
11
+ import { resolveGitIdentity, type GitIdentity } from '@/git/resolve-identity'
11
12
  import { commitSystemFile as commitSystemFileShared } from '@/git/system-commit'
12
13
  import { send as sendToDaemon } from '@/hostd/client'
13
14
  import { ensureModels as ensureHostModels } from '@/hostd/models'
@@ -92,6 +93,7 @@ export type PlanStartOptions = {
92
93
  // POSIX identity whose ownership bind-mounted runtime writes must retain.
93
94
  // Omitted when unavailable (native Windows and unusual JS hosts).
94
95
  hostIdentity?: { uid: number; gid: number } | null
96
+ gitIdentity?: GitIdentity | null
95
97
  }
96
98
 
97
99
  export type HostDaemonControl = {
@@ -703,6 +705,7 @@ export async function planStart({
703
705
  tuiToken = null,
704
706
  platform = process.platform,
705
707
  hostIdentity = currentHostIdentity(),
708
+ gitIdentity,
706
709
  }: PlanStartOptions): Promise<StartPlan> {
707
710
  const containerName = containerNameFromCwd(cwd)
708
711
  const imageTag = imageTagFromCwd(cwd)
@@ -856,6 +859,19 @@ export async function planStart({
856
859
  if (existsSync(join(cwd, ENV_FILE))) {
857
860
  runArgs.push('--env-file', join(cwd, ENV_FILE))
858
861
  }
862
+ const resolvedGitIdentity = gitIdentity === undefined ? await resolveGitIdentity(cwd) : gitIdentity
863
+ if (resolvedGitIdentity !== null) {
864
+ runArgs.push(
865
+ '-e',
866
+ `GIT_AUTHOR_NAME=${resolvedGitIdentity.name}`,
867
+ '-e',
868
+ `GIT_AUTHOR_EMAIL=${resolvedGitIdentity.email}`,
869
+ '-e',
870
+ `GIT_COMMITTER_NAME=${resolvedGitIdentity.name}`,
871
+ '-e',
872
+ `GIT_COMMITTER_EMAIL=${resolvedGitIdentity.email}`,
873
+ )
874
+ }
859
875
  const agentMessengerPolicy = resolveAgentMessengerConfigPolicy(cwd)
860
876
  if (agentMessengerPolicy.override === null) {
861
877
  runArgs.push('-e', `AGENT_MESSENGER_CONFIG_DIR=${agentMessengerPolicy.containerDir}`)
@@ -0,0 +1,66 @@
1
+ import { resolveAgentGit } from './resolve-agent-git'
2
+ import { runGit } from './run'
3
+
4
+ export type GitIdentity = { name: string; email: string }
5
+
6
+ const GIT_CONFIG_ENV = {
7
+ GIT_CONFIG_GLOBAL: '/dev/null',
8
+ GIT_CONFIG_NOSYSTEM: '1',
9
+ GIT_TERMINAL_PROMPT: '0',
10
+ } as const
11
+
12
+ const GIT_REPOSITORY_ENV_NAMES = new Set([
13
+ 'GIT_COMMON_DIR',
14
+ 'GIT_DIR',
15
+ 'GIT_INDEX_FILE',
16
+ 'GIT_OBJECT_DIRECTORY',
17
+ 'GIT_WORK_TREE',
18
+ ])
19
+
20
+ export async function resolveGitIdentity(cwd: string): Promise<GitIdentity | null> {
21
+ const repo = resolveAgentGit(cwd)
22
+ if (repo === null) return null
23
+
24
+ const values = await readRepositoryIdentity(cwd, repo.gitArgs)
25
+ const name = values.get('user.name')?.at(-1)?.trim() || null
26
+ const email = values.get('user.email')?.at(-1)?.trim() || null
27
+ return name !== null && email !== null ? { name, email } : null
28
+ }
29
+
30
+ async function readRepositoryIdentity(cwd: string, gitArgs: readonly string[]): Promise<Map<string, string[]>> {
31
+ try {
32
+ const result = await runGit(Bun, cwd, [...gitArgs, 'config', '--null', '--get-regexp', '^user\\.(name|email)$'], {
33
+ env: { ...withoutGitOverrides(process.env), ...GIT_CONFIG_ENV },
34
+ })
35
+ if (result.exitCode !== 0) return new Map()
36
+ return parseNullConfigEntries(result.stdout)
37
+ } catch {
38
+ return new Map()
39
+ }
40
+ }
41
+
42
+ function parseNullConfigEntries(output: string): Map<string, string[]> {
43
+ const values = new Map<string, string[]>()
44
+ for (const entry of output.split('\0')) {
45
+ if (entry.length === 0) continue
46
+ const separator = entry.indexOf('\n')
47
+ if (separator < 0) continue
48
+ const key = entry.slice(0, separator)
49
+ const value = entry.slice(separator + 1)
50
+ const existing = values.get(key)
51
+ if (existing === undefined) values.set(key, [value])
52
+ else existing.push(value)
53
+ }
54
+ return values
55
+ }
56
+
57
+ function withoutGitOverrides(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
58
+ return Object.fromEntries(
59
+ Object.entries(env).filter(([name]) => {
60
+ const normalized = name.toUpperCase()
61
+ return !normalized.startsWith('GIT_CONFIG') && !GIT_REPOSITORY_ENV_NAMES.has(normalized)
62
+ }),
63
+ )
64
+ }
65
+
66
+ export const _internal = { withoutGitOverrides }
package/src/git/run.ts CHANGED
@@ -33,10 +33,12 @@ export async function runGit(
33
33
  bun: { spawn: typeof Bun.spawn },
34
34
  cwd: string,
35
35
  args: readonly string[],
36
+ options: { env?: NodeJS.ProcessEnv } = {},
36
37
  ): Promise<RunGitResult> {
37
38
  const proc = bun.spawn({
38
39
  cmd: ['git', ...hooklessGitArgs(args)],
39
40
  cwd,
41
+ env: options.env,
40
42
  stdout: 'pipe',
41
43
  stderr: 'pipe',
42
44
  })
@@ -4,8 +4,8 @@ import { resolveAgentGit } from './resolve-agent-git'
4
4
  // Commits TypeClaw-owned tracked files (.gitignore, package.json,
5
5
  // typeclaw.json) if any are dirty in git. Skips silently when the agent
6
6
  // folder is not a git repo, when Bun is unavailable, or when every named
7
- // file is clean. Uses the user's global git config for authorship —
8
- // TypeClaw does not impersonate the user here.
7
+ // file is clean. Uses Git's ambient identity: host config in host-stage calls,
8
+ // or the agent repo identity injected into the container process at start.
9
9
  //
10
10
  // Accepts a single file or an array; the array form produces a single
11
11
  // atomic commit covering all listed paths (used for migrations that touch
@@ -1,7 +1,5 @@
1
- import type { LiveSessionPayload } from '@/shared'
2
-
3
1
  import type { ViewerItem } from './item'
4
- import { listSessions, type ListSessionsOptions, mergeLiveSessions, type SessionSummary } from './session-list'
2
+ import { listSessions, type ListSessionsOptions, type SessionSummary } from './session-list'
5
3
 
6
4
  export type ListViewerItemsOptions = ListSessionsOptions & {
7
5
  containerRunning: boolean
@@ -16,9 +14,6 @@ export type ListViewerItemsOptions = ListSessionsOptions & {
16
14
  // (most-recent) tui transcript — and any older tui transcript the heuristic
17
15
  // would otherwise promote — must NOT be offered as a writable live row.
18
16
  allowWritable?: boolean
19
- // Registry sessions not yet flushed to disk, fetched by the CLI over the
20
- // /inspect WS. The lib layer stays I/O-free; the caller owns the connection.
21
- liveSessions?: LiveSessionPayload[]
22
17
  }
23
18
 
24
19
  export type ViewerList = {
@@ -34,11 +29,7 @@ export type ViewerList = {
34
29
  // `logs` row is appended last (container stdout, available offline) so it sits
35
30
  // below the divider in the picker.
36
31
  export async function listViewerItems(opts: ListViewerItemsOptions): Promise<ViewerList> {
37
- const diskSessions = await listSessions(opts)
38
- const sessions =
39
- opts.liveSessions !== undefined && opts.liveSessions.length > 0
40
- ? mergeLiveSessions(diskSessions, opts.liveSessions)
41
- : diskSessions
32
+ const sessions = await listSessions(opts)
42
33
  const allowWritable = opts.interactive && opts.allowWritable !== false
43
34
  const writableSessionId = opts.containerRunning && allowWritable ? pickWritableSession(sessions) : null
44
35
 
@@ -14,10 +14,9 @@ export type SessionSummary = {
14
14
  mtimeMs: number
15
15
  origin: MinimalSessionOrigin | null
16
16
  firstPrompt: string | null
17
- // True only for a registry-derived session with no .jsonl on disk yet (a
18
- // reply is in flight). Disk sessions leave this undefined. Selecting one tails
19
- // live-only: streamSessionEvents replays an empty file, then the WS delivers
20
- // events as they happen.
17
+ // True only for a registered session with no .jsonl on disk yet. Registration
18
+ // means the session is warm, not that a reply is currently in flight. Disk
19
+ // sessions leave this undefined.
21
20
  live?: boolean
22
21
  }
23
22
 
@@ -26,6 +25,7 @@ export type ListSessionsOptions = {
26
25
  limit?: number
27
26
  sinceMs?: number
28
27
  onWarn?: (msg: string) => void
28
+ liveSessions?: LiveSessionPayload[]
29
29
  }
30
30
 
31
31
  // pi-coding-agent writes session files as `${ISO_TIMESTAMP}_${SESSION_ID}.jsonl`,
@@ -72,17 +72,23 @@ type StatEntry = { path: string; basename: string; sessionId: string; mtimeMs: n
72
72
  // Split from listSessions so resolveSession can match ids first and peek only the
73
73
  // candidates, instead of reading every file body on disk. Reads no file content.
74
74
  async function statSessionFiles(opts: ListSessionsOptions): Promise<StatEntry[]> {
75
+ return (await scanSessionFiles(opts)).eligible
76
+ }
77
+
78
+ async function scanSessionFiles(
79
+ opts: ListSessionsOptions,
80
+ ): Promise<{ eligible: StatEntry[]; onDiskSessionIds: Set<string> }> {
75
81
  const entries = await readSessionFiles(opts.sessionsDir, opts.onWarn)
76
82
  const withStats = await mapConcurrent(entries, SESSION_IO_CONCURRENCY, async (entry) => {
77
83
  const s = await safeStat(entry.path)
78
84
  if (s === null) return null
79
85
  const mtimeMs = s.mtimeMs
80
- if (opts.sinceMs !== undefined && mtimeMs < opts.sinceMs) return null
81
86
  return { ...entry, mtimeMs }
82
87
  })
83
88
  const valid = withStats.filter((v): v is StatEntry => v !== null)
84
- valid.sort((a, b) => b.mtimeMs - a.mtimeMs)
85
- return valid
89
+ const eligible = opts.sinceMs === undefined ? valid : valid.filter((entry) => entry.mtimeMs >= opts.sinceMs!)
90
+ eligible.sort((a, b) => b.mtimeMs - a.mtimeMs)
91
+ return { eligible, onDiskSessionIds: new Set(valid.map((entry) => entry.sessionId)) }
86
92
  }
87
93
 
88
94
  async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void): Promise<SessionSummary> {
@@ -98,18 +104,25 @@ async function summarizeEntry(entry: StatEntry, onWarn?: (msg: string) => void):
98
104
  }
99
105
 
100
106
  export async function listSessions(opts: ListSessionsOptions): Promise<SessionSummary[]> {
101
- const valid = await statSessionFiles(opts)
102
- const limited = opts.limit !== undefined ? valid.slice(0, opts.limit) : valid
103
- return mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
107
+ const { eligible, onDiskSessionIds } = await scanSessionFiles(opts)
108
+ const limited = opts.limit !== undefined ? eligible.slice(0, opts.limit) : eligible
109
+ const disk = await mapConcurrent(limited, SESSION_IO_CONCURRENCY, (entry) => summarizeEntry(entry, opts.onWarn))
110
+ if (opts.liveSessions === undefined || opts.liveSessions.length === 0) return disk
111
+ return mergeLiveSessions(disk, opts.liveSessions, { onDiskSessionIds, limit: opts.limit })
104
112
  }
105
113
 
106
114
  // Overlay container-registry sessions onto the disk listing. A live session
107
- // already flushed to disk (post-reply) is dropped from the overlay — the disk
115
+ // already flushed to disk is dropped from the overlay — the disk
108
116
  // summary wins, carrying its real mtime and prompt preview. Only sessions with
109
117
  // no .jsonl yet become synthetic live rows, sorted to the top by registration
110
- // time so an in-flight reply surfaces above settled history.
111
- export function mergeLiveSessions(disk: SessionSummary[], live: LiveSessionPayload[]): SessionSummary[] {
112
- const onDisk = new Set(disk.map((s) => s.sessionId))
118
+ // time. The final limit applies after merging, so registry-only rows displace
119
+ // older history rather than expanding the picker.
120
+ export function mergeLiveSessions(
121
+ disk: SessionSummary[],
122
+ live: LiveSessionPayload[],
123
+ opts: { onDiskSessionIds?: ReadonlySet<string>; limit?: number } = {},
124
+ ): SessionSummary[] {
125
+ const onDisk = opts.onDiskSessionIds ?? new Set(disk.map((s) => s.sessionId))
113
126
  const liveOnly = live
114
127
  .filter((l) => !onDisk.has(l.sessionId))
115
128
  .map(
@@ -123,7 +136,8 @@ export function mergeLiveSessions(disk: SessionSummary[], live: LiveSessionPaylo
123
136
  live: true,
124
137
  }),
125
138
  )
126
- return [...liveOnly, ...disk].sort((a, b) => b.mtimeMs - a.mtimeMs)
139
+ const merged = [...liveOnly, ...disk].sort((a, b) => b.mtimeMs - a.mtimeMs)
140
+ return opts.limit !== undefined ? merged.slice(0, opts.limit) : merged
127
141
  }
128
142
 
129
143
  export type ResolveResult =
package/src/run/index.ts CHANGED
@@ -5,7 +5,7 @@ import { SessionManager } from '@mariozechner/pi-coding-agent'
5
5
  import { createSession, createSessionWithDispose } from '@/agent'
6
6
  import { createProviderAuthReloadable } from '@/agent/auth-reloadable'
7
7
  import { LiveSessionRegistry } from '@/agent/live-sessions'
8
- import { LiveSubagentRegistry } from '@/agent/live-subagents'
8
+ import { LiveSubagentRegistry, newestRunningBackgroundChildStartedAt } from '@/agent/live-subagents'
9
9
  import { requestContainerRestart } from '@/agent/restart'
10
10
  import { consumeRestartHandoff } from '@/agent/restart-handoff'
11
11
  import { sessionMetaPayload } from '@/agent/session-meta'
@@ -475,13 +475,7 @@ async function startAgentRuntime(
475
475
  githubTokenBridge,
476
476
  stream,
477
477
  newestRunningChildSubagentStartedAt: (sessionId) =>
478
- liveSubagentRegistry
479
- .list({ parentSessionId: sessionId })
480
- .reduce<number | null>(
481
- (newest, child) =>
482
- child.status === 'running' && (newest === null || child.startedAt > newest) ? child.startedAt : newest,
483
- null,
484
- ),
478
+ newestRunningBackgroundChildStartedAt(liveSubagentRegistry.list({ parentSessionId: sessionId })),
485
479
  listRunningBackgroundSubagentNames: (sessionId) =>
486
480
  liveSubagentRegistry
487
481
  .list({ parentSessionId: sessionId })
@@ -54,6 +54,13 @@ const EXECUTION_CONTROL_ENV_NAMES = new Set<string>([
54
54
 
55
55
  const EXECUTION_CONTROL_ENV_PREFIXES = ['GIT_CONFIG', 'BASH_FUNC_'] as const
56
56
 
57
+ const GIT_IDENTITY_ENV_NAMES = [
58
+ 'GIT_AUTHOR_NAME',
59
+ 'GIT_AUTHOR_EMAIL',
60
+ 'GIT_COMMITTER_NAME',
61
+ 'GIT_COMMITTER_EMAIL',
62
+ ] as const
63
+
57
64
  // Withheld ONLY when the name would compromise sandbox integrity or claim a
58
65
  // host/container-injected runtime token — not for being credential-shaped. `.env`
59
66
  // is the operator's expose-to-the-agent surface: every value they declare there
@@ -66,18 +73,24 @@ function isWithheldEnvName(name: string): boolean {
66
73
  return EXECUTION_CONTROL_ENV_PREFIXES.some((prefix) => name === prefix || name.startsWith(prefix))
67
74
  }
68
75
 
69
- // Every name an operator declared in the `.env` FILE with a non-empty value,
70
- // minus the sandbox-integrity/broker withholds. Eligibility is decided from the
71
- // PARSED `.env` value, never process.env: an empty `.env` line (`X=`) is not an
72
- // operator expose-choice even if hydrateChannelEnvFromSecrets later fills
73
- // process.env[X] from secrets.json. The inherited VALUE is still snapshotted
74
- // from process.env at spawn time.
75
- export function resolveExposableEnvNames(declaredEnv: ReadonlyMap<string, string>): string[] {
76
+ // Every non-empty name declared in `.env`, minus sandbox-integrity/broker
77
+ // withholds, plus the four Git identity names that `typeclaw start` resolves
78
+ // from the agent repository and owns in the container environment. No other
79
+ // process.env-only name is eligible: an empty `.env` line (`X=`) remains hidden
80
+ // even if secrets.json hydration later fills process.env[X]. Inherited VALUES
81
+ // are snapshotted from process.env at spawn time.
82
+ export function resolveExposableEnvNames(
83
+ declaredEnv: ReadonlyMap<string, string>,
84
+ runtimeEnv: Readonly<Record<string, string | undefined>> = {},
85
+ ): string[] {
76
86
  const out: string[] = []
77
87
  for (const [name, fileValue] of declaredEnv) {
78
88
  if (fileValue.length === 0) continue
79
89
  if (isWithheldEnvName(name)) continue
80
90
  out.push(name)
81
91
  }
92
+ for (const name of GIT_IDENTITY_ENV_NAMES) {
93
+ if (runtimeEnv[name]?.length && !out.includes(name)) out.push(name)
94
+ }
82
95
  return out
83
96
  }
@@ -115,7 +115,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
115
115
 
116
116
  **The reviewer's `<review>` block is the only source of the verdict and the findings.** You do not review the PR yourself. Between spawning the reviewer and reading its result you do **no analysis of this PR** — do not run `gh pr diff`, do not read the changed files to form an opinion, do not draft a verdict. The reviewer runs on the `deep` model precisely so this judgment is not yours to make on the parent model. If you analyze the diff and post your own assessment while the reviewer is still running, you will post one verdict now and the reviewer's (often different) verdict when it completes — **two contradictory reviews on the same PR**, the exact failure this flow exists to prevent. Wait for the reviewer; post what it returns; nothing before that.
117
117
 
118
- **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
118
+ **HARD RULE — a review with actionable findings is a formal review, never a flat comment.** If the reviewer returns **one or more** actionable findings (`blocker`/`concern`/`nit`), the ONLY acceptable way to deliver them is a formal review via `POST /pulls/<N>/reviews` (step 4) — `REQUEST_CHANGES`, `COMMENT`, or `APPROVE` per the verdict, with the line-anchored findings in `comments[]`. You may **never** flatten those findings into a `channel_reply` or a top-level issue comment, **even when** the `gh api` call fails. A 422 means an anchor is wrong (almost always a `line` not in the diff): re-anchor it or move that one finding into the top-level review `body`, then resubmit the formal review — do **not** abandon the formal review and post prose instead. A flat "## Review … two blockers" comment is a bug, not a fallback: it strands the findings without line anchors and is the exact failure this rule exists to prevent. The flat/issue-comment path is reserved for the **zero-actionable-findings** branch only (see below). **Narrow exception:** when `post_github_review` finds that this bot's identical `CHANGES_REQUESTED` verdict is already effective, the tool itself converts the redundant submission into one substantive root PR comment while the existing formal block remains authoritative. This is a successful tool-managed fallback, not permission to replace a failed or invalid formal review manually. If you genuinely cannot land a formal review after fixing anchors, say so plainly and post nothing that claims a review happened — silence beats a false receipt.
119
119
 
120
120
  1. **Minimal intake, then delegate immediately.** Capture only the repo, PR number, current head SHA, exact base OID, authorship, and the prior blocking context needed to identify a re-review. Do not inspect the diff or changed files. Batch the independent metadata/history reads where the tool interface permits.
121
121
 
@@ -185,7 +185,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
185
185
 
186
186
  **Operator approval policy.** If the inbound carries a note that PR approval is disabled (`channels.github.review.approve: false` — the adapter appends "Operator policy: PR approval is disabled for this agent" to the message), you must **not** submit an `APPROVE`. Map an `approve` verdict to `COMMENT` instead: post the same `<summary>` and all inline `comments[]` as a `COMMENT` review, just without the formal approval. `request-changes` and `comment` verdicts are unaffected (they never approve). Absent that note, approval is enabled and the table above applies unchanged.
187
187
 
188
- **Re-review.** If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block — never a top-level PR comment. The clearing mechanics depend on which form the prior block took:
188
+ **Re-review.** If step 1 established this is a re-review (an unresolved blocking obligation of yours — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), the result MUST clear or re-assert that block. The only top-level-comment exception is the tool-managed duplicate fallback described above: the existing identical `CHANGES_REQUESTED` already re-asserts the formal block, so the new summary/findings may be added as one root comment without posting another blocking review. The clearing mechanics depend on which form the prior block took:
189
189
  - **Prior block was a formal `CHANGES_REQUESTED`.** It is sticky: **only** a fresh `APPROVE` from you, or a dismissal of your prior review, clears it. A plain issue comment does **not** clear it, and — critically — **neither does a `COMMENT` review.**
190
190
  - **Prior block was a flat comment** (no formal `CHANGES_REQUESTED` exists). There is no sticky GitHub state to clear, but the obligation is still yours to discharge as a **formal** review so the verdict finally lands as review state: submit `APPROVE` (resolved, approval enabled) or `REQUEST_CHANGES` (not resolved). Do not discharge a flat-comment block with another flat comment — that re-strands the verdict, the original bug.
191
191
 
@@ -218,11 +218,11 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
218
218
  })
219
219
  ```
220
220
 
221
- Anchor mechanics: `line` is a line number **in the file**, not a position in the diff. `side: RIGHT` is the new revision (default for additions); `side: LEFT` is the old revision (use for comments on removed lines). For multi-line comments, also set `start_line` and `start_side` (same semantics). The tool resolves the head SHA, validates anchors against the complete PR diff, moves out-of-diff findings into the top-level body, enforces approval policy, and verifies the exact returned review id/state. Its successful receipt is proof that the formal review landed. On failure, fix the payload or policy issue and retry; never post a flat comment claiming the review succeeded.
221
+ Anchor mechanics: `line` is a line number **in the file**, not a position in the diff. `side: RIGHT` is the new revision (default for additions); `side: LEFT` is the old revision (use for comments on removed lines). For multi-line comments, also set `start_line` and `start_side` (same semantics). The tool resolves the head SHA, validates anchors against the complete PR diff, moves out-of-diff findings into the top-level body, enforces approval policy, and verifies the exact returned review id/state. Its successful receipt is proof that the output landed. A receipt with `details.fallback === "comment"` means the prior `CHANGES_REQUESTED` remains live and the new review content landed as one root PR comment; treat that as complete and do not add a `channel_reply`. On failure, fix the payload or policy issue and retry; never post a flat comment claiming the review succeeded.
222
222
 
223
223
  5. **The decoy reviewer is dropped for you — no action needed.** Under **GitHub App** auth, the adapter automatically removes the decoy reviewer from the PR's requested-reviewers list the moment your formal review lands (it reacts to your own `pull_request_review.submitted` webhook). Why this matters: GitHub auto-adds **you** (the App account) to the PR's reviewers when your review posts, but the **decoy** account would otherwise stay pinned as a perpetual "review requested", as if the review never happened. You do **not** need to issue a `DELETE /requested_reviewers` yourself — and you should not, since it would race the adapter's own cleanup. The removal is self-loop-safe: the adapter's `DELETE` is authenticated as the App, so the `review_request_removed` webhook carries your bot actor (`slug[bot]`) as `sender`, which the classifier drops (see "Self-loop safety" below). This is a no-op under **PAT** auth (no decoy) and for **plain-language**/**team** requests (no decoy user was placed). See [GitHub decoy reviewer](/docs/internals/github-decoy-reviewer).
224
224
 
225
- 6. **End the turn with `skip_response`, not a trace reply.** The formal review from step 4 already landed _in this PR_ — it carries the summary, the verdict, and the inline comments. A `channel_reply` here does **not** go to a separate operator channel; on GitHub it posts another public comment on the same PR. A one-line "Posted review on PR #N: …" narrated into the PR thread is meta-commentary addressed to a phantom operator, and it reads absurdly next to the review it claims to point at. So once `post_github_review` confirms success, call `skip_response({ reason: "review posted via post_github_review" })` to close the turn silently. Only fall back to `channel_reply` when there was **no** formal review to post — the zero-actionable-findings branch below uses `channel_reply` as the substantive reply.
225
+ 6. **End the turn with `skip_response`, not a trace reply.** The formal review or tool-managed duplicate fallback from step 4 already landed _in this PR_ — it carries the summary, verdict context, and findings. A `channel_reply` here does **not** go to a separate operator channel; on GitHub it posts another public comment on the same PR. A one-line "Posted review on PR #N: …" narrated into the PR thread is meta-commentary addressed to a phantom operator, and it reads absurdly next to the output it claims to point at. So once `post_github_review` confirms success, call `skip_response({ reason: "review posted via post_github_review" })` to close the turn silently. Only fall back to `channel_reply` when there was **no** review output to post — the zero-actionable-findings branch below uses `channel_reply` as the substantive reply.
226
226
 
227
227
  ### Zero actionable findings
228
228