typeclaw 0.29.0 → 0.30.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 (35) hide show
  1. package/package.json +1 -1
  2. package/scripts/verify-realproc-sandbox.sh +58 -0
  3. package/src/agent/index.ts +6 -0
  4. package/src/agent/live-subagents.ts +5 -0
  5. package/src/agent/plugin-tools.ts +79 -10
  6. package/src/agent/subagent-drain.ts +150 -0
  7. package/src/agent/subagents.ts +34 -3
  8. package/src/agent/system-prompt.ts +1 -1
  9. package/src/agent/tools/spawn-subagent.ts +13 -1
  10. package/src/bundled-plugins/bun-hygiene/README.md +12 -11
  11. package/src/bundled-plugins/bun-hygiene/policy.ts +8 -3
  12. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +116 -35
  13. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +14 -9
  14. package/src/bundled-plugins/github-cli-auth/index.ts +3 -3
  15. package/src/bundled-plugins/planner/planner.ts +2 -1
  16. package/src/bundled-plugins/researcher/researcher.ts +9 -2
  17. package/src/bundled-plugins/reviewer/reviewer.ts +2 -1
  18. package/src/channels/adapters/discord-bot-format.ts +191 -0
  19. package/src/channels/adapters/discord-bot.ts +2 -1
  20. package/src/channels/adapters/github/inbound.ts +88 -30
  21. package/src/channels/adapters/github/review-state.ts +27 -0
  22. package/src/channels/github-review-claim.ts +15 -3
  23. package/src/channels/outbound-flood-filter.ts +70 -3
  24. package/src/channels/router.ts +53 -0
  25. package/src/compose/discover.ts +5 -1
  26. package/src/config/config.ts +38 -0
  27. package/src/container/start.ts +14 -0
  28. package/src/migrations/index.ts +35 -0
  29. package/src/migrations/secrets-v1-to-v2.ts +344 -0
  30. package/src/run/index.ts +13 -0
  31. package/src/sandbox/availability.ts +12 -0
  32. package/src/sandbox/build.ts +53 -9
  33. package/src/sandbox/index.ts +1 -1
  34. package/src/sandbox/policy.ts +17 -1
  35. package/typeclaw.schema.json +24 -0
@@ -9,6 +9,7 @@ import { removeRequestedReviewer } from './decoy-reviewer'
9
9
  import type { DeliveryDedup } from './dedup'
10
10
  import { isGithubEventAllowed } from './event-allowlist'
11
11
  import { encodeGithubReactionRef, type GithubReactionTarget } from './reactions'
12
+ import { fetchSelfReviewBlocking } from './review-state'
12
13
  import { listUnresolvedSelfReviewThreads } from './review-thread-resolver'
13
14
 
14
15
  export type GithubInboundLogger = { info: (m: string) => void; warn: (m: string) => void; error: (m: string) => void }
@@ -83,14 +84,16 @@ export function createGithubWebhookHandler(options: GithubWebhookHandlerOptions)
83
84
  }
84
85
 
85
86
  // A push to an open PR (`synchronize`) is not a message to react to — it is
86
- // a trigger to re-check whether the new commits addressed the bot's own
87
- // still-open review threads. The check needs a GraphQL round-trip, so it
88
- // runs OFF the ACK path (like the decoy-reviewer drop) and only wakes a
89
- // session when there is at least one such thread. Returning here also keeps
87
+ // a trigger to re-evaluate the bot's own outstanding review obligations on
88
+ // this PR: unresolved review threads it authored AND a sticky
89
+ // CHANGES_REQUESTED block (which leaves no threads when filed as a top-level
90
+ // verdict the black hole this path closes). Both need an API round-trip,
91
+ // so it runs OFF the ACK path (like the decoy-reviewer drop) and only wakes a
92
+ // session when an obligation is outstanding. Returning here also keeps
90
93
  // synchronize out of the generic awareness-only fallthrough below.
91
94
  if (event === 'pull_request' && action === 'synchronize') {
92
95
  if (delivery !== '') options.dedup.add(delivery)
93
- scheduleReviewThreadRecheck({ payload, selfLogin, options })
96
+ scheduleReviewFollowup({ payload, selfLogin, options })
94
97
  return ok()
95
98
  }
96
99
 
@@ -187,7 +190,7 @@ function defaultScheduleBackgroundTask(task: () => Promise<void>): void {
187
190
  void task().catch(() => {})
188
191
  }
189
192
 
