typeclaw 0.45.1 → 0.46.1

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 (163) 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 +44 -30
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/multimodal/index.ts +1 -1
  7. package/src/agent/multimodal/look-at.ts +78 -44
  8. package/src/agent/multimodal/looker.ts +161 -39
  9. package/src/agent/network/response-body.ts +26 -0
  10. package/src/agent/network/safe-http.ts +207 -0
  11. package/src/agent/plugin-tools.ts +377 -157
  12. package/src/agent/provider-error.ts +52 -1
  13. package/src/agent/restart/index.ts +61 -40
  14. package/src/agent/restart-handoff/index.ts +73 -4
  15. package/src/agent/reviewer-bash-policy.ts +42 -1
  16. package/src/agent/session-origin.ts +2 -0
  17. package/src/agent/subagent-drain.ts +117 -7
  18. package/src/agent/subagents.ts +49 -16
  19. package/src/agent/throttle-circuit.ts +25 -5
  20. package/src/agent/tool-error-remediation.ts +72 -0
  21. package/src/agent/tool-file-safety.ts +1310 -0
  22. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  23. package/src/agent/tools/ddg.ts +16 -2
  24. package/src/agent/tools/post-github-review.ts +199 -0
  25. package/src/agent/tools/spawn-subagent.ts +21 -18
  26. package/src/agent/tools/webfetch/fetch.ts +163 -183
  27. package/src/agent/tools/webfetch/tool.ts +2 -3
  28. package/src/agent/tools/websearch.ts +23 -2
  29. package/src/agent/tools-without-local-file-operands.ts +30 -0
  30. package/src/agent/turn-runner.ts +86 -6
  31. package/src/bundled-plugins/backup/README.md +23 -10
  32. package/src/bundled-plugins/backup/git-auth.ts +6 -4
  33. package/src/bundled-plugins/backup/index.ts +85 -44
  34. package/src/bundled-plugins/backup/runner.ts +85 -1
  35. package/src/bundled-plugins/doc-render/render.ts +93 -12
  36. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  37. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  38. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  39. package/src/bundled-plugins/github-cli-auth/git-askpass.ts +74 -26
  40. package/src/bundled-plugins/github-cli-auth/git-command.ts +224 -36
  41. package/src/bundled-plugins/github-cli-auth/graphql-auth-nudge.ts +9 -9
  42. package/src/bundled-plugins/github-cli-auth/index.ts +207 -132
  43. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  44. package/src/bundled-plugins/github-cli-auth/token-class.ts +4 -6
  45. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  46. package/src/bundled-plugins/memory/README.md +32 -11
  47. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  48. package/src/bundled-plugins/memory/citations.ts +22 -9
  49. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  50. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  51. package/src/bundled-plugins/memory/index.ts +0 -4
  52. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  53. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  54. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  55. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  56. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  57. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  58. package/src/bundled-plugins/memory/vector/embed-threads.ts +36 -0
  59. package/src/bundled-plugins/memory/vector/embedder.ts +19 -1
  60. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  61. package/src/bundled-plugins/researcher/write-report.ts +8 -5
  62. package/src/bundled-plugins/reviewer/index.ts +2 -2
  63. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  64. package/src/bundled-plugins/reviewer/skills/code-review.ts +19 -9
  65. package/src/bundled-plugins/scout/scout.ts +8 -0
  66. package/src/bundled-plugins/security/index.ts +4 -4
  67. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  68. package/src/bundled-plugins/security/policies/private-surface-read.ts +787 -36
  69. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  70. package/src/bundled-plugins/security/policies/ssrf.ts +147 -42
  71. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  72. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  73. package/src/channels/adapters/discord-bot.ts +66 -6
  74. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  75. package/src/channels/adapters/discord-id.ts +4 -0
  76. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  77. package/src/channels/adapters/discord.ts +57 -7
  78. package/src/channels/adapters/github/auth-app.ts +41 -12
  79. package/src/channels/adapters/github/inbound.ts +11 -0
  80. package/src/channels/adapters/github/index.ts +71 -65
  81. package/src/channels/adapters/github/reconcile-cooldown-store.ts +178 -0
  82. package/src/channels/adapters/github/reconcile-open-prs.ts +31 -0
  83. package/src/channels/adapters/github/review-submitter.ts +302 -0
  84. package/src/channels/adapters/kakaotalk-channel-resolver.ts +5 -3
  85. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  86. package/src/channels/adapters/kakaotalk-typing.ts +17 -15
  87. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  88. package/src/channels/adapters/slack-bot-edit.ts +85 -20
  89. package/src/channels/adapters/slack-bot.ts +26 -10
  90. package/src/channels/adapters/slack-classify.ts +21 -2
  91. package/src/channels/adapters/slack-format.ts +245 -0
  92. package/src/channels/adapters/slack.ts +59 -7
  93. package/src/channels/adapters/telegram-bot.ts +18 -5
  94. package/src/channels/adapters/webex-bot.ts +8 -3
  95. package/src/channels/adapters/webex.ts +8 -3
  96. package/src/channels/fetch-attachment.ts +43 -0
  97. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  98. package/src/channels/github-token-bridge.ts +12 -6
  99. package/src/channels/manager.ts +9 -0
  100. package/src/channels/router.ts +248 -6
  101. package/src/channels/types.ts +28 -1
  102. package/src/cli/channel.ts +1 -1
  103. package/src/cli/init.ts +1 -1
  104. package/src/cli/model.ts +57 -7
  105. package/src/compose/stop.ts +17 -5
  106. package/src/config/config.ts +6 -6
  107. package/src/config/models-mutation.ts +13 -1
  108. package/src/config/providers.ts +176 -0
  109. package/src/container/docker-app.ts +42 -13
  110. package/src/container/start.ts +62 -10
  111. package/src/cron/bridge.ts +9 -2
  112. package/src/doctor/checks.ts +8 -3
  113. package/src/doctor/commit.ts +2 -1
  114. package/src/doctor/file-ownership.ts +52 -0
  115. package/src/dreams/git.ts +2 -1
  116. package/src/git/bound-gc-config.ts +82 -0
  117. package/src/git/hookless.ts +5 -0
  118. package/src/git/reconcile-ignored.ts +18 -5
  119. package/src/git/system-commit.ts +12 -6
  120. package/src/hostd/spawn.ts +133 -47
  121. package/src/init/dockerfile.ts +99 -5
  122. package/src/init/index.ts +17 -5
  123. package/src/init/models-dev.ts +4 -0
  124. package/src/init/validate-api-key.ts +2 -0
  125. package/src/inspect/replay.ts +21 -9
  126. package/src/inspect/session-list.ts +71 -33
  127. package/src/mcp/tools.ts +17 -3
  128. package/src/network/internal-destinations.ts +267 -0
  129. package/src/permissions/builtins.ts +3 -1
  130. package/src/plugin/context.ts +2 -0
  131. package/src/plugin/index.ts +1 -0
  132. package/src/plugin/manager.ts +4 -0
  133. package/src/plugin/types.ts +22 -0
  134. package/src/run/index.ts +40 -0
  135. package/src/run/llm-fetch-observer.ts +41 -4
  136. package/src/sandbox/build.ts +37 -15
  137. package/src/sandbox/canonical-secrets.ts +18 -0
  138. package/src/sandbox/env-exposure.ts +83 -0
  139. package/src/sandbox/errors.ts +13 -6
  140. package/src/sandbox/hidden-paths.ts +102 -44
  141. package/src/sandbox/index.ts +22 -4
  142. package/src/sandbox/package-install.ts +3 -27
  143. package/src/sandbox/policy.ts +16 -28
  144. package/src/sandbox/privileged-runtime.ts +256 -0
  145. package/src/sandbox/session-tmp.ts +8 -2
  146. package/src/sandbox/writable-zones.ts +204 -140
  147. package/src/secrets/index.ts +8 -0
  148. package/src/secrets/refresh-provider-oauth.ts +128 -0
  149. package/src/server/command-runner.ts +48 -4
  150. package/src/server/index.ts +4 -0
  151. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  152. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  153. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  154. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  155. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  156. package/src/skills/typeclaw-config/SKILL.md +27 -11
  157. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  158. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  159. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  160. package/src/skills/typeclaw-permissions/SKILL.md +36 -19
  161. package/src/skills/typeclaw-plugins/SKILL.md +37 -0
  162. package/src/usage/scan.ts +11 -2
  163. package/typeclaw.schema.json +25 -0
@@ -2,6 +2,12 @@ import { createHash } from 'node:crypto'
2
2
 
3
3
  import { loadAllShards, type TopicShard } from '../load-shards'
4
4
  import { buildParentLinks } from '../parent-link'
5
+ import {
6
+ buildProvenanceIndexFrom,
7
+ type MemoryScope,
8
+ type ProvenanceChild,
9
+ type ProvenanceIndex,
10
+ } from '../provenance-index'
5
11
  import { loadAllReferences, type Reference } from '../references/load-references'
6
12
  import {
7
13
  buildMatcher,
@@ -13,7 +19,7 @@ import {
13
19
  type StreamMatch,
14
20
  } from '../search-tool'
15
21
  import type { FragmentProvenance, StreamEvent } from '../stream-events'
16
- import { readAllUndreamedStreamDays, type UndreamedStreamDay } from '../stream-io'
22
+ import { filterUndreamedEvents, readAllStreamDays, type UndreamedStreamDay } from '../stream-io'
17
23
  import { embed, EMBEDDING_MODEL_ID, type EmbedType } from './embedder'
18
24
  import type { Passage } from './passages'
19
25
  import { clearsBaseline, gateRelevance, MARGIN, streamAdmissionBaseline } from './relevance-gate'
@@ -49,9 +55,11 @@ export type HybridSearchResult = {
49
55
  who?: string
50
56
  when?: string
51
57
  where?: FragmentProvenance
58
+ provenance?: ProvenanceChild[]
52
59
  }
53
60
 
54
61
  export type EmbedFn = (texts: string[], type: EmbedType) => Promise<Float32Array[]>
62
+ export type HybridSearchOptions = { scope?: MemoryScope }
55
63
 
56
64
  export async function hybridSearch(
57
65
  query: string,
@@ -59,22 +67,69 @@ export async function hybridSearch(
59
67
  agentDir: string,
60
68
  topK: number,
61
69
  embedFn: EmbedFn = embed,
70
+ options: HybridSearchOptions = {},
62
71
  ): Promise<HybridSearchResult[]> {
63
72
  if (topK <= 0) return []
64
73
 
65
74
  const queryChunks = queryEmbeddingChunks(query)
66
- const [shards, streamDays, references, queryEmbeddings] = await Promise.all([
75
+ const [shards, allStreamDays, references, queryEmbeddings] = await Promise.all([
67
76
  loadAllShards(agentDir),
68
- readAllUndreamedStreamDays(agentDir),
77
+ readAllStreamDays(agentDir),
69
78
  loadAllReferences(agentDir),
70
79
  embedFn(queryChunks, 'query'),
71
80
  ])
72
-
73
- const { parentSlugsByFragmentId, supersededFragmentIds } = buildParentLinks(shards)
74
- const index = buildContentIndex(shards, streamDays, references, supersededFragmentIds)
81
+ const allUndreamedDays: UndreamedStreamDay[] = allStreamDays.flatMap((day) => {
82
+ const events = filterUndreamedEvents(day.events, day.dreamedIds)
83
+ return events.length === 0 ? [] : [{ date: day.date, path: day.path, name: day.name, events }]
84
+ })
85
+ const provenanceIndex = await buildProvenanceIndexFrom(agentDir, shards, allStreamDays)
86
+ const scope = options.scope ?? {}
87
+ const scoped = hasScope(scope)
88
+ const eligibleCitations = new Set(provenanceIndex.undreamedChildren(scope).map((child) => child.citation))
89
+ const streamDays = allUndreamedDays.flatMap((day) => {
90
+ const events = day.events.filter((event) => {
91
+ if (!scoped) return true
92
+ if (event.type !== 'fragment') return false
93
+ return eligibleCitations.has(`streams/${day.date}#${event.id}`)
94
+ })
95
+ return events.length === 0 ? [] : [{ ...day, events }]
96
+ })
97
+ const eligibleShards = shards.filter((shard) => provenanceIndex.topicEligible(shard.slug, scope))
98
+ const eligibleReferences = scoped ? [] : references
99
+
100
+ const { supersededFragmentIds } = buildParentLinks(shards)
101
+ const { parentSlugsByFragmentId } = buildParentLinks(eligibleShards)
102
+ if (scoped) {
103
+ const eligibleFragmentIds = new Set(
104
+ eligibleShards.flatMap((shard) =>
105
+ provenanceIndex.childrenForTopic(shard.slug, scope).flatMap((child) => fragmentIdFromKey(child.citation) ?? []),
106
+ ),
107
+ )
108
+ for (const fragmentId of parentSlugsByFragmentId.keys()) {
109
+ if (!eligibleFragmentIds.has(fragmentId)) parentSlugsByFragmentId.delete(fragmentId)
110
+ }
111
+ }
112
+ const index = buildContentIndex(
113
+ eligibleShards,
114
+ streamDays,
115
+ eligibleReferences,
116
+ supersededFragmentIds,
117
+ provenanceIndex,
118
+ scope,
119
+ )
75
120
  const vectorRows =
76
- queryEmbeddings.length === 0 ? [] : gatedVectorLane(queryEmbeddings, queryChunks, store, topK, index)
77
- const keywordMatches = keywordLane(query, shards, streamDays, references, topK * 2)
121
+ queryEmbeddings.length === 0
122
+ ? []
123
+ : gatedVectorLane(queryEmbeddings, queryChunks, store, topK, index, parentSlugsByFragmentId)
124
+ const keywordMatches = keywordLane(
125
+ query,
126
+ eligibleShards,
127
+ streamDays,
128
+ eligibleReferences,
129
+ topK * 2,
130
+ provenanceIndex,
131
+ scope,
132
+ )
78
133
 
79
134
  return fuseLanes(vectorRows, keywordMatches, index, parentSlugsByFragmentId).slice(0, topK)
80
135
  }
@@ -107,8 +162,11 @@ function gatedVectorLane(
107
162
  store: VectorStore,
108
163
  topK: number,
109
164
  index: Map<string, Omit<HybridSearchResult, 'rrfScore'>>,
165
+ parentSlugsByFragmentId: Map<string, Set<string>>,
110
166
  ): VectorRow[] {
111
- const { scored, winnerChunkByRowId } = maxScoreAcrossChunks(queryEmbeddings, store)
167
+ const allScored = maxScoreAcrossChunks(queryEmbeddings, store)
168
+ const scored = allScored.scored.filter(({ row }) => vectorRowIsAuthorized(row, index, parentSlugsByFragmentId))
169
+ const { winnerChunkByRowId } = allScored
112
170
  const bandDefiningRows = scored.filter(({ row }) => row.source === 'topic' || row.source === 'reference')
113
171
  const streamRows = scored.filter(({ row }) => row.source === 'stream')
114
172
 
@@ -142,6 +200,18 @@ function gatedVectorLane(
142
200
  return [...keptBandDefiningRows, ...keptStreams].sort((a, b) => b.score - a.score).map(({ row }) => row)
143
201
  }
144
202
 
203
+ function vectorRowIsAuthorized(
204
+ row: VectorRow,
205
+ index: Map<string, Omit<HybridSearchResult, 'rrfScore'>>,
206
+ parentSlugsByFragmentId: Map<string, Set<string>>,
207
+ ): boolean {
208
+ if (row.source === 'reference') return index.has(laneKey('reference', referenceSlugFromKey(row.key)))
209
+ if (row.source === 'topic') return index.has(laneKey('topic', row.key))
210
+ if (index.has(laneKey('stream', row.key))) return true
211
+ const fragmentId = fragmentIdFromKey(row.key)
212
+ return fragmentId !== null && (parentSlugsByFragmentId.get(fragmentId)?.size ?? 0) > 0
213
+ }
214
+
145
215
  // The scripts of the HEAD band-defining rows (the gate examines the top of the
146
216
  // score-sorted band to set the knee, so the head is what the query is actually
147
217
  // contrasted against). `bandDefiningRows` is score-sorted descending, so the
@@ -215,10 +285,39 @@ function keywordLane(
215
285
  streamDays: UndreamedStreamDay[],
216
286
  references: Reference[],
217
287
  maxResults: number,
288
+ provenanceIndex: ProvenanceIndex,
289
+ scope: MemoryScope,
218
290
  ): MemorySearchMatch[] {
219
291
  const matcher = buildMatcher(query, false)
220
292
  if (typeof matcher === 'string') return []
221
- const phrase = searchAll(shards, streamDays, matcher, { full: false, maxResults, references })
293
+ const topicDocuments = new Map(
294
+ shards.map((shard) => [
295
+ shard.slug,
296
+ `${shard.slug}\n${shard.frontmatter.heading}\n${shard.body}\n${provenanceIndex.lexicalTextForTopic(shard.slug, scope)}`,
297
+ ]),
298
+ )
299
+ const topicProvenance = new Map(
300
+ shards.map((shard) => [shard.slug, provenanceIndex.childrenForTopic(shard.slug, scope)]),
301
+ )
302
+ const streamDocuments = new Map<string, string>()
303
+ for (const day of streamDays) {
304
+ for (const event of day.events) {
305
+ if (event.type !== 'fragment') continue
306
+ const citation = `streams/${day.date}#${event.id}`
307
+ streamDocuments.set(
308
+ citation,
309
+ `${event.topic}\n${event.body}\n${provenanceIndex.lexicalTextForUndreamed(citation, scope)}`,
310
+ )
311
+ }
312
+ }
313
+ const phrase = searchAll(shards, streamDays, matcher, {
314
+ full: false,
315
+ maxResults,
316
+ references,
317
+ topicDocuments,
318
+ topicProvenance,
319
+ streamDocuments,
320
+ })
222
321
  const phraseMatches = 'matches' in phrase ? phrase.matches : []
223
322
  if (phraseMatches.length > 0) return phraseMatches
224
323
 
@@ -230,6 +329,9 @@ function keywordLane(
230
329
  maxResults,
231
330
  references,
232
331
  tokenMatchMode: 'ascii-boundary',
332
+ topicDocuments,
333
+ topicProvenance,
334
+ streamDocuments,
233
335
  })
234
336
  return 'matches' in ranked ? ranked.matches : []
235
337
  }
@@ -470,21 +572,26 @@ function buildContentIndex(
470
572
  streamDays: UndreamedStreamDay[],
471
573
  references: Reference[],
472
574
  supersededFragmentIds: Set<string>,
575
+ provenanceIndex: ProvenanceIndex,
576
+ scope: MemoryScope,
473
577
  ): Map<string, Omit<HybridSearchResult, 'rrfScore'>> {
474
578
  const index = new Map<string, Omit<HybridSearchResult, 'rrfScore'>>()
579
+ const undreamedByCitation = new Map(provenanceIndex.undreamedChildren(scope).map((child) => [child.citation, child]))
475
580
 
476
581
  for (const shard of shards) {
582
+ const provenance = provenanceIndex.childrenForTopic(shard.slug, scope)
477
583
  index.set(laneKey('topic', shard.slug), {
478
584
  source: 'topic',
479
585
  key: shard.slug,
480
586
  heading: shard.frontmatter.heading,
481
587
  excerpt: excerpt(shard.body, shard.frontmatter.heading),
588
+ ...(provenance.length > 0 ? { provenance } : {}),
482
589
  })
483
590
  }
484
591
 
485
592
  for (const day of streamDays) {
486
593
  for (const event of day.events) {
487
- const item = streamIndexItem(day, event, supersededFragmentIds)
594
+ const item = streamIndexItem(day, event, supersededFragmentIds, undreamedByCitation)
488
595
  if (item !== null) index.set(laneKey('stream', item.key), item)
489
596
  }
490
597
  }
@@ -502,10 +609,15 @@ function buildContentIndex(
502
609
  return index
503
610
  }
504
611
 
612
+ function hasScope(scope: MemoryScope): boolean {
613
+ return scope.workspace !== undefined || scope.chat !== undefined || scope.thread !== undefined
614
+ }
615
+
505
616
  function streamIndexItem(
506
617
  day: UndreamedStreamDay,
507
618
  event: StreamEvent,
508
619
  supersededFragmentIds: Set<string>,
620
+ undreamedByCitation: Map<string, ProvenanceChild>,
509
621
  ): Omit<HybridSearchResult, 'rrfScore'> | null {
510
622
  if (event.type === 'watermark') return null
511
623
  if (event.type === 'fragment') {
@@ -517,8 +629,9 @@ function streamIndexItem(
517
629
  excerpt: excerpt(event.body, event.topic),
518
630
  when: event.ts,
519
631
  }
520
- if (event.who !== undefined) item.who = event.who
521
- if (event.where !== undefined) item.where = event.where
632
+ const child = undreamedByCitation.get(`streams/${day.date}#${event.id}`)
633
+ if (child?.who !== undefined) item.who = child.who
634
+ if (child?.where !== undefined) item.where = child.where
522
635
  return item
523
636
  }
524
637
  return {
@@ -9,6 +9,7 @@ import { defineTool, type Tool, type ToolContext } from '@/plugin'
9
9
  export type WriteReportArgs = { path: string; content: string }
10
10
 
11
11
  const REPORT_BASENAME_RE = /^research-[a-z0-9][a-z0-9-]*\.md$/
12
+ const PROC_FD_PARENT_RE = /^\/proc\/self\/fd\/\d+$/
12
13
 
13
14
  // One report per session. The researcher subagent object — and therefore this
14
15
  // tool instance — is built ONCE by `createResearcherSubagent()` at plugin
@@ -30,8 +31,8 @@ const writtenBySession = new Map<string, true>()
30
31
  // - the parent dir's realpath must equal the real workspace/public dir, which
31
32
  // blocks `workspace -> /agent/.env` style symlink escapes that a lexical
32
33
  // check would follow,
33
- // - the file is created with O_EXCL, so an existing file or a planted
34
- // final-path symlink is rejected rather than clobbered or followed,
34
+ // - the runtime descriptor-anchors the parent, then the file is created with
35
+ // O_EXCL, so an existing file or planted final-path symlink is rejected,
35
36
  // - a second write in the same session is rejected (one report per spawn),
36
37
  // - the schema is strict, so an `acknowledgeGuards` field is rejected, not
37
38
  // silently stripped.
@@ -51,6 +52,7 @@ Write to \`public/\` instead of \`workspace/\` when your resolved role lacks \`f
51
52
  .describe('Absolute path: <agent>/workspace/research-<slug>.md or <agent>/public/research-<slug>.md'),
52
53
  content: z.string().describe('The full markdown report body.'),
53
54
  }),
55
+ fileOperands: { create: ['path'] },
54
56
  async execute(args: WriteReportArgs, ctx: ToolContext) {
55
57
  if (writtenBySession.has(ctx.sessionId)) {
56
58
  throw new Error('A report has already been written for this session. You may write exactly one report.')
@@ -63,15 +65,16 @@ Write to \`public/\` instead of \`workspace/\` when your resolved role lacks \`f
63
65
 
64
66
  const parent = path.dirname(target)
65
67
  const base = path.basename(target)
68
+ const lexicalParent = PROC_FD_PARENT_RE.test(parent) ? await realpath(parent) : parent
66
69
 
67
70
  if (!REPORT_BASENAME_RE.test(base)) {
68
71
  throw new Error(
69
72
  `Report filename must match research-<slug>.md (lowercase slug), got: ${base}. Path: ${target}.`,
70
73
  )
71
74
  }
72
- if (parent !== workspaceDir && parent !== publicDir) {
75
+ if (lexicalParent !== workspaceDir && lexicalParent !== publicDir) {
73
76
  throw new Error(
74
- `Report must be written directly under ${workspaceDir} or ${publicDir} (no subdirectories), got parent: ${parent}.`,
77
+ `Report must be written directly under ${workspaceDir} or ${publicDir} (no subdirectories), got parent: ${lexicalParent}.`,
75
78
  )
76
79
  }
77
80
 
@@ -80,7 +83,7 @@ Write to \`public/\` instead of \`workspace/\` when your resolved role lacks \`f
80
83
  // `realpath('<agent>/public')` throws ENOENT on agents that never made it,
81
84
  // which would reject every valid write to `workspace/`. The symlink-escape
82
85
  // defense is unchanged — the parent actually written to is still canonicalized.
83
- const canonicalDir = parent === workspaceDir ? workspaceDir : publicDir
86
+ const canonicalDir = lexicalParent === workspaceDir ? workspaceDir : publicDir
84
87
  const [realParent, realCanonical] = await Promise.all([realpath(parent), realpath(canonicalDir)])
85
88
  if (realParent !== realCanonical) {
86
89
  throw new Error(`Report parent directory resolves outside the allowed report directories: ${parent}.`)
@@ -3,9 +3,9 @@ import { definePlugin } from '@/plugin'
3
3
  import { createReviewerSubagent } from './reviewer'
4
4
 
5
5
  export default definePlugin({
6
- plugin: async () => ({
6
+ plugin: async (ctx) => ({
7
7
  subagents: {
8
- reviewer: createReviewerSubagent(),
8
+ reviewer: createReviewerSubagent({ resolveTokenForRepo: ctx.github.resolveTokenForRepo }),
9
9
  },
10
10
  }),
11
11
  })
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod'
2
2
 
3
+ import { createReviewerCheckoutTool } from '@/bundled-plugins/github-cli-auth/review-checkout'
4
+ import type { ResolveGithubTokenForRepo } from '@/channels/github-token-bridge'
3
5
  import {
4
6
  bashTool,
5
7
  createLoadSkillTool,
@@ -129,7 +131,7 @@ These rules apply to every review regardless of domain.
129
131
 
130
132
  1. **Form findings, not opinions.** Each finding is one issue. State severity (\`blocker\` / \`concern\` / \`nit\` / \`praise\`). Cite specific evidence — a file:line, a diff hunk, a quoted passage. Suggest a concrete alternative.
131
133
  2. **Evidence is mandatory.** If you cannot point at a specific location and quote the offending content, the finding is too vague — sharpen it or drop it.
132
- 3. **Verify external claims.** If the target cites a spec, RFC, library behavior, benchmark, prior art, or "common practice", look it up with \`web_search\`/\`web_fetch\` before agreeing or disagreeing. Cite the source in the finding.
134
+ 3. **Verify external claims — but do not loop on it.** If the target cites a spec, RFC, library behavior, benchmark, prior art, or "common practice", look it up with \`web_search\`/\`web_fetch\` and cite the source in the finding. This is bounded, not unconditional: web verification is a *supporting* step for a finding you can already reason about, never a prerequisite that blocks the review. Give any single claim **at most two or three** \`web_search\`/\`web_fetch\` attempts. If the web is blocked, rate-limited, or returns CAPTCHA / 403 / 404 / junk (as it often will), **stop searching and fall back to your own reasoning**: state the finding from the evidence you already have and mark the external claim as unverified — e.g. \`concern\` … "(could not confirm via web; based on documented \`COUNTIFS\` blank-cell semantics)". A finding you can justify from the target itself does not need web confirmation to ship. Never spend a chain of failing searches chasing a detail you could assert, qualify, or drop — a stalled reviewer that never emits its \`<review>\` block is worse than a review that flags a claim as unverified. If a claim is *load-bearing* and you genuinely cannot resolve it, raise it as a \`concern\` asking the author to confirm, and move on.
133
135
  4. **One finding, one concern.** Do not bundle unrelated issues into a single finding. The parent parses findings; mixed-concern findings break that.
134
136
  5. **Praise is rare.** Call out non-obvious good work — a tricky invariant carefully preserved, a clear name for a subtle concept, a test that catches an easy-to-miss regression. Do not pad reviews with positivity.
135
137
  6. **No generic LLM review noise.** "Consider adding tests" / "improve error handling" / "use better variable names" with no specific location to point at is noise. If you cannot point at a line, do not raise the finding.
@@ -188,7 +190,9 @@ export const reviewerPayloadSchema = z
188
190
 
189
191
  export type ReviewerPayload = z.infer<typeof reviewerPayloadSchema>
190
192
 
191
- export function createReviewerSubagent(): Subagent<ReviewerPayload> {
193
+ export function createReviewerSubagent(options?: {
194
+ resolveTokenForRepo: ResolveGithubTokenForRepo
195
+ }): Subagent<ReviewerPayload> {
192
196
  const loadSkillTool = createLoadSkillTool({
193
197
  skills: REVIEWER_SKILLS,
194
198
  description: `Load a curated review skill by name. Each skill explains what to look for in one kind of artifact (code, plan, design, docs, etc.) and refines the universal severity scale for that domain. Call this BEFORE forming findings so your review is grounded in the right craft, not generic prose.
@@ -210,7 +214,10 @@ If none of the listed skills fit the target, load \`general\`. Keep the skill-se
210
214
  // two layers; this is the one that survives a trusted/owner caller.
211
215
  bashPolicy: { kind: 'readonly-reviewer' },
212
216
  tools: [readTool, grepTool, findTool, lsTool, bashTool, webSearchTool, webFetchTool],
213
- customTools: [loadSkillTool],
217
+ customTools: [
218
+ loadSkillTool,
219
+ ...(options === undefined ? [] : [createReviewerCheckoutTool(options.resolveTokenForRepo)]),
220
+ ],
214
221
  payloadSchema: reviewerPayloadSchema,
215
222
  visibility: 'public',
216
223
  rosterDescription:
@@ -35,22 +35,29 @@ gh api "/repos/<owner>/<repo>/contents/<path>?ref=<headSha>" -H "Accept: applica
35
35
 
36
36
  That returns the file's raw bytes (no base64, no second stage). For the line numbers your \`location="path:line"\` anchors need, read them off the unified diff you already fetched (\`gh pr diff\` prints the new-side line numbers in its hunk headers, \`@@ -a,b +c,d @@\`), or escalate to Mode 2 where a real \`read\`/\`grep\` gives native line numbers. Fetch each file once and keep its output — do not re-fetch the same file to re-derive a line you already saw.
37
37
 
38
- **Mode 2 — scratch checkout (escalate when navigation gets broad).** When the review needs repo-wide \`grep\`, symbol tracing across several directories, many adjacent files, or repeated access to the same files, the remote-read dance is slower and more error-prone than a real checkout. In that case clone the PR head into a **fresh throwaway directory under \`/tmp\`** and read it natively:
38
+ **Mode 2 — scratch checkout (escalate when navigation gets broad).** When navigation gets broad, call \`github_prepare_review_checkout({ repoSlug: "<owner>/<repo>", headSha: "<40-char headSha>" })\`. The runtime verifies that exact SHA in the one allowlisted repository and performs the authenticated fetch without exposing its token to model bash.
39
39
 
40
- \`\`\`sh
41
- git clone --depth 1 "https://github.com/<owner>/<repo>.git" /tmp/review-<n>-src && \
42
- git -C /tmp/review-<n>-src fetch --depth 1 origin <headSha> && git -C /tmp/review-<n>-src checkout <headSha>
43
- \`\`\`
44
-
45
- Then \`read\`, \`grep\`, \`find\`, and read-only \`git\` (\`git -C /tmp/review-<n>-src log|diff|show|blame|grep|ls-files|cat-file\`) all work against \`/tmp/review-<n>-src\` with correct line numbers and zero per-file round-trips.
40
+ Then use the receipt path with \`read\`, \`grep\`, \`find\`, and read-only \`git\` (\`git -C <receipt-path> log|diff|show|blame|grep|ls-files|cat-file\`) for correct line numbers and zero per-file round-trips. Do not use \`git clone\`, \`git fetch\`, \`git checkout\`, or \`gh pr checkout\` for acquisition.
46
41
 
47
42
  This \`/tmp\` scratch checkout is the **one** write the read-only contract permits — and only because it is a private acquisition cache, never the reviewed artifact. Inside it you may only **read**. You still may NOT: edit any file, install dependencies, run builds or tests, commit/stage/push/rebase/reset, or write anywhere outside this \`/tmp\` scratch dir. Do not \`rm\` it when done — leave cleanup to the session lifecycle (\`rm\` stays forbidden). When in doubt about how many files you'll touch, start with Mode 1 and escalate to Mode 2 only once the file count or grep breadth justifies the clone.
48
43
 
44
+ ## Bound your external verification — never loop
45
+
46
+ A code review's evidence is the **diff and the surrounding code**, which you already have. \`web_search\`/\`web_fetch\` are a supporting layer for external facts (a spec's exact wording, a library's documented behavior, a CVE), not a gate the review must pass through. The public web frequently blocks automated fetches — CAPTCHA, rate-limit, 403/404, or scraped-search junk — and chasing a single detail through a chain of failing searches is the classic way a review stalls and **never emits its \`<review>\` block**. That silent non-answer is the worst outcome; a review that ships with a claim flagged "unverified" is strictly better.
47
+
48
+ So, for any one external claim:
49
+
50
+ - **Cap it at two or three fetches.** If they fail or come back useless, **stop** — do not reformulate the query five more ways or pivot to a different search engine's scrape page.
51
+ - **Fall back to reasoning from the artifact.** Most findings do not need the web at all. Excel/spreadsheet formula semantics, standard-library behavior, language quirks — reason from what the code does and what you know, and state the finding. Anchor it to the line; qualify the external half if you couldn't confirm it: *"…(could not verify via web; based on documented \`COUNTIFS\` treating a blank cell as \`0\`, which \`"<="&date\` then counts)"*.
52
+ - **A blocked lookup downgrades confidence, it does not block the finding.** If the claim is load-bearing and genuinely unresolvable, raise it as a \`concern\` that asks the author to confirm — then move on to the next finding. Do not let one unresolved external detail hold the whole verdict hostage.
53
+
54
+ The bar is a shipped \`<review>\` block, not a fully web-sourced one.
55
+
49
56
  ## How to build context
50
57
 
51
58
  A finding without context is noise. Before forming findings:
52
59
 
53
- 1. **Read the change description.** PR body, commit messages, linked issues. The author told you what they intended — verify the code matches.
60
+ 1. **Read the change description and establish the author's intent baseline.** PR body, commit messages, linked issues. The author told you what they intended — verify the code matches. Separate out the four things you will hold the review to across every later push: the outcome they set out to deliver, the explicit in/out-of-scope boundary they drew, the constraints they accepted, and the approach they deliberately chose. This baseline is the frame your findings must serve — verify the code fulfills it; do not silently swap in the feature, abstraction, or design *you* would have built. When these sources conflict, are too vague to fix the intended scope, or no longer match the diff, raise that as a scope/record gap (see "Review the PR title and body as an artifact") — do not resolve it by inventing a new goal for the PR.
54
61
  2. **Read adjacent code.** A change to one function means reading callers and callees. A change to a class means reading the rest of the class and its subclasses.
55
62
  3. **Read the project's conventions.** \`AGENTS.md\`, \`CONTRIBUTING.md\`, \`CLAUDE.md\`, \`README.md\`, the test layout, the linter config. Deviation from established convention is a finding worth raising; following convention is not worth praising.
56
63
  4. **Read the tests.** Existing tests show what the project considers important to verify. New tests show what the author considers important to lock in. The gap between them is often where the bugs hide.
@@ -80,7 +87,7 @@ Keep the anti-noise line from below firmly in view: **do not confuse restating t
80
87
  Prioritize in this order:
81
88
 
82
89
  1. **Correctness.** Does the change do what its description claims? Off-by-one errors, missing null/undefined handling, race conditions, incorrect error propagation, broken invariants.
83
- 2. **Security.** Injection vectors (SQL, shell, HTML), missing authz/authn checks, secret leakage in logs or error messages, unsafe deserialization, SSRF, path traversal, time-of-check-time-of-use. Cite OWASP / CWE / RFC by number when relevant; verify with \`web_search\` or \`web_fetch\` before asserting.
90
+ 2. **Security.** Injection vectors (SQL, shell, HTML), missing authz/authn checks, secret leakage in logs or error messages, unsafe deserialization, SSRF, path traversal, time-of-check-time-of-use. Cite OWASP / CWE / RFC by number when relevant; verify with \`web_search\` or \`web_fetch\` when it strengthens the finding — but keep it bounded (see below).
84
91
  3. **Architecture fit and intent drift.** Does the change respect existing layering? Does it introduce a new dependency where the existing pattern would have worked? Does it duplicate logic that already exists elsewhere in the repo? Beyond local fit, check for **intent drift** — the change technically compiles and passes its own tests, but quietly diverges from the design intent the surrounding code was built on: a "temporary" branch that bypasses an established abstraction, a special-case that erodes an invariant the module exists to protect, a layer reaching past its boundary because that was the shortest path. The diff can be locally correct and still pull the system away from the shape the author (or the codebase's own conventions) intended. When the description states an intent — "without changing the public API", "purely a refactor", "no behavior change" — verify the diff actually holds that line; a refactor that alters observable behavior, or an "internal only" change that shifts an exported contract, is drift even if nothing is strictly broken. Anchor the finding to the line where the divergence enters and name the intent it violates.
85
92
  4. **Regression risk and blast radius.** A change is rarely self-contained. For every function signature, return shape, exported type, default value, thrown-error type, or side-effecting behavior the diff alters, ask **who depended on the old behavior**. \`grep\` for callers of changed exports; trace the call sites that touch a modified invariant. A contract change that is correct *here* can silently break a caller the diff never shows — that caller is the regression, and it will not appear in the test count for this PR. Removed or loosened validation, a narrowed accepted-input range, a changed enum value, an altered ordering guarantee, a default that flipped: each is a regression vector for existing consumers even when the new code reads fine in isolation. State the blast radius explicitly — which call sites, which inputs, which downstream behavior changes — so the author knows whether this is a \`concern\` or a \`blocker\`. "Looks fine in the diff" is not a regression clearance; the diff is exactly where regressions hide their other half.
86
93
  5. **Side effects and ripple.** Watch for effects that reach outside the lines being changed: mutation of shared or global state, a cache that now needs invalidating, an event/log/metric whose shape downstream consumers parse, a config or feature flag whose new value changes behavior elsewhere, a migration that must run in lockstep, a resource (file handle, connection, lock, subscription) opened on a new path and never released. The dangerous side effect is the one whose *consequence* isn't obvious from the changed line alone — a behavior that emerges from the interaction between the changed code and code it touches indirectly. There is still a line that introduces it: anchor the finding to the mutation, lifecycle, or config line where the ripple enters, then name the downstream consumer or shared state that breaks and say what goes wrong when it is not accounted for. If the change touches a shared resource's lifecycle, verify the cleanup path (\`finally\`, \`defer\`, \`using\`, teardown hook) covers the new branch too — a leak introduced on an error path is a side effect that only shows up under load.
@@ -99,6 +106,7 @@ Prioritize in this order:
99
106
  - **Restating the code.** "This function reads the file and returns its contents" is not a finding.
100
107
  - **Restating the change description.** Summarizing what the PR does back to its author — "this PR adds caching to the user lookup" — is not a review. They wrote the description; they know. (This forbids *echoing* the body, not *reviewing* it: judging whether the body records the why, matches the diff, and separates its meaning units is in scope — see "Review the PR title and body as an artifact". The line is echo vs. evaluate.)
101
108
  - **Already-acknowledged gaps.** A weakness the author already flagged with a \`TODO\`/\`FIXME\` in the diff, or named in the PR body as out of scope, is not a finding — they're already aware. Only raise it if you have new information: the gap is worse than they think, or it's a blocker they've mislabeled as deferrable. Say which.
109
+ - **Reviewer-imposed scope drift.** Anchor every finding to the author's intent baseline — the outcome, scope boundary, constraints, and chosen approach you established from the PR body, commits, and linked context. The question here is not "did the author's code drift?" (that is Architecture-fit intent drift, above) but "would my *requested change* drift this PR away from what the author set out to do?" Turning "I would have built this differently" into a review requirement — demanding a broader abstraction, a more general feature, an adjacent cleanup, an architecture that is merely *your preference* rather than the surrounding codebase's documented or observable design, or support for use cases this PR never undertook — is **reviewer-imposed scope drift** whenever the submitted approach can correctly deliver the author's stated outcome. Before raising a finding, ask: *if the author does nothing about this, does the PR fail its stated goal, violate an existing contract or invariant, introduce a concrete correctness/security/regression risk, deviate from the codebase's established layering, dependency placement, or settled conventions in a way that will compound, or leave a real scope/record gap?* If none of those, drop it — or surface it once as an explicitly optional suggestion, never as a condition of approval. This is the line the rule draws: an evidence-backed deviation from the codebase's *own* established architecture, layering boundaries, duplication of existing logic, or documented conventions — the ones "Architecture fit and intent drift" already tells you to catch — stays a legitimate finding even before it produces one of the other concrete defects, because "will compound" IS the harm; only redesign toward an architecture the codebase doesn't itself call for is the drift this rule forbids. The author's intent bounds what you may **demand**; it does not redefine **correctness**: a real bug, vulnerability, regression, or broken invariant inside the chosen scope is always fair game even when fixing it was never part of the author's plan, and a stated scope boundary may still be challenged when you can show it makes the promised outcome unsafe, incorrect, or materially misleading (that is ONE finding challenging the boundary with a concrete trigger — see the best-effort rule below). Prefer the smallest fix that restores correctness while keeping the author's approach intact; require a redesign only when the approach *itself* causes the demonstrated defect and no bounded correction resolves it.
102
110
  - **Disproportionate theoretical corners on best-effort code.** Weigh every finding by \`(realistic probability of the input) × (cost of the bad outcome)\` against the cost of the fix. When the code is explicitly a **best-effort heuristic, approximation, or partial parser** — and says so, in a comment or the PR body, with a stated scope boundary — an edge case that lies OUTSIDE that boundary and cannot arise from realistic inputs is not a finding; it is scope the author already priced in. A guard that "should ideally handle every case in spec X" is being measured against the wrong bar: the bar is *the failure mode that actually occurs in this system's traffic*, not spec-completeness. Before raising such a corner, ask: can you construct a REALISTIC input (not a synthetic worst case) that triggers it, and is the bad outcome worse than the complexity the fix adds? If either answer is no, drop it — or, at most, note the boundary once and move on. Do NOT walk a partial implementation through progressively deeper theoretical inputs across re-reviews; a heuristic that is sound for real inputs and honest about its documented limits is DONE, and demanding it grow into a full parser to satisfy spec-completeness is exactly the noise this rule forbids. If you genuinely believe the stated scope boundary is wrong, that is ONE finding challenging the boundary itself (with a realistic triggering input as evidence) — not a standing series of ever-deeper corner reports.
103
111
 
104
112
  ## Severity hints specific to code
@@ -127,6 +135,8 @@ This includes payloads where the parent says the author **addressed your prior b
127
135
 
128
136
  A re-review is a decision, not a fresh hunt for something new to block on. If the author resolved your prior blockers, the default outcome is \`approve\` — do not manufacture a new \`request-changes\` by escalating into a deeper theoretical corner of the same best-effort code you already accepted the shape of. A "new blocker" on re-review must clear the same bar as any blocker: a realistic input triggers it and the impact justifies the fix. A strictly-deeper variant of an already-addressed edge case, on code that documents its scope boundary, is not a new blocker — it is the "disproportionate theoretical corners" noise the What-NOT-to-find rule forbids, and repeating it across pushes is how a re-review loop fails to converge. When the fix satisfies the boundary and the remaining corners are out of scope by design, say so in the \`<summary>\` and \`approve\`.
129
137
 
138
+ Weigh the *cumulative direction* of the review against the author's intent baseline, not just this push's diff. Several individually reasonable requests can add up to a different project than the one submitted — a narrow fix grows into a framework, a targeted parser is pushed toward a complete implementation, the author's chosen design is displaced layer by layer with the reviewer's. **You are a fresh session with no memory of your own prior rounds**, so do not assume you can recall "your earlier feedback" — you must reconstruct it. Two sources give you that history: the spawn payload names the prior blockers that made this a re-review, and the PR's own review timeline is readable — \`gh api --paginate --slurp /repos/<owner>/<repo>/pulls/<n>/reviews\`, \`gh api --paginate /repos/<owner>/<repo>/pulls/<n>/comments\` (inline threads), and \`gh api --paginate /repos/<owner>/<repo>/issues/<n>/comments\` (top-level comments) return the earlier reviews and comments, the bot's prior rounds included. **\`--paginate\` is mandatory here**: GitHub returns these collections 30 per page, so an earlier round on a long-lived PR sits past page one — read it unpaginated and you silently truncate exactly the history this check needs, misattributing or missing the cumulative drift (the same reason \`typeclaw-channel-github\`'s re-review query paginates). Read the full timeline before judging cumulative drift; attributing a change to "reviewer overreach" without having read the review that requested it is a guess, not a finding. **When that history is genuinely unavailable** (no payload blockers, review timeline unreachable), do NOT invent a narrative about who pushed what — fall back to the anchorable comparison you always have: does the *current cumulative diff* still serve the recorded intent baseline, or has it grown past the stated scope? Judge the head against the baseline, not against a reconstructed sequence you can't see. Either way, each round ask whether the current head is moving *closer to the outcome the author originally stated* or merely *deeper into scope the review introduced*; if a prior round crossed that line, stop extending it — the author complying with an earlier suggestion is not license to demand the next layer of a preferred design. Re-anchor to the stated goal and the real correctness/security/contract obligations, name the overreach in the \`<summary>\` when the history supports it, and \`approve\` once the legitimate blockers are resolved. (If the author has *deliberately* changed direction mid-PR, that new intent governs — but the body should record the shift; mere compliance under review pressure is not an intentional scope change.)
139
+
130
140
  **Account for resolved threads in the \`<summary>\`, not as \`praise\` findings.** A re-review tempts you to emit one \`praise\` finding per prior concern the author fixed — "Thread 123 is addressed", "Thread 456 is addressed". Do **not**. \`praise\` is reserved for *non-obvious good work*, and a routine "you fixed what I asked" is neither non-obvious nor a finding the parent should post inline (it strips \`praise\` from inline comments anyway, so these become dead weight). Instead, state the resolution accounting in one sentence in your \`<summary>\` — e.g. "Both prior blockers (the unfenced table scan and the backtick-wrap span) are resolved at head \`<sha>\`; one new concern below." Reserve actual \`<finding>\` entries for what still needs action: a prior blocker that is **only partially** fixed (\`blocker\`/\`concern\`, anchored to the line that's still wrong), a **regression the fix introduced** (\`blocker\`/\`concern\`), or a genuinely non-obvious fix worth a rare \`praise\`. A clean re-review where everything was addressed is an \`approve\` whose \`<summary>\` says so and whose \`<findings>\` is empty — not a wall of \`praise\` receipts.
131
141
  - **Do NOT return \`comment\` on a re-review.** \`comment\` is for ambiguous partial reviews with no accept/reject signal; a re-review is the opposite — it is precisely an accept/reject decision. A \`comment\` verdict here leaves the PR's \`REQUEST_CHANGES\` state stuck (a plain comment does not clear it on GitHub), which is the exact failure a re-review exists to resolve. The only escape hatch is the same one that always applies: if you genuinely cannot reach the diff or the prior context, return one \`blocker\` finding stating what you need and a \`comment\` verdict — but a reachable, reviewable re-review must end in \`approve\` or \`request-changes\`.
132
142
 
@@ -83,10 +83,18 @@ export const scoutPayloadSchema = z
83
83
 
84
84
  export type ScoutPayload = z.infer<typeof scoutPayloadSchema>
85
85
 
86
+ // Ceiling for a wedged scout run. `startSubagent`'s timeout guard only engages
87
+ // when `timeoutMs` is set, so without this a scout whose `session.prompt` never
88
+ // settles (e.g. the model looping on a transient network error) blocks its
89
+ // parent — the researcher especially — forever. 5 min is generous headroom over
90
+ // the normal seconds-to-low-minutes path while still bounding the hang.
91
+ export const SCOUT_TIMEOUT_MS = 300_000
92
+
86
93
  export function createScoutSubagent(): Subagent<ScoutPayload> {
87
94
  return {
88
95
  systemPrompt: SCOUT_SYSTEM_PROMPT,
89
96
  profile: 'fast',
97
+ timeoutMs: SCOUT_TIMEOUT_MS,
90
98
  tools: [webSearchTool, webFetchTool],
91
99
  payloadSchema: scoutPayloadSchema,
92
100
  visibility: 'public',
@@ -201,15 +201,15 @@ export default definePlugin({
201
201
  SECURITY_PERMISSIONS.bypassSecretExfilRead,
202
202
  GUARD_SECRET_EXFIL_READ_SEVERITY,
203
203
  ),
204
- // Role-derived, not severity-bypassed: resolveHiddenPaths already
205
- // returns an empty deny-list for roles that may see the surface, so
206
- // there is no canBypass wrapper. Mirrors the bash sandbox masks onto
207
- // the non-bash read/grep/find/ls/edit/write builtins.
204
+ // Not severity-bypassed: private directories remain role-derived,
205
+ // while canonical credential-store denial is unconditional. Mirrors
206
+ // the bash masks onto every non-bash path-bearing tool.
208
207
  checkPrivateSurfaceReadGuard({
209
208
  tool: event.tool,
210
209
  args: event.args,
211
210
  agentDir: ctx.agentDir,
212
211
  hidden: resolveHiddenPaths(ctx.permissions, event.origin, ctx.agentDir),
212
+ ...(event.fileOperands !== undefined ? { fileOperands: event.fileOperands } : {}),
213
213
  }),
214
214
  canBypass(GUARD_SSRF_SEVERITY, SECURITY_PERMISSIONS.bypassSsrf)
215
215
  ? undefined
@@ -56,6 +56,7 @@ const PROCESS_ENV_TARGETS: ReadonlyArray<string> = [
56
56
  'ANTHROPIC_API_KEY',
57
57
  'MINIMAX_API_KEY',
58
58
  'DEEPSEEK_API_KEY',
59
+ 'UPSTAGE_API_KEY',
59
60
  'MOONSHOT_API_KEY',
60
61
  'MOONSHOT_CODING_API_KEY',
61
62
  'GOOGLE_API_KEY',