typeclaw 0.45.0 → 0.46.0

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 (147) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -1,10 +1,10 @@
1
- import { mkdir, writeFile } from 'node:fs/promises'
2
1
  import { join, sep } from 'node:path'
3
2
 
4
3
  import { Type } from '@mariozechner/pi-ai'
5
4
  import { defineTool } from '@mariozechner/pi-coding-agent'
6
5
 
7
6
  import type { SessionOrigin } from '@/agent/session-origin'
7
+ import { TOOL_INPUT_MAX_BYTES, writeFileAnchored } from '@/agent/tool-file-safety'
8
8
  import type { ChannelRouter } from '@/channels/router'
9
9
  import type { AdapterId } from '@/channels/schema'
10
10
  import type { PermissionService } from '@/permissions'
@@ -32,6 +32,7 @@ export type CreateChannelFetchAttachmentToolOptions = {
32
32
  // its follow-up look_at/read). See buildChannelTools for the decision.
33
33
  resolveBaseDir?: () => string
34
34
  logger?: ChannelToolLogger
35
+ agentDir?: string
35
36
  }
36
37
 
37
38
  // workspace/ is private-surface: readable only by roles with fs.see.private.
@@ -46,6 +47,7 @@ export function createChannelFetchAttachmentTool({
46
47
  inboxDir,
47
48
  resolveBaseDir,
48
49
  logger = consoleChannelLogger,
50
+ agentDir = process.cwd(),
49
51
  }: CreateChannelFetchAttachmentToolOptions) {
50
52
  const fallbackBaseDir = inboxDir ?? DEFAULT_INBOX_DIR
51
53
  const adapter = origin.adapter
@@ -108,6 +110,7 @@ export function createChannelFetchAttachmentTool({
108
110
  const filename = params.filename ?? found.filename
109
111
  const result = await router.fetchAttachment(adapter, {
110
112
  ref,
113
+ maxBytes: TOOL_INPUT_MAX_BYTES.channel_upload,
111
114
  ...(filename !== undefined ? { filename } : {}),
112
115
  })
113
116
  if (!result.ok) {
@@ -123,8 +126,12 @@ export function createChannelFetchAttachmentTool({
123
126
  const targetDir = join(baseDir, adapter, refSlug)
124
127
  const targetPath = join(targetDir, safeFilename)
125
128
  try {
126
- await mkdir(targetDir, { recursive: true })
127
- await writeFile(targetPath, result.buffer)
129
+ await writeFileAnchored({
130
+ targetPath,
131
+ data: result.buffer,
132
+ agentDir,
133
+ tool: 'channel_fetch_attachment',
134
+ })
128
135
  } catch (err) {
129
136
  const message = err instanceof Error ? err.message : String(err)
130
137
  logger.warn(formatChannelToolFailure('channel_fetch_attachment', `${adapter}: write failed: ${message}`))
@@ -7,6 +7,7 @@ import {
7
7
  containsKimiToolDelimiter,
8
8
  isNoReplySignal,
9
9
  isUpstreamEmptyResponseSentinel,
10
+ stripTrailingLeakedToolCall,
10
11
  type ChannelRouter,
11
12
  } from '@/channels/router'
12
13
  import type { AdapterId } from '@/channels/schema'
@@ -100,7 +101,7 @@ export function createChannelReplyTool({
100
101
  }),
101
102
 
102
103
  async execute(_toolCallId, params) {
103
- const text = params.text
104
+ let text = params.text
104
105
  const attachments = params.attachments
105
106
  const keepTurnAlive = params.continue === true
106
107
  if ((text === undefined || text === '') && (attachments === undefined || attachments.length === 0)) {
@@ -140,6 +141,19 @@ export function createChannelReplyTool({
140
141
  }
141
142
  }
142
143
 
144
+ // Prose-then-trailing-call leak (mirrors router.ts + channel-send.ts):
145
+ // strip a serialized trailing tool call while keeping the real reply
146
+ // prose, rather than denying and stranding the user's answer.
147
+ if (text !== undefined) {
148
+ const trailingLeak = stripTrailingLeakedToolCall(text)
149
+ if (trailingLeak !== null && trailingLeak.text !== '') {
150
+ logger.warn(
151
+ formatChannelToolFailure('channel_reply', `stripped trailing_tool_call_leak tool=${trailingLeak.toolName}`),
152
+ )
153
+ text = trailingLeak.text
154
+ }
155
+ }
156
+
143
157
  // Required-choice guard: a terminal github review-thread text reply must
144
158
  // make an explicit resolve_review_thread choice. The model kept silently
145
159
  // omitting the flag after acknowledging a fix, leaving the thread open;
@@ -8,6 +8,7 @@ import {
8
8
  containsKimiToolDelimiter,
9
9
  isNoReplySignal,
10
10
  isUpstreamEmptyResponseSentinel,
11
+ stripTrailingLeakedToolCall,
11
12
  type ChannelRouter,
12
13
  } from '@/channels/router'
13
14
  import { ADAPTER_IDS, type AdapterId } from '@/channels/schema'
@@ -124,7 +125,7 @@ export function createChannelSendTool({
124
125
 
125
126
  async execute(_toolCallId, params) {
126
127
  const adapter = params.adapter as AdapterId
127
- const bodyText = params.text
128
+ let bodyText = params.text
128
129
  const attachments = params.attachments
129
130
  if ((bodyText === undefined || bodyText === '') && (attachments === undefined || attachments.length === 0)) {
130
131
  logger.warn(formatChannelToolFailure('channel_send', 'missing text and attachments'))
@@ -163,6 +164,21 @@ export function createChannelSendTool({
163
164
  }
164
165
  }
165
166
 
167
+ // Prose-then-trailing-call leak (mirrors router.ts validateChannelTurn):
168
+ // the model put a real reply plus a serialized trailing tool call in the
169
+ // `text` arg. Strip the plumbing and keep the prose rather than denying,
170
+ // so the legitimate reply still reaches the channel. Whole-message calls
171
+ // (no prose prefix) are untouched here and left to the router's recovery.
172
+ if (bodyText !== undefined) {
173
+ const trailingLeak = stripTrailingLeakedToolCall(bodyText)
174
+ if (trailingLeak !== null && trailingLeak.text !== '') {
175
+ logger.warn(
176
+ formatChannelToolFailure('channel_send', `stripped trailing_tool_call_leak tool=${trailingLeak.toolName}`),
177
+ )
178
+ bodyText = trailingLeak.text
179
+ }
180
+ }
181
+
166
182
  // Required-choice guard (mirrors channel_reply): a github PR review-thread
167
183
  // send with text must make an explicit resolve_review_thread choice. The
168
184
  // `pull_request.synchronize` recheck routes the post-push close-out HERE
@@ -12,7 +12,7 @@
12
12
  // TLS handshake + HTTP/2 settings + header ordering. See that file's header
13
13
  // for the full rationale and AGENTS.md §"Web search" for the original story.
14
14
 
15
- import { curlImpersonate } from './curl-impersonate'
15
+ import { CurlImpersonateError, curlImpersonate, isCurlExitTimeout } from './curl-impersonate'
16
16
  import { createKeyedSemaphore } from './keyed-semaphore'
17
17
  import { type SearchRetryOptions, withSearchRetry } from './search-retry'
18
18
 
@@ -61,12 +61,26 @@ export async function ddgSearch(query: string, limit: number, signal?: AbortSign
61
61
  }
62
62
  return parseDdgHtml(html).slice(0, limit)
63
63
  },
64
- { ...retryOverride, shouldRetry: (error) => error instanceof DdgCaptchaError, signal },
64
+ { ...retryOverride, shouldRetry: isTransientSearchError, signal },
65
65
  ),
66
66
  signal,
67
67
  )
68
68
  }
69
69
 
70
+ // Both a tripped CAPTCHA and a bare connection timeout are transient: DDG's
71
+ // gate lifts after a cooldown, and an egress timeout is almost always a
72
+ // momentary network blip (the incident that motivated this: an agent's egress
73
+ // timed out for a few minutes, then recovered). Retrying both under the bounded
74
+ // `withSearchRetry` backoff turns an otherwise-unbounded model-driven retry
75
+ // loop into at most `attempts` code-level tries that then surface a single
76
+ // terminal error. A hard network failure (DNS, refused, TLS) is NOT retried —
77
+ // it won't fix itself on a re-run and would just burn the budget.
78
+ export function isTransientSearchError(error: unknown): boolean {
79
+ if (error instanceof DdgCaptchaError) return true
80
+ if (error instanceof CurlImpersonateError && isCurlExitTimeout(error)) return true
81
+ return false
82
+ }
83
+
70
84
  export class DdgCaptchaError extends Error {
71
85
  constructor() {
72
86
  super('DuckDuckGo returned a CAPTCHA page (rate-limited). Try again later or with a different query.')
@@ -0,0 +1,199 @@
1
+ import { Type } from '@mariozechner/pi-ai'
2
+ import { defineTool } from '@mariozechner/pi-coding-agent'
3
+
4
+ import { recordReview, recordReviewOutput, type ReviewVerdict } from '@/channels/github-review-turn-ledger'
5
+ import { createSharedReviewVerdictGuard, type ReviewVerdictGuard } from '@/channels/github-review-verdict-coordinator'
6
+ import type { ChannelRouter } from '@/channels/router'
7
+ import type { ReviewFinding, SubmitReviewRequest } from '@/channels/types'
8
+
9
+ import { type ChannelToolLogger, consoleChannelLogger, formatChannelToolFailure } from './channel-log'
10
+ import { type ChannelReplyOrigin, TOOL_RESULT_PREFIX } from './channel-reply'
11
+ import { fenceToolResult } from './runtime-notice'
12
+
13
+ type PostGithubReviewDetails = {
14
+ ok: boolean
15
+ error?: string
16
+ code?: string
17
+ reviewId?: number
18
+ state?: string
19
+ downgraded?: boolean
20
+ reanchored?: ReviewFinding[]
21
+ }
22
+
23
+ export function createPostGithubReviewTool(options: {
24
+ router: ChannelRouter
25
+ origin: ChannelReplyOrigin
26
+ sessionId: string
27
+ logger?: ChannelToolLogger
28
+ verdictGuard?: ReviewVerdictGuard
29
+ }) {
30
+ const { router, origin, sessionId, logger = consoleChannelLogger } = options
31
+ const verdictGuard = options.verdictGuard ?? createSharedReviewVerdictGuard()
32
+ return defineTool({
33
+ name: 'post_github_review',
34
+ label: 'Post GitHub PR Review',
35
+ description:
36
+ 'GitHub channel sessions only. Submit a formal PR review. The adapter resolves the head SHA, validates diff anchors, moves out-of-diff findings into the body, enforces approval policy, and verifies the posted review.',
37
+ parameters: Type.Object({
38
+ event: Type.Union([Type.Literal('APPROVE'), Type.Literal('REQUEST_CHANGES'), Type.Literal('COMMENT')]),
39
+ body: Type.String({ minLength: 1 }),
40
+ comments: Type.Optional(
41
+ Type.Array(
42
+ Type.Object({
43
+ path: Type.String({ minLength: 1 }),
44
+ line: Type.Integer({ minimum: 1 }),
45
+ side: Type.Optional(Type.Union([Type.Literal('LEFT'), Type.Literal('RIGHT')])),
46
+ start_line: Type.Optional(Type.Integer({ minimum: 1 })),
47
+ start_side: Type.Optional(Type.Union([Type.Literal('LEFT'), Type.Literal('RIGHT')])),
48
+ body: Type.String({ minLength: 1 }),
49
+ }),
50
+ { minItems: 1 },
51
+ ),
52
+ ),
53
+ }),
54
+ async execute(toolCallId, params) {
55
+ if (origin.adapter !== 'github') return denied(logger, 'post_github_review is only supported on github sessions.')
56
+ const prNumber = parsePrNumber(origin.chat)
57
+ if (prNumber === null) return denied(logger, `invalid GitHub review target: ${origin.chat}`)
58
+ const verdict = decisiveVerdict(params.event)
59
+ const coordinationCallId = `${sessionId}:${toolCallId}`
60
+ if (verdict !== null) {
61
+ const blocked = await verdictGuard.guard({
62
+ callId: coordinationCallId,
63
+ workspace: origin.workspace,
64
+ prNumber,
65
+ verdict,
66
+ })
67
+ if (blocked !== null) return denied(logger, blocked.reason)
68
+ }
69
+ const request: SubmitReviewRequest = {
70
+ adapter: 'github',
71
+ workspace: origin.workspace,
72
+ chat: origin.chat,
73
+ event: params.event,
74
+ body: params.body,
75
+ comments: (params.comments ?? []).map(toReviewFinding),
76
+ }
77
+ let releaseAsLanded = false
78
+ try {
79
+ const result = await router.submitReview(request)
80
+ if (!result.ok) {
81
+ // A POST whose verification failed may already have landed. Keep the
82
+ // short conservative shield, but never credit an unverified ledger.
83
+ releaseAsLanded = verdict !== null && result.submitted === true
84
+ return denied(logger, result.error, result.code)
85
+ }
86
+
87
+ const effective = effectiveReviewState(result.state)
88
+ if (effective === null)
89
+ return denied(logger, `GitHub returned an unknown verified review state: ${result.state}`)
90
+ releaseAsLanded = verdict !== null && effective === verdict
91
+ creditVerifiedReview({ sessionId, workspace: origin.workspace, prNumber, effective })
92
+
93
+ const receipt = renderReceipt(
94
+ result.reviewId,
95
+ result.state,
96
+ result.downgraded === true,
97
+ result.reanchored ?? [],
98
+ )
99
+ const details: PostGithubReviewDetails = {
100
+ ok: true,
101
+ reviewId: result.reviewId,
102
+ state: result.state,
103
+ ...(result.downgraded === true ? { downgraded: true } : {}),
104
+ ...(result.reanchored !== undefined ? { reanchored: result.reanchored } : {}),
105
+ }
106
+ return { content: [{ type: 'text' as const, text: fenceToolResult(receipt) }], details }
107
+ } finally {
108
+ if (verdict !== null) {
109
+ await verdictGuard.release({ callId: coordinationCallId, succeeded: releaseAsLanded })
110
+ }
111
+ }
112
+ },
113
+ })
114
+ }
115
+
116
+ function parsePrNumber(chat: string): number | null {
117
+ const match = /^pr:(\d+)$/.exec(chat)
118
+ if (match?.[1] === undefined) return null
119
+ const value = Number(match[1])
120
+ return Number.isSafeInteger(value) && value > 0 ? value : null
121
+ }
122
+
123
+ function decisiveVerdict(event: SubmitReviewRequest['event']): ReviewVerdict | null {
124
+ return event === 'APPROVE' || event === 'REQUEST_CHANGES' ? event : null
125
+ }
126
+
127
+ function effectiveReviewState(state: string): ReviewVerdict | 'COMMENT' | null {
128
+ if (state === 'APPROVED') return 'APPROVE'
129
+ if (state === 'CHANGES_REQUESTED') return 'REQUEST_CHANGES'
130
+ if (state === 'COMMENTED') return 'COMMENT'
131
+ return null
132
+ }
133
+
134
+ function creditVerifiedReview(args: {
135
+ sessionId: string
136
+ workspace: string
137
+ prNumber: number
138
+ effective: ReviewVerdict | 'COMMENT'
139
+ }): void {
140
+ if (args.effective === 'COMMENT') {
141
+ recordReviewOutput({
142
+ sessionId: args.sessionId,
143
+ workspace: args.workspace,
144
+ prNumber: args.prNumber,
145
+ state: 'COMMENT',
146
+ })
147
+ return
148
+ }
149
+ // recordReview also emits the review-output observer signal for decisive
150
+ // states, keeping verdict and output credit atomic.
151
+ recordReview({
152
+ sessionId: args.sessionId,
153
+ workspace: args.workspace,
154
+ prNumber: args.prNumber,
155
+ verdict: args.effective,
156
+ })
157
+ }
158
+
159
+ function denied(logger: ChannelToolLogger, error: string, code?: string) {
160
+ logger.warn(formatChannelToolFailure('post_github_review', error))
161
+ const details: PostGithubReviewDetails = { ok: false, error, ...(code !== undefined ? { code } : {}) }
162
+ return {
163
+ content: [{ type: 'text' as const, text: `${TOOL_RESULT_PREFIX}post_github_review denied: ${error}` }],
164
+ details,
165
+ }
166
+ }
167
+
168
+ function toReviewFinding(comment: {
169
+ path: string
170
+ line: number
171
+ side?: 'LEFT' | 'RIGHT'
172
+ start_line?: number
173
+ start_side?: 'LEFT' | 'RIGHT'
174
+ body: string
175
+ }): ReviewFinding {
176
+ return {
177
+ path: comment.path,
178
+ line: comment.line,
179
+ ...(comment.side !== undefined ? { side: comment.side } : {}),
180
+ ...(comment.start_line !== undefined ? { startLine: comment.start_line } : {}),
181
+ ...(comment.start_side !== undefined ? { startSide: comment.start_side } : {}),
182
+ body: comment.body,
183
+ }
184
+ }
185
+
186
+ function renderReceipt(
187
+ reviewId: number,
188
+ state: string,
189
+ downgraded: boolean,
190
+ reanchored: readonly ReviewFinding[],
191
+ ): string {
192
+ const notes = [
193
+ downgraded ? 'APPROVE was downgraded to COMMENT by operator policy.' : null,
194
+ reanchored.length > 0
195
+ ? `${reanchored.length} out-of-diff finding(s) moved into the review body: ${reanchored.map((finding) => `${finding.path}:${finding.line}`).join(', ')}.`
196
+ : null,
197
+ ].filter((note): note is string => note !== null)
198
+ return [`GitHub review posted: id=${reviewId}, state=${state}.`, ...notes].join('\n')
199
+ }
@@ -176,24 +176,27 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
176
176
 
177
177
  void completion.then((c) => {
178
178
  const durationMs = now() - startedAt
179
- liveRegistry.recordCompletion(taskId, completionToFinalShape(c, durationMs))
180
- if (stream && background) {
181
- const hasRecoverableOutput = !c.ok && c.finalMessage !== undefined
182
- stream.publish({
183
- target: { kind: 'broadcast' },
184
- payload: {
185
- kind: 'subagent.completed',
186
- taskId,
187
- subagent: subagentName,
188
- parentSessionId,
189
- ok: c.ok,
190
- durationMs,
191
- ...(c.ok ? {} : { error: c.error }),
192
- ...(hasRecoverableOutput ? { hasRecoverableOutput: true } : {}),
193
- ...(channelKey !== undefined ? { channelKey } : {}),
194
- },
195
- })
196
- }
179
+ // First-writer-wins: if the parent drain already settled this child by
180
+ // timeout, our real completion lost — skip both the overwrite and the
181
+ // broadcast so exactly one canonical completed-event is emitted (the
182
+ // winner's).
183
+ const won = liveRegistry.recordCompletionIfRunning(taskId, completionToFinalShape(c, durationMs))
184
+ if (!won || !stream || !background) return
185
+ const hasRecoverableOutput = !c.ok && c.finalMessage !== undefined
186
+ stream.publish({
187
+ target: { kind: 'broadcast' },
188
+ payload: {
189
+ kind: 'subagent.completed',
190
+ taskId,
191
+ subagent: subagentName,
192
+ parentSessionId,
193
+ ok: c.ok,
194
+ durationMs,
195
+ ...(c.ok ? {} : { error: c.error }),
196
+ ...(hasRecoverableOutput ? { hasRecoverableOutput: true } : {}),
197
+ ...(channelKey !== undefined ? { channelKey } : {}),
198
+ },
199
+ })
197
200
  })
198
201
 
199
202
  if (background) {