190
- function scheduleReviewThreadRecheck(input: {
193
+ function scheduleReviewFollowup(input: {
191
194
  payload: Record<string, unknown>
192
195
  selfLogin: string | null
193
196
  options: GithubWebhookHandlerOptions
@@ -203,13 +206,27 @@ function scheduleReviewThreadRecheck(input: {
203
206
  if (repository === null || pullNumber === null) return
204
207
  const headSha = readString(readRecord(pr?.head), 'sha')
205
208
 
209
+ // Same webhook head SHA can arrive on several deliveries (a multi-commit push
210
+ // emits one synchronize per ref update). Dedup the follow-up on the head SHA
211
+ // so a single push wakes at most one re-review, distinct from the per-delivery
212
+ // dedup above. When headSha is absent we cannot dedup, so we skip the followup
213
+ // rather than risk a re-review storm.
214
+ if (headSha === null) {
215
+ options.logger.warn(`[github] synchronize for ${repository.owner}/${repository.name}#${pullNumber} has no head sha`)
216
+ return
217
+ }
218
+ const followupKey = `synchronize-followup:${repository.owner}/${repository.name}#${pullNumber}:${headSha}`
219
+ if (options.dedup.has(followupKey)) return
220
+ options.dedup.add(followupKey)
221
+
222
+ const reviewOn = options.reviewOn?.() ?? 'review_requested'
206
223
  const fetchImpl = options.fetchImpl ?? fetch
207
224
  const schedule = options.scheduleBackgroundTask ?? defaultScheduleBackgroundTask
208
225
  const target = `${repository.owner}/${repository.name}#${pullNumber}`
209
226
  schedule(async () => {
210
227
  try {
211
228
  const token = await authToken({ repoSlug: `${repository.owner}/${repository.name}` })
212
- const result = await listUnresolvedSelfReviewThreads({
229
+ const threads = await listUnresolvedSelfReviewThreads({
213
230
  token,
214
231
  selfLogin,
215
232
  owner: repository.owner,
@@ -217,46 +234,63 @@ function scheduleReviewThreadRecheck(input: {
217
234
  prNumber: pullNumber,
218
235
  fetchImpl,
219
236
  })
220
- if (!result.ok) {
221
- options.logger.warn(`[github] review-thread recheck failed for ${target}: ${result.error}`)
237
+ if (!threads.ok) {
238
+ options.logger.warn(`[github] review-thread recheck failed for ${target}: ${threads.error}`)
222
239
  return
223
240
  }
224
- if (result.threads.length === 0) return
241
+
242
+ // A held CHANGES_REQUESTED is the bot's own obligation regardless of how
243
+ // reviews are triggered, so re-evaluate it on push unless review is off.
244
+ let selfBlocking = false
245
+ if (reviewOn !== 'off') {
246
+ const blocking = await fetchSelfReviewBlocking({
247
+ token,
248
+ selfLogin,
249
+ owner: repository.owner,
250
+ repo: repository.name,
251
+ prNumber: pullNumber,
252
+ fetchImpl,
253
+ })
254
+ if (blocking.ok) selfBlocking = blocking.selfBlocking
255
+ else options.logger.warn(`[github] review-state recheck failed for ${target}: ${blocking.error}`)
256
+ }
257
+
258
+ const rootCommentIds = threads.threads.map((t) => t.rootCommentId)
259
+ if (rootCommentIds.length === 0 && !selfBlocking) return
225
260
  options.route(
226
- buildRecheckInbound({
227
- repository,
228
- pullNumber,
229
- headSha,
230
- rootCommentIds: result.threads.map((t) => t.rootCommentId),
231
- title: readString(pr, 'title'),
232
- }),
261
+ withApprovalPolicy(
262
+ buildReviewFollowupInbound({
263
+ repository,
264
+ pullNumber,
265
+ headSha,
266
+ rootCommentIds,
267
+ selfBlocking,
268
+ title: readString(pr, 'title'),
269
+ }),
270
+ options.allowApprove?.() ?? true,
271
+ ),
233
272
  )
234
273
  } catch (err) {
235
274
  options.logger.warn(
236
- `[github] review-thread recheck failed for ${target}: ${err instanceof Error ? err.message : String(err)}`,
275
+ `[github] review followup failed for ${target}: ${err instanceof Error ? err.message : String(err)}`,
237
276
  )
238
277
  }
239
278
  })
240
279
  }
241
280
 
242
- function buildRecheckInbound(input: {
281
+ function buildReviewFollowupInbound(input: {
243
282
  repository: { owner: string; name: string }
244
283
  pullNumber: number
245
- headSha: string | null
284
+ headSha: string
246
285
  rootCommentIds: readonly number[]
286
+ selfBlocking: boolean
247
287
  title: string | null
248
288
  }): InboundMessage {
249
- const { repository, pullNumber, headSha, rootCommentIds, title } = input
289
+ const { repository, pullNumber, headSha, rootCommentIds, selfBlocking, title } = input
250
290
  const titleSegment = title !== null && title.trim() !== '' ? `: "${title}"` : ''
251
- const shaSegment = headSha !== null ? ` (now at ${headSha.slice(0, 7)})` : ''
252
- const idList = rootCommentIds.join(', ')
253
291
  const text =
254
- `PR #${pullNumber}${titleSegment} received new commits${shaSegment}. ` +
255
- `You have ${rootCommentIds.length} unresolved review thread(s) you authored on this PR ` +
256
- `(root comment id(s): ${idList}). For each, check whether the new commits addressed your ` +
257
- `concern. If addressed, reply on that thread via channel_send with a short acknowledgement ` +
258
- `and resolve_review_thread: true (the thread id is the root comment id). If not addressed, ` +
259
- `leave it open. If none are addressed, end your turn without replying.`
292
+ `PR #${pullNumber}${titleSegment} received new commits (now at ${headSha.slice(0, 7)}). ` +
293
+ followupInstruction(rootCommentIds, selfBlocking)
260
294
 
261
295
  return {
262
296
  adapter: 'github',
@@ -264,7 +298,7 @@ function buildRecheckInbound(input: {
264
298
  chat: `pr:${pullNumber}`,
265
299
  thread: null,
266
300
  text,
267
- externalMessageId: `pr-${pullNumber}-recheck-${headSha ?? 'unknown'}`,
301
+ externalMessageId: `pr-${pullNumber}-recheck-${headSha}`,
268
302
  authorId: 'github-system',
269
303
  authorName: 'github',
270
304
  authorIsBot: false,
@@ -277,6 +311,30 @@ function buildRecheckInbound(input: {
277
311
  }
278
312
  }
279
313
 
314
+ function followupInstruction(rootCommentIds: readonly number[], selfBlocking: boolean): string {
315
+ const threadPart =
316
+ rootCommentIds.length > 0
317
+ ? `You have ${rootCommentIds.length} unresolved review thread(s) you authored on this PR ` +
318
+ `(root comment id(s): ${rootCommentIds.join(', ')}). For each, check whether the new commits ` +
319
+ `addressed your concern. If addressed, reply on that thread via channel_send with a short ` +
320
+ `acknowledgement and resolve_review_thread: true (the thread id is the root comment id); ` +
321
+ `if not, leave it open. `
322
+ : ''
323
+ // A held CHANGES_REQUESTED never clears itself: GitHub keeps the block until a
324
+ // fresh APPROVE/COMMENT/dismiss, so a blocking follow-up must always end with a
325
+ // submitted verdict — the "end without replying" escape hatch is reserved for
326
+ // the thread-only path, where leaving every thread open is a valid no-op.
327
+ const blockingPart = selfBlocking
328
+ ? `Your latest review on this PR is still CHANGES_REQUESTED, which keeps the PR blocked until you ` +
329
+ `submit a fresh review. Re-review the current head against the concerns from that blocking review ` +
330
+ `and always end with a new verdict: if the commits resolve your concerns, submit an APPROVE ` +
331
+ `(or COMMENT if approval is disabled) to clear the block; if concerns remain, submit a new ` +
332
+ `CHANGES_REQUESTED explaining what is still blocking. `
333
+ : ''
334
+ const tail = selfBlocking ? '' : 'If none are addressed, end your turn without replying.'
335
+ return `${threadPart}${blockingPart}${tail}`
336
+ }
337
+
280
338
  export async function verifySignature(body: string, secret: string, sigHeader: string): Promise<boolean> {
281
339
  const expected = `sha256=${createHmac('sha256', secret).update(body).digest('hex')}`
282
340
  const a = Buffer.from(expected)
@@ -48,6 +48,33 @@ export function createGithubReviewStateResolver(deps: {
48
48
  }
49
49
  }
50
50
 
51
+ export type SelfReviewBlockingResult =
52
+ | { ok: true; selfBlocking: boolean }
53
+ | { ok: false; error: string; code: 'not-found' | 'permission-denied' | 'transient' }
54
+
55
+ // Last DECISIVE self review == CHANGES_REQUESTED? (COMMENTED/PENDING ignored, as
56
+ // in createGithubReviewStateResolver.) Standalone so the synchronize follow-up
57
+ // skips the reviewDecision round-trip the stranding guard needs but this doesn't.
58
+ export async function fetchSelfReviewBlocking(deps: {
59
+ token: string
60
+ selfLogin: string
61
+ owner: string
62
+ repo: string
63
+ prNumber: number
64
+ fetchImpl?: typeof fetch
65
+ }): Promise<SelfReviewBlockingResult> {
66
+ const fetchImpl = deps.fetchImpl ?? fetch
67
+ const reviews = await fetchSelfReviews(
68
+ fetchImpl,
69
+ deps.token,
70
+ { owner: deps.owner, repo: deps.repo, prNumber: deps.prNumber },
71
+ deps.selfLogin,
72
+ )
73
+ if (!reviews.ok) return { ok: false, error: reviews.error, code: reviews.code }
74
+ const lastDecisive = reviews.states.filter(isDecisive).at(-1) ?? null
75
+ return { ok: true, selfBlocking: lastDecisive === 'CHANGES_REQUESTED' }
76
+ }
77
+
51
78
  type Target = { owner: string; repo: string; prNumber: number }
52
79
 
53
80
  function parseTarget(workspace: string, chat: string): Target | null {
@@ -53,6 +53,12 @@ const WARN_POSITIVE_CLOSEOUT: readonly RegExp[] = [
53
53
  /\bshould be (fine|good)\b/,
54
54
  /\blooks resolved\b/,
55
55
  /\bseems resolved\b/,
56
+ // The canonical PR #672 close-out: "that addresses the concern", "addressed
57
+ // your feedback". On a PR the bot still blocks, this READS as a verdict and
58
+ // strands the block, so it escalates through the re-review guard. Demoted to
59
+ // ignore by the negation/future markers below ("haven't addressed", "to
60
+ // address").
61
+ /\baddress(es|ed)\b[^.!?]*\b(concern|feedback|review|comment|issue|point)/,
56
62
  ]
57
63
 
58
64
  // Negative warn phrases re-assert a block ("not done yet") instead of closing it
@@ -65,11 +71,17 @@ const WARN: readonly RegExp[] = [...WARN_POSITIVE_CLOSEOUT, ...WARN_NEGATIVE]
65
71
  // ignore. Blocking "I haven't approved" / "I'll approve" / "approved it earlier"
66
72
  // (answering a question) is the worst false-positive class, so it is checked first.
67
73
  const DEMOTE_TO_IGNORE: readonly RegExp[] = [
68
- /\b(haven'?t|have not|did ?n'?t|did not|not yet|never)\b[^.!?]*\b(approv|request|resolv|block)/,
69
- /\b(can'?t|cannot|won'?t|will not|wouldn'?t)\b[^.!?]*\b(approv|request|resolv|block)/,
70
- /\bnot (approved|resolved|blocked|requesting)\b/,
74
+ /\b(haven'?t|have not|did ?n'?t|did not|not yet|never)\b[^.!?]*\b(approv|request|resolv|block|address)/,
75
+ /\b(can'?t|cannot|won'?t|will not|wouldn'?t)\b[^.!?]*\b(approv|request|resolv|block|address)/,
76
+ /\bnot (approved|resolved|blocked|requesting|addressed)\b/,
71
77
  /\b(not|no longer|hardly|barely)\b[^.!?]*\b(lgtm|looks good|looks fine|seems fine|should be (fine|good)|looks resolved|seems resolved)\b/,
72
78
  /\b(i'?ll|i will|going to|gonna|about to|planning to)\b[^.!?]*\b(approv|review|request|resolv)/,
79
+ // "address" demotion is restricted to explicit future/obligation forms only.
80
+ // A standalone `to` marker (e.g. "...to address my feedback") would match
81
+ // hard-claim prose like "Approved — thanks for updating the docs to address
82
+ // my feedback" and demote it to ignore BEFORE the BLOCK_APPROVE check, hiding
83
+ // a real verdict (the recovery path would then post it unguarded — PR #675).
84
+ /\b(i'?ll|i will|going to|gonna|about to|planning to|need(s)? to|have to|want(s)? to|trying to)\b[^.!?]*\baddress/,
73
85
  /\b(approved|resolved|requested changes)\b[^.!?]*\b(earlier|already|yesterday|before|last (review|time)|previously)\b/,
74
86
  /\b(pre|self|co|re|un|non|ai|admin|user|machine|auto) approved\b/,
75
87
  ]
@@ -3,9 +3,34 @@ export type OutboundFloodCheckResult = { ok: true } | { ok: false; reason: strin
3
3
  const MIN_LENGTH = 40
4
4
  const MAX_RUN = 30
5
5
  const MIN_LONG_LENGTH = 80
6
- const MIN_UNIQUE_RATIO = 0.05
7
6
  const MAX_DOMINANCE = 0.9
8
7
 
8
+ // Contiguous-span detector for multi-character floods ("lollol...", "ababab...",
9
+ // repeated emoji pairs) — including a flood body buried inside otherwise-varied
10
+ // text, which a whole-message periodicity test misses. Strict equality (no
11
+ // mismatch budget) and a large span floor keep it clear of incidental prose
12
+ // repetition ("---", "....", "hahaha", code indentation, table separators).
13
+ const MAX_REPEATING_PERIOD = 32
14
+ // Span floor is deliberately a flood boundary, not a "never-deny" guarantee: it
15
+ // catches obvious short-period floods like "ab".repeat(300) (600 chars) and
16
+ // "lol".repeat(300) (900). Hundreds of byte-identical rows or box-art lines also
17
+ // trip it — that output is information-poor and flood-like, and raising the floor
18
+ // to clear it would let those real floods through. Tables/diagrams with varying
19
+ // cells break periodicity and pass.
20
+ const MIN_PERIODIC_SPAN = 384
21
+ const MIN_PERIODIC_REPETITIONS = 24
22
+
23
+ // Narrow last resort: structured text (code, tables, logs) is often lower-
24
+ // entropy than prose, so this only fires on a tiny alphabet at real length.
25
+ const MIN_ENTROPY_LENGTH = 200
26
+ const MAX_TINY_ALPHABET_SIZE = 4
27
+ const VERY_LOW_ENTROPY_BITS = 1.25
28
+
29
+ // Replaces the old `uniqueRatio = distinctChars / length` gate, which was
30
+ // length-coupled: natural language draws from a fixed alphabet, so any reply
31
+ // past ~(alphabet/0.05) chars failed it regardless of variety — a 2.9KB
32
+ // markdown report was silently dropped. Every check below is bounded-run or
33
+ // length-independent, so length alone never makes a reply look like a flood.
9
34
  export function checkOutboundFlood(text: string): OutboundFloodCheckResult {
10
35
  if (text.length < MIN_LENGTH) return { ok: true }
11
36
 
@@ -18,12 +43,18 @@ export function checkOutboundFlood(text: string): OutboundFloodCheckResult {
18
43
  if (graphemes.length < MIN_LONG_LENGTH) return { ok: true }
19
44
 
20
45
  const counts = countGraphemes(graphemes)
21
- const uniqueRatio = counts.size / graphemes.length
22
- if (uniqueRatio < MIN_UNIQUE_RATIO) return { ok: false, reason: `low-unique-ratio:${uniqueRatio.toFixed(3)}` }
23
46
 
24
47
  const dominance = maxValue(counts) / graphemes.length
25
48
  if (dominance > MAX_DOMINANCE) return { ok: false, reason: `char-dominance:${dominance.toFixed(2)}` }
26
49
 
50
+ const span = findLongestPeriodicSpan(graphemes)
51
+ if (span !== undefined) return { ok: false, reason: `repeated-pattern-span:${span.period}:${span.spanLength}` }
52
+
53
+ if (graphemes.length >= MIN_ENTROPY_LENGTH && counts.size <= MAX_TINY_ALPHABET_SIZE) {
54
+ const entropy = shannonEntropyBitsPerGrapheme(counts, graphemes.length)
55
+ if (entropy < VERY_LOW_ENTROPY_BITS) return { ok: false, reason: `low-entropy:${entropy.toFixed(2)}` }
56
+ }
57
+
27
58
  return { ok: true }
28
59
  }
29
60
 
@@ -42,6 +73,42 @@ function findLongestRun(graphemes: readonly string[]): number {
42
73
  return longest
43
74
  }
44
75
 
76
+ // Longest contiguous span (in graphemes) that is exactly periodic at some
77
+ // period 2..32, or undefined when no span clears the flood floor. Period 1 is
78
+ // left to the run check above. A span must reach MIN_PERIODIC_SPAN graphemes
79
+ // AND repeat its unit MIN_PERIODIC_REPETITIONS times — the larger bound wins,
80
+ // so a 32-period unit needs 768 graphemes, not three echoes of a 32-char line.
81
+ function findLongestPeriodicSpan(graphemes: readonly string[]): { period: number; spanLength: number } | undefined {
82
+ const maxPeriod = Math.min(MAX_REPEATING_PERIOD, Math.floor(graphemes.length / MIN_PERIODIC_REPETITIONS))
83
+ let best: { period: number; spanLength: number } | undefined
84
+ for (let period = 2; period <= maxPeriod; period++) {
85
+ let matches = 0
86
+ let longestForPeriod = 0
87
+ for (let i = period; i < graphemes.length; i++) {
88
+ if (graphemes[i] === graphemes[i - period]) {
89
+ matches++
90
+ const spanLength = matches + period
91
+ if (spanLength > longestForPeriod) longestForPeriod = spanLength
92
+ } else {
93
+ matches = 0
94
+ }
95
+ }
96
+ const requiredSpan = Math.max(MIN_PERIODIC_SPAN, period * MIN_PERIODIC_REPETITIONS)
97
+ if (longestForPeriod < requiredSpan) continue
98
+ if (best === undefined || longestForPeriod > best.spanLength) best = { period, spanLength: longestForPeriod }
99
+ }
100
+ return best
101
+ }
102
+
103
+ function shannonEntropyBitsPerGrapheme(counts: Map<string, number>, length: number): number {
104
+ let entropy = 0
105
+ for (const count of counts.values()) {
106
+ const probability = count / length
107
+ entropy -= probability * Math.log2(probability)
108
+ }
109
+ return entropy
110
+ }
111
+
45
112
  function countGraphemes(graphemes: readonly string[]): Map<string, number> {
46
113
  const counts = new Map<string, number>()
47
114
  for (const grapheme of graphemes) counts.set(grapheme, (counts.get(grapheme) ?? 0) + 1)
@@ -32,6 +32,8 @@ import {
32
32
  StickyLedger,
33
33
  type EngagementDecision,
34
34
  } from './engagement'
35
+ import { checkFalseReceipt } from './github-false-receipt'
36
+ import { evaluateRereviewGuard } from './github-rereview-guard'
35
37
  import { resetReviewTurn } from './github-review-turn-ledger'
36
38
  import {
37
39
  MEMBERSHIP_COLD_FETCH_TIMEOUT_MS,
@@ -3125,6 +3127,25 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3125
3127
  // the model's pre-tool commentary is the only user-facing text we have.
3126
3128
  // Recovering it means the user gets *something* — strictly better than
3127
3129
  // the historical silent drop.
3130
+ // Egress-level GitHub review guards. The false-receipt and re-review
3131
+ // stranding guards live inside the channel_reply / channel_send tool
3132
+ // handlers, but recovery surfaces trailing assistant prose through a
3133
+ // `source:'system'` send that never touches those handlers. A model that
3134
+ // ends its turn with a close-out ack ("that addresses the concern") instead
3135
+ // of calling a channel tool would otherwise post a verdict-shaped comment
3136
+ // while still holding its own CHANGES_REQUESTED — stranding the PR (PR #672).
3137
+ // Re-run the guards here and SUPPRESS on block: recovery cannot land the
3138
+ // missing formal review on the model's behalf, and posting the unguarded ack
3139
+ // is worse than dropping it — the next inbound re-prompts the model, which
3140
+ // can then land the verdict properly.
3141
+ const recoveryBlock = await evaluateRecoveryReviewGuards(live, assistantText)
3142
+ if (recoveryBlock !== null) {
3143
+ logger.warn(
3144
+ `[channels] ${live.keyId}: suppressed recovery (github review guard) reason=${JSON.stringify(recoveryBlock)} text_len=${assistantText.length}`,
3145
+ )
3146
+ return
3147
+ }
3148
+
3128
3149
  logger.warn(
3129
3150
  `[channels] ${live.keyId}: recovering assistant_text_without_channel_tool source=${source} text_len=${assistantText.length}`,
3130
3151
  )
@@ -3143,6 +3164,38 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3143
3164
  }
3144
3165
  }
3145
3166
 
3167
+ // Returns a block reason when the recovered text would be denied by a github
3168
+ // review guard, or null when it is safe to surface. Non-github channels and
3169
+ // non-PR chats short-circuit inside each guard (adapter / `pr:\d+` checks), so
3170
+ // this is a no-op for everything except GitHub PR sessions.
3171
+ const evaluateRecoveryReviewGuards = async (live: LiveSession, text: string): Promise<string | null> => {
3172
+ const falseReceipt = checkFalseReceipt({
3173
+ sessionId: live.sessionId,
3174
+ adapter: live.key.adapter,
3175
+ workspace: live.key.workspace,
3176
+ chat: live.key.chat,
3177
+ thread: live.key.thread,
3178
+ text,
3179
+ isContinue: false,
3180
+ resolveReviewThread: false,
3181
+ })
3182
+ if (falseReceipt.kind === 'block') return falseReceipt.reason
3183
+
3184
+ const rereview = await evaluateRereviewGuard({
3185
+ adapter: live.key.adapter,
3186
+ workspace: live.key.workspace,
3187
+ chat: live.key.chat,
3188
+ thread: live.key.thread,
3189
+ text,
3190
+ wantsResolve: false,
3191
+ isContinue: false,
3192
+ getReviewState: (req) => getReviewState(req),
3193
+ })
3194
+ if (rereview.block) return rereview.reason
3195
+
3196
+ return null
3197
+ }
3198
+
3146
3199
  const getConsecutiveSendCount = (target: {
3147
3200
  adapter: ChannelKey['adapter']
3148
3201
  workspace: string
@@ -1,6 +1,7 @@
1
1
  import { readdirSync } from 'node:fs'
2
2
  import { join, resolve } from 'node:path'
3
3
 
4
+ import { loadConfigSyncOrDefaults } from '@/config'
4
5
  import { containerNameFromCwd } from '@/container'
5
6
  import { isInitialized } from '@/init'
6
7
 
@@ -17,7 +18,9 @@ export type AgentEntry = {
17
18
  //
18
19
  // Underscore-prefixed names are also skipped so operators can park a disabled
19
20
  // or in-progress agent next to live ones (e.g. `_archived-coder/`) without
20
- // compose touching it.
21
+ // compose touching it. Agents with `compose.exclude: true` in typeclaw.json
22
+ // are skipped too — the in-config opt-out for operators who don't want to rename
23
+ // the folder.
21
24
  //
22
25
  // Returns an empty array when rootCwd doesn't exist or is empty — discovery is
23
26
  // not the place to fail; the caller decides what to do with zero agents.
@@ -40,6 +43,7 @@ export function discoverAgents(rootCwd: string): AgentEntry[] {
40
43
  if (entry.name.startsWith('_')) continue
41
44
  const cwd = join(root, entry.name)
42
45
  if (!isInitialized(cwd)) continue
46
+ if (loadConfigSyncOrDefaults(cwd).compose.exclude) continue
43
47
  agents.push({ name: entry.name, cwd, containerName: containerNameFromCwd(cwd) })
44
48
  }
45
49
 
@@ -338,6 +338,39 @@ export const networkSchema = z
338
338
 
339
339
  export type NetworkConfig = z.infer<typeof networkSchema>
340
340
 
341
+ // `realProc` opts the per-tool bwrap sandbox into the 'real-proc' strategy
342
+ // (src/sandbox/build.ts): a fresh procfs scoped to a new PID namespace so
343
+ // external-package runners (`bunx`, `bun add <pkg>`, `bun run <pkg-bin>`) get a
344
+ // working /proc/self/{fd,maps} and stop aborting with Bun's "NotDir". Default
345
+ // `false` keeps the universally-portable '--tmpfs /proc' profile, under which
346
+ // sandboxed external-package execution is unsupported by design. Turning it on
347
+ // makes `typeclaw start` grant the container CAP_SYS_ADMIN (required to mount
348
+ // proc for the new PID namespace), which is a deliberate posture change on the
349
+ // single-tenant outer boundary — see docs/internals/sandbox.mdx. PID isolation
350
+ // and the /proc/N/environ leak guard are both preserved; the trade is the
351
+ // CAP_SYS_ADMIN grant, not sandbox strength.
352
+ export const sandboxSchema = z
353
+ .object({
354
+ realProc: z.boolean().default(false),
355
+ })
356
+ .default({ realProc: false })
357
+
358
+ export type SandboxConfig = z.infer<typeof sandboxSchema>
359
+
360
+ // Host-stage `typeclaw compose` knobs. `exclude: true` skips this agent during
361
+ // compose discovery (same effect as parking it under an `_`-prefixed dir, but
362
+ // without renaming the folder). The container never reads this block — it's a
363
+ // pure compose CLI hint, so omitting it keeps the agent in every compose
364
+ // operation. Namespaced under `compose` so future compose-only settings have a
365
+ // home without crowding the top level.
366
+ export const composeSchema = z
367
+ .object({
368
+ exclude: z.boolean().default(false),
369
+ })
370
+ .default({ exclude: false })
371
+
372
+ export type ComposeConfig = z.infer<typeof composeSchema>
373
+
341
374
  // Reverse-proxy tunnels expose a container-private port to the public internet
342
375
  // via a managed subprocess (cloudflared) or a user-supplied external URL.
343
376
  // See AGENTS.md `## Tunnels`. Keeping the enum scoped to what's implemented
@@ -490,9 +523,11 @@ export const configSchema = z
490
523
  // time. Defaults to `[]`. Hatching appends the agent's chosen name
491
524
  // here, so a freshly-hatched bot already has its identity wired up.
492
525
  alias: z.array(z.string().trim().min(1)).default([]),
526
+ compose: composeSchema,
493
527
  channels: channelsSchema,
494
528
  portForward: portForwardSchema,
495
529
  network: networkSchema,
530
+ sandbox: sandboxSchema,
496
531
  docker: dockerSchema,
497
532
  git: gitSchema,
498
533
  roles: rolesConfigSchema.optional(),
@@ -632,9 +667,11 @@ export const FIELD_EFFECTS: Record<string, FieldEffect> = {
632
667
  mcpServers: 'restart-required',
633
668
  plugins: 'restart-required',
634
669
  alias: 'applied',
670
+ compose: 'ignored',
635
671
  channels: 'applied',
636
672
  portForward: 'restart-required',
637
673
  network: 'restart-required',
674
+ sandbox: 'restart-required',
638
675
  tunnels: 'restart-required',
639
676
  'docker.file': 'restart-required',
640
677
  'git.ignore': 'restart-required',
@@ -723,6 +760,7 @@ export function extractPluginConfigs(raw: unknown): Record<string, unknown> {
723
760
  'mounts',
724
761
  'plugins',
725
762
  'alias',
763
+ 'compose',
726
764
  'channels',
727
765
  'portForward',
728
766
  'network',
@@ -514,6 +514,20 @@ export async function planStart({
514
514
  }
515
515
  }
516
516
 
517
+ // sandbox.realProc opts the per-tool bwrap sandbox into the 'real-proc'
518
+ // strategy (src/sandbox/build.ts), which prefixes the sandbox with
519
+ // `unshare --pid --fork --mount --mount-proc`. Mounting a fresh procfs for the
520
+ // new PID namespace needs real CAP_SYS_ADMIN — seccomp=unconfined alone is not
521
+ // enough (it only unblocks the unshare/clone SYSCALLS; the kernel still
522
+ // rejects mount(2) of proc without the capability). This is the deliberate
523
+ // posture change documented in docs/internals/sandbox.mdx: the default keeps
524
+ // the narrower seccomp-only profile, and the operator grants the broad
525
+ // "new root" capability ONLY by opting into real-proc. Placed before the
526
+ // image tag (like --cap-add=NET_ADMIN) so docker applies it at run time.
527
+ if (cfg.sandbox.realProc) {
528
+ runArgs.push('--cap-add=SYS_ADMIN')
529
+ }
530
+
517
531
  if (hostdControl) {
518
532
  runArgs.push('--add-host', HOST_GATEWAY_ALIAS)
519
533
  }
@@ -0,0 +1,35 @@
1
+ import { MIGRATION_ID, migrateSecretsV1ToV2, type SecretsMigrationResult } from './secrets-v1-to-v2'
2
+
3
+ export { MIGRATION_ID, migrateSecretsV1ToV2, type SecretsMigrationResult }
4
+
5
+ export type Migration = {
6
+ id: string
7
+ run: (agentDir: string) => SecretsMigrationResult
8
+ }
9
+
10
+ export type MigrationOutcome = { id: string; changed: boolean; summary: string; error?: string }
11
+
12
+ const MIGRATIONS: readonly Migration[] = [{ id: MIGRATION_ID, run: migrateSecretsV1ToV2 }]
13
+
14
+ // Each migration is isolated: a throw is captured per-migration so one folder's
15
+ // unsafe state (e.g. both auth.json and a non-empty secrets.json) is reported
16
+ // loudly without aborting boot or blocking later migrations. Returns one
17
+ // outcome per registered migration so the caller can log what happened.
18
+ export function runStartupMigrations(
19
+ agentDir: string,
20
+ log: (message: string) => void = (m) => console.warn(m),
21
+ ): MigrationOutcome[] {
22
+ const outcomes: MigrationOutcome[] = []
23
+ for (const migration of MIGRATIONS) {
24
+ try {
25
+ const result = migration.run(agentDir)
26
+ if (result.changed) log(`migration ${migration.id}: ${result.summary}`)
27
+ outcomes.push({ id: migration.id, changed: result.changed, summary: result.summary })
28
+ } catch (err) {
29
+ const error = err instanceof Error ? err.message : String(err)
30
+ log(`migration ${migration.id} failed: ${error}`)
31
+ outcomes.push({ id: migration.id, changed: false, summary: 'failed', error })
32
+ }
33
+ }
34
+ return outcomes
35
+ }