typeclaw 0.48.9 → 0.48.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/package.json +1 -1
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +176 -0
  5. package/src/agent/index.ts +9 -0
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/agent/tools/subagent-cancel.ts +14 -2
  12. package/src/bundled-plugins/backup/README.md +4 -3
  13. package/src/bundled-plugins/backup/runner.ts +125 -32
  14. package/src/bundled-plugins/github-cli-auth/gh-command.ts +106 -9
  15. package/src/bundled-plugins/github-cli-auth/git-command.ts +94 -9
  16. package/src/bundled-plugins/github-cli-auth/index.ts +45 -5
  17. package/src/channels/adapters/github/inbound.ts +210 -27
  18. package/src/channels/adapters/github/index.ts +16 -18
  19. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  20. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  21. package/src/channels/adapters/github/review-submitter.ts +28 -0
  22. package/src/channels/adapters/instagram-continuity-store.ts +141 -0
  23. package/src/channels/adapters/instagram.ts +149 -4
  24. package/src/channels/github-repo.ts +11 -0
  25. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  26. package/src/channels/github-verdict-activity.ts +12 -6
  27. package/src/channels/manager.ts +10 -0
  28. package/src/channels/persistence.ts +28 -2
  29. package/src/channels/router.ts +371 -33
  30. package/src/channels/schema.ts +18 -0
  31. package/src/channels/types.ts +11 -0
  32. package/src/cli/compose.ts +7 -4
  33. package/src/compose/restart.ts +26 -16
  34. package/src/compose/start.ts +24 -14
  35. package/src/config/config.ts +9 -1
  36. package/src/container/restart.ts +4 -0
  37. package/src/container/shared.ts +30 -3
  38. package/src/container/start.ts +137 -56
  39. package/src/doctor/apparmor.ts +101 -0
  40. package/src/doctor/checks.ts +2 -0
  41. package/src/hostd/daemon.ts +40 -17
  42. package/src/init/dockerfile.ts +7 -6
  43. package/src/init/windows-dev-link.ts +34 -2
  44. package/src/run/channel-session-factory.ts +35 -15
  45. package/src/run/index.ts +1 -0
  46. package/src/sandbox/availability.ts +7 -5
  47. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  48. package/typeclaw.schema.json +7 -0
@@ -272,11 +272,12 @@ export function createChannelSendTool({
272
272
  }
273
273
  }
274
274
  if (resolve.kind === 'already-resolved') {
275
- router.finishGithubReviewRoundCloseout?.({
275
+ router.finishGithubReviewThreadCloseout?.({
276
276
  sessionId,
277
277
  workspace: params.workspace,
278
278
  prNumber: parseGithubPrNumber(params.chat),
279
279
  thread: params.thread ?? null,
280
+ decision: 'resolved',
280
281
  })
281
282
  return {
282
283
  content: [{ type: 'text' as const, text: alreadyResolvedHint(params.thread ?? null) }],
@@ -293,11 +294,12 @@ export function createChannelSendTool({
293
294
  resolveMissNotice = resolveMissHint(params.thread ?? null)
294
295
  } else {
295
296
  recordResolvedThreadFromSend(sessionId, params.workspace, params.chat, params.thread ?? null)
296
- router.finishGithubReviewRoundCloseout?.({
297
+ router.finishGithubReviewThreadCloseout?.({
297
298
  sessionId,
298
299
  workspace: params.workspace,
299
300
  prNumber: parseGithubPrNumber(params.chat),
300
301
  thread: params.thread ?? null,
302
+ decision: 'resolved',
301
303
  })
302
304
  }
303
305
  }
@@ -319,6 +321,21 @@ export function createChannelSendTool({
319
321
  ),
320
322
  )
321
323
  }
324
+ if (
325
+ result.ok &&
326
+ params.resolve_review_thread === false &&
327
+ adapter === 'github' &&
328
+ params.thread != null &&
329
+ /^pr:\d+$/.test(params.chat)
330
+ ) {
331
+ router.finishGithubReviewThreadCloseout?.({
332
+ sessionId,
333
+ workspace: params.workspace,
334
+ prNumber: parseGithubPrNumber(params.chat),
335
+ thread: params.thread ?? null,
336
+ decision: 'left-open',
337
+ })
338
+ }
322
339
  const details: { ok: boolean; error?: string; messageId?: string; messageIds?: readonly string[] } = result.ok
323
340
  ? {
324
341
  ok: true,
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto'
3
3
  import { Type } from '@mariozechner/pi-ai'
4
4
  import { defineTool } from '@mariozechner/pi-coding-agent'
5
5
 
6
+ import { githubReviewerWorkKey } from '@/channels/github-repo'
6
7
  import type { PermissionService } from '@/permissions'
7
8
  import type { Stream } from '@/stream'
8
9
 
@@ -199,6 +200,10 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
199
200
  reviewKind: params.review_identity.review_kind,
200
201
  }
201
202
  }
203
+ const workKey =
204
+ params.review_identity === undefined
205
+ ? undefined
206
+ : githubReviewerWorkKey(params.review_identity.repo, params.review_identity.pull_request)
202
207
 
203
208
  const coalesceKey = subagentCoalesceKey({
204
209
  parentSessionId,
@@ -216,6 +221,8 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
216
221
  coalesceKeyHeld = false
217
222
  coalescer.release(coalesceKey)
218
223
  }
224
+ const pendingWorkKeyRegistration =
225
+ workKey === undefined ? undefined : liveRegistry.beginWorkKeyRegistration(workKey)
219
226
 
220
227
  const startedAt = now()
221
228
  const spawnedByRole = permissions?.resolveRole(origin)
@@ -240,6 +247,9 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
240
247
  try {
241
248
  resolvedHandle = await handle
242
249
  } catch (err) {
250
+ if (pendingWorkKeyRegistration !== undefined) {
251
+ liveRegistry.abandonWorkKeyRegistration(pendingWorkKeyRegistration)
252
+ }
243
253
  releaseCoalesceKey()
244
254
  const message = err instanceof Error ? err.message : String(err)
245
255
  return errorResult(`failed to spawn ${subagentName}: ${message}`)
@@ -252,12 +262,36 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
252
262
  parentSessionId,
253
263
  ...(spawnedByRole !== undefined ? { spawnedByRole } : {}),
254
264
  background,
265
+ // Drafting a PR invalidates every reviewer job for it, regardless of
266
+ // commit or review kind. This is intentionally broader than the
267
+ // reviewer's head/base/kind-aware coalescing key.
268
+ ...(workKey !== undefined ? { workKey } : {}),
255
269
  startedAt,
256
270
  status: 'running' as const,
257
271
  abort: resolvedHandle.abort,
258
272
  releaseCoalesceKey,
259
273
  }
260
- liveRegistry.register(live)
274
+ const registered =
275
+ pendingWorkKeyRegistration === undefined
276
+ ? (liveRegistry.register(live), true)
277
+ : liveRegistry.registerIfWorkKeyActive(live, pendingWorkKeyRegistration)
278
+ let delayedCancellationError: string | undefined
279
+ if (!registered) {
280
+ void completion.then(releaseCoalesceKey)
281
+ try {
282
+ await resolvedHandle.abort()
283
+ } catch (err) {
284
+ const message = err instanceof Error ? err.message : String(err)
285
+ // The child is still live. Register it so later cancellation, status
286
+ // inspection, and completion settlement can still reach it.
287
+ liveRegistry.register(live)
288
+ delayedCancellationError = `reviewer cancellation failed before registration: ${message}`
289
+ }
290
+ if (delayedCancellationError === undefined) {
291
+ releaseCoalesceKey()
292
+ return errorResult('reviewer cancelled before registration: pull request converted to draft')
293
+ }
294
+ }
261
295
  if (capturedFinalMessage !== undefined) {
262
296
  liveRegistry.recordCapturedFinalMessageIfRunning(taskId, capturedFinalMessage)
263
297
  }
@@ -293,6 +327,8 @@ export function createSpawnSubagentTool(options: CreateSpawnSubagentToolOptions)
293
327
  })
294
328
  })
295
329
 
330
+ if (delayedCancellationError !== undefined) return errorResult(delayedCancellationError)
331
+
296
332
  if (background) {
297
333
  const details: SpawnSubagentToolDetails = {
298
334
  ok: true,
@@ -16,10 +16,11 @@ export type CreateSubagentCancelToolOptions = {
16
16
  getOrigin: () => SessionOrigin | undefined
17
17
  permissions?: PermissionService
18
18
  callerSessionId?: string
19
+ hasOutstandingReviewThreadCloseout?: (sessionId: string) => boolean
19
20
  }
20
21
 
21
22
  export function createSubagentCancelTool(options: CreateSubagentCancelToolOptions) {
22
- const { liveRegistry, getOrigin, permissions, callerSessionId } = options
23
+ const { liveRegistry, getOrigin, permissions, callerSessionId, hasOutstandingReviewThreadCloseout } = options
23
24
 
24
25
  return defineTool({
25
26
  name: 'subagent_cancel',
@@ -71,6 +72,17 @@ export function createSubagentCancelTool(options: CreateSubagentCancelToolOption
71
72
  return errorResult(`abort failed: ${message}`)
72
73
  }
73
74
  live.releaseCoalesceKey?.()
75
+ const owesReviewThreadCloseout =
76
+ callerSessionId !== undefined && hasOutstandingReviewThreadCloseout?.(callerSessionId) === true
77
+ const hasOtherRunningChild =
78
+ callerSessionId !== undefined &&
79
+ liveRegistry
80
+ .list({ parentSessionId: callerSessionId })
81
+ .some((candidate) => candidate.taskId !== live.taskId && candidate.status === 'running')
82
+ const closeoutWarning =
83
+ owesReviewThreadCloseout && !hasOtherRunningChild
84
+ ? ' Warning: cancellation succeeded, but this session still owes its GitHub review thread a close-out. Reply now with an explicit resolve choice, or explain why you are leaving the thread open.'
85
+ : ''
74
86
  const details: SubagentCancelToolDetails = {
75
87
  ok: true,
76
88
  taskId: live.taskId,
@@ -81,7 +93,7 @@ export function createSubagentCancelTool(options: CreateSubagentCancelToolOption
81
93
  content: [
82
94
  {
83
95
  type: 'text' as const,
84
- text: `${live.subagentName} (${live.taskId}) cancellation requested. It will stop on the next abort checkpoint.`,
96
+ text: `${live.subagentName} (${live.taskId}) cancellation requested. It will stop on the next abort checkpoint.${closeoutWarning}`,
85
97
  },
86
98
  ],
87
99
  details,
@@ -38,10 +38,11 @@ If a new prompt arrives while the runner is in flight, the runner finishes its c
38
38
 
39
39
  ## What it commits
40
40
 
41
- The runner stages two categories of dirty paths:
41
+ The runner stages an explicit snapshot from NUL-delimited porcelain status:
42
42
 
43
- - **Tracked or untracked agent paths** (anything `git status --porcelain=v1 --untracked-files=all` reports), **except** paths under `memory/` — those are owned by the memory plugin's dreaming subagent.
44
- - **Force-added `sessions/`** — gitignored, but force-added so transcripts survive across restarts.
43
+ - **Tracked changes**, including deletions and both rename/copy endpoints, are staged even when an endpoint is no longer present on disk.
44
+ - **Ordinary untracked paths** are staged only while still present. If one disappears between snapshot and `git add`, the runner re-reads status and retries that same snapshot once without the vanished path; paths discovered during that re-read are never added.
45
+ - **`memory/`** remains excluded. Present **`sessions/` and `todo/`** paths remain force-added; tracked deletions under those prefixes stay in the ordinary snapshot. The post-message pass re-stages only `sessions/` paths that appeared while the message was selected.
45
46
 
46
47
  Commit message comes from the `backup-message` subagent, which sees a truncated `git status` and `git diff --cached --stat` and writes a single conventional-ish commit message to a tmp file. On any failure the runner falls back to `chore: backup`.
47
48
 
@@ -1,4 +1,4 @@
1
- import { existsSync } from 'node:fs'
1
+ import { lstatSync } from 'node:fs'
2
2
  import { join } from 'node:path'
3
3
 
4
4
  import { hooklessGitArgs } from '@/git/hookless'
@@ -95,31 +95,35 @@ export async function runBackup(options: BackupRunnerOptions, deps: BackupRunner
95
95
  const repo = resolveAgentGit(cwd)
96
96
  if (!repo) return { ok: true, kind: 'no-repo' }
97
97
 
98
- const status = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '--untracked-files=all'], {
98
+ const status = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
99
99
  cwd,
100
100
  timeoutMs: COMMIT_TIMEOUT_MS,
101
101
  })
102
102
  if (status.exitCode !== 0) return { ok: false, kind: 'aborted', reason: `git status failed: ${shortErr(status)}` }
103
- const dirty = filterAgentOwned(parsePorcelain(status.stdout))
104
- const force = filterForceAdd(parsePorcelain(status.stdout))
105
- if (dirty.length === 0 && force.length === 0) return { ok: true, kind: 'clean' }
103
+ const snapshot = selectStagingSnapshot(parsePorcelain(status.stdout), cwd)
104
+ if (snapshot.paths.length === 0 && snapshot.forcePaths.length === 0) return { ok: true, kind: 'clean' }
106
105
 
107
- if (dirty.length > 0) {
108
- const add = await deps.gitSpawn([...repo.gitArgs, 'add', '--', ...dirty], { cwd, timeoutMs: COMMIT_TIMEOUT_MS })
109
- if (add.exitCode !== 0) return { ok: false, kind: 'commit-failed', reason: `git add failed: ${shortErr(add)}` }
110
- }
111
- if (force.length > 0) {
112
- const present = force.filter((p) => existsSync(join(cwd, p)))
113
- if (present.length > 0) {
114
- const addF = await deps.gitSpawn([...repo.gitArgs, 'add', '-f', '--', ...present], {
115
- cwd,
116
- timeoutMs: COMMIT_TIMEOUT_MS,
117
- })
118
- if (addF.exitCode !== 0) {
119
- return { ok: false, kind: 'commit-failed', reason: `git add -f failed: ${shortErr(addF)}` }
106
+ if (snapshot.paths.length > 0) {
107
+ const add = await deps.gitSpawn([...repo.gitArgs, 'add', '--', ...snapshot.paths], {
108
+ cwd,
109
+ timeoutMs: COMMIT_TIMEOUT_MS,
110
+ })
111
+ if (add.exitCode !== 0) {
112
+ const retry = await retryAfterVanishedUntracked(cwd, deps, repo, snapshot)
113
+ if (!retry || retry.exitCode !== 0) {
114
+ return { ok: false, kind: 'commit-failed', reason: `git add failed: ${shortErr(retry ?? add)}` }
120
115
  }
121
116
  }
122
117
  }
118
+ if (snapshot.forcePaths.length > 0) {
119
+ const addF = await deps.gitSpawn([...repo.gitArgs, 'add', '-f', '--', ...snapshot.forcePaths], {
120
+ cwd,
121
+ timeoutMs: COMMIT_TIMEOUT_MS,
122
+ })
123
+ if (addF.exitCode !== 0) {
124
+ return { ok: false, kind: 'commit-failed', reason: `git add -f failed: ${shortErr(addF)}` }
125
+ }
126
+ }
123
127
 
124
128
  const stagedCheck = await deps.gitSpawn([...repo.gitArgs, 'diff', '--cached', '--quiet'], {
125
129
  cwd,
@@ -132,7 +136,7 @@ export async function runBackup(options: BackupRunnerOptions, deps: BackupRunner
132
136
  timeoutMs: COMMIT_TIMEOUT_MS,
133
137
  })
134
138
  const message = await deps.pickCommitMessage({
135
- status: status.stdout.slice(0, 4096),
139
+ status: status.stdout.replaceAll('\0', '\n').slice(0, 4096),
136
140
  diffstat: diffstat.stdout.slice(0, 4096),
137
141
  })
138
142
 
@@ -144,12 +148,12 @@ export async function runBackup(options: BackupRunnerOptions, deps: BackupRunner
144
148
  // one-cycle-behind churn. Re-status, filter to `sessions/` additions
145
149
  // only (don't accidentally stage user work that arrived during the
146
150
  // window), and force-add anything new.
147
- const reStatus = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '--untracked-files=all'], {
151
+ const reStatus = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
148
152
  cwd,
149
153
  timeoutMs: COMMIT_TIMEOUT_MS,
150
154
  })
151
155
  if (reStatus.exitCode === 0) {
152
- const lateForce = filterForceAdd(parsePorcelain(reStatus.stdout)).filter((p) => existsSync(join(cwd, p)))
156
+ const lateForce = selectForcePaths(parsePorcelain(reStatus.stdout), cwd, ['sessions/'])
153
157
  if (lateForce.length > 0) {
154
158
  const lateAdd = await deps.gitSpawn([...repo.gitArgs, 'add', '-f', '--', ...lateForce], {
155
159
  cwd,
@@ -372,23 +376,112 @@ function isNonFastForward(r: GitSpawnResult): boolean {
372
376
  return blob.includes('non-fast-forward') || blob.includes('updates were rejected')
373
377
  }
374
378
 
375
- export function parsePorcelain(stdout: string): string[] {
376
- const out: string[] = []
377
- for (const raw of stdout.split('\n')) {
379
+ export type PorcelainEntry = {
380
+ status: string
381
+ kind: 'tracked' | 'untracked'
382
+ paths: readonly string[]
383
+ }
384
+
385
+ // `-z` makes paths literal rather than C-quoted. Rename/copy records carry the
386
+ // destination followed by the source, and both are needed when staging a
387
+ // snapshot that contains an endpoint which has since disappeared.
388
+ export function parsePorcelain(stdout: string): PorcelainEntry[] {
389
+ const separator = stdout.includes('\0') ? '\0' : '\n'
390
+ const records = stdout.split(separator)
391
+ const entries: PorcelainEntry[] = []
392
+
393
+ for (let index = 0; index < records.length; index += 1) {
394
+ const raw = records[index] ?? ''
378
395
  if (raw.length < 4) continue
379
- const rest = raw.slice(3)
380
- const arrowIdx = rest.indexOf(' -> ')
381
- out.push(arrowIdx === -1 ? rest : rest.slice(arrowIdx + 4))
396
+ const status = raw.slice(0, 2)
397
+ const path = raw.slice(3)
398
+ const renamedOrCopied = status.includes('R') || status.includes('C')
399
+ const source = renamedOrCopied && separator === '\0' ? records[++index] : undefined
400
+ const fallbackSource = renamedOrCopied && separator === '\n' ? path.split(' -> ')[0] : undefined
401
+ const destination = fallbackSource ? path.slice(fallbackSource.length + 4) : path
402
+ entries.push({
403
+ status,
404
+ kind: status === '??' ? 'untracked' : 'tracked',
405
+ paths: source ? [path, source] : fallbackSource ? [destination, fallbackSource] : [path],
406
+ })
382
407
  }
383
- return out
408
+ return entries
409
+ }
410
+
411
+ type StagingSnapshot = {
412
+ paths: string[]
413
+ untrackedPaths: Set<string>
414
+ forcePaths: string[]
415
+ }
416
+
417
+ function selectStagingSnapshot(entries: readonly PorcelainEntry[], cwd: string): StagingSnapshot {
418
+ const paths: string[] = []
419
+ const untrackedPaths = new Set<string>()
420
+ for (const entry of entries) {
421
+ for (const path of entry.paths) {
422
+ if (isAgentOwned(path)) continue
423
+ const forceAdded = FORCE_ADD_PREFIXES.some((prefix) => path.startsWith(prefix))
424
+ if (entry.kind === 'untracked') {
425
+ if (forceAdded || !hasDirectoryEntry(join(cwd, path))) continue
426
+ untrackedPaths.add(path)
427
+ }
428
+ paths.push(path)
429
+ }
430
+ }
431
+ return { paths: uniquePaths(paths), untrackedPaths, forcePaths: selectForcePaths(entries, cwd) }
432
+ }
433
+
434
+ async function retryAfterVanishedUntracked(
435
+ cwd: string,
436
+ deps: BackupRunnerDeps,
437
+ repo: AgentGit,
438
+ snapshot: StagingSnapshot,
439
+ ): Promise<GitSpawnResult | undefined> {
440
+ const reread = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
441
+ cwd,
442
+ timeoutMs: COMMIT_TIMEOUT_MS,
443
+ })
444
+ if (reread.exitCode !== 0) return undefined
445
+
446
+ const reported = new Set(
447
+ parsePorcelain(reread.stdout)
448
+ .filter((entry) => entry.kind === 'untracked')
449
+ .flatMap((entry) => entry.paths),
450
+ )
451
+ const vanished = new Set(
452
+ [...snapshot.untrackedPaths].filter((path) => !hasDirectoryEntry(join(cwd, path)) && !reported.has(path)),
453
+ )
454
+ if (vanished.size === 0) return undefined
455
+
456
+ const retryPaths = snapshot.paths.filter((path) => !vanished.has(path))
457
+ if (retryPaths.length === 0) return { exitCode: 0, stdout: '', stderr: '', timedOut: false }
458
+ return deps.gitSpawn([...repo.gitArgs, 'add', '--', ...retryPaths], { cwd, timeoutMs: COMMIT_TIMEOUT_MS })
459
+ }
460
+
461
+ function selectForcePaths(
462
+ entries: readonly PorcelainEntry[],
463
+ cwd: string,
464
+ prefixes: readonly string[] = FORCE_ADD_PREFIXES,
465
+ ): string[] {
466
+ return uniquePaths(
467
+ entries.flatMap((entry) =>
468
+ entry.paths.filter(
469
+ (path) => prefixes.some((prefix) => path.startsWith(prefix)) && hasDirectoryEntry(join(cwd, path)),
470
+ ),
471
+ ),
472
+ )
473
+ }
474
+
475
+ function hasDirectoryEntry(path: string): boolean {
476
+ return lstatSync(path, { throwIfNoEntry: false }) !== undefined
384
477
  }
385
478
 
386
- function filterAgentOwned(paths: readonly string[]): string[] {
387
- return paths.filter((p) => !RUNTIME_OWNED_PREFIXES.some((pre) => p.startsWith(pre)))
479
+ function uniquePaths(paths: readonly string[]): string[] {
480
+ return [...new Set(paths)]
388
481
  }
389
482
 
390
- function filterForceAdd(paths: readonly string[]): string[] {
391
- return paths.filter((p) => FORCE_ADD_PREFIXES.some((pre) => p.startsWith(pre)))
483
+ function isAgentOwned(path: string): boolean {
484
+ return RUNTIME_OWNED_PREFIXES.some((prefix) => path.startsWith(prefix))
392
485
  }
393
486
 
394
487
  function sanitizeCommitMessage(raw: string): string {
@@ -21,11 +21,15 @@ export type GhCommandDecision =
21
21
  // (REST, non-`api` subcommands) leave the command unchanged and omit it.
22
22
  | { kind: 'inject'; repoSlug: string; rewrittenCommand?: string }
23
23
 
24
+ // Reached whenever no EFFECTIVE DESTINATION repo can be determined — which is not
25
+ // the same as "argv has no slug": `gh label clone owner/repo` names a literal SOURCE
26
+ // slug and still lands here because the destination is what a token would be scoped
27
+ // to. The message must not assert a multi-owner App (MULTI_OWNER_REASON below covers
28
+ // that, and a single-owner App hitting this text reports a cause that is simply false).
24
29
  const MISSING_REPO_REASON =
25
- 'This GitHub App spans multiple owners, so `gh` has no single correct token. ' +
26
- 'Re-run as a single bare command with a LITERAL repo: `gh <cmd> -R owner/repo` ' +
27
- '(or `gh api /repos/owner/repo/...`) so the right installation token can be injected. ' +
28
- 'The repo must be a concrete `owner/repo` slug, not a shell variable.'
30
+ 'TypeClaw could not determine the effective destination repository for this `gh` command, ' +
31
+ 'so it cannot mint a scoped installation token. Re-run as a single bare command that names a ' +
32
+ 'LITERAL `owner/repo` slug TypeClaw can read from argv — not a shell variable.'
29
33
 
30
34
  const NON_LITERAL_REPO_REASON =
31
35
  'The `-R/--repo` value is not a literal `owner/repo` slug TypeClaw can verify. ' +
@@ -322,7 +326,20 @@ function addGraphqlQuery(queries: string[], field: string): void {
322
326
 
323
327
  const SAFE_GH_OPERATIONS: Readonly<Record<string, ReadonlySet<string>>> = {
324
328
  api: new Set(['']),
325
- pr: new Set(['view', 'list', 'status', 'checks', 'diff', 'review', 'comment', 'close', 'reopen', 'ready', 'merge']),
329
+ pr: new Set([
330
+ 'view',
331
+ 'list',
332
+ 'status',
333
+ 'checks',
334
+ 'diff',
335
+ 'review',
336
+ 'comment',
337
+ 'close',
338
+ 'reopen',
339
+ 'ready',
340
+ 'merge',
341
+ 'edit',
342
+ ]),
326
343
  issue: new Set(['view', 'list', 'status', 'comment', 'close', 'reopen', 'create']),
327
344
  label: new Set(['list', 'create', 'edit', 'delete', 'clone']),
328
345
  release: new Set(['view', 'list']),
@@ -346,6 +363,26 @@ const CREDENTIAL_UNSAFE_FLAGS = new Set([
346
363
  '--delete-branch',
347
364
  ])
348
365
 
366
+ // `gh pr edit` field flags whose values are inline argv strings. Every one is a
367
+ // label/login/name/free-text operand — none names a file, a host, or a template,
368
+ // so they satisfy the same credential-safety criterion as `gh pr comment --body`.
369
+ // `-F`/`--body-file` (file read) and `-t` (template) are excluded here and denied
370
+ // by CREDENTIAL_UNSAFE_FLAGS and the api-field scoping above.
371
+ const PR_EDIT_FIELD_FLAGS = new Set([
372
+ '--add-label',
373
+ '--remove-label',
374
+ '--add-assignee',
375
+ '--remove-assignee',
376
+ '--add-reviewer',
377
+ '--remove-reviewer',
378
+ '--add-project',
379
+ '--remove-project',
380
+ '--remove-milestone',
381
+ ])
382
+
383
+ const PR_EDIT_IDENTIFIER_FLAGS = new Set([...PR_EDIT_FIELD_FLAGS, '--milestone', '--base'])
384
+ const PR_EDIT_TEXT_FLAGS = new Set(['--title', '--body', '-b'])
385
+
349
386
  const CREDENTIAL_SAFE_FLAGS = new Set([
350
387
  '-R',
351
388
  '--repo',
@@ -404,6 +441,7 @@ const CREDENTIAL_SAFE_FLAGS = new Set([
404
441
  '--confirm',
405
442
  '--branch',
406
443
  '--event',
444
+ ...PR_EDIT_FIELD_FLAGS,
407
445
  ])
408
446
 
409
447
  function isCredentialSafeGhCommand(command: string): boolean {
@@ -415,6 +453,21 @@ function isCredentialSafeGhCommand(command: string): boolean {
415
453
  return tokens[0] === 'gh' && isCredentialSafeGhArgs(tokens.slice(1))
416
454
  }
417
455
 
456
+ // Flag NAMES are scoped by Cobra command, so a name-only allowlist is not a
457
+ // flag allowlist. `-F` is `--field` for `gh api`/`gh workflow run`, but Cobra
458
+ // binds it to `--body-file` on every pr/issue command in SAFE_GH_OPERATIONS:
459
+ // `gh pr comment 1 -R o/r -F /proc/self/environ` reads the minted token out of
460
+ // gh's own environ and posts it to a public comment thread. The long `--body-file`
461
+ // was denied while its short alias walked straight through the same allowlist.
462
+ // `-f` keeps its `gh label create/clone` `--force` meaning — the same command
463
+ // scoping `ghFlagTakesValue` already applies when finding positionals.
464
+ const API_FIELD_FLAGS = new Set(['-f', '--raw-field', '-F', '--field'])
465
+
466
+ function acceptsApiFieldFlag(command: string, flag: string): boolean {
467
+ if (command === 'api' || command === 'workflow') return true
468
+ return flag === '-f' && command === 'label'
469
+ }
470
+
418
471
  function isCredentialSafeGhArgs(args: readonly string[]): boolean {
419
472
  const parsed = parseGhArgs(args)
420
473
  if (parsed === null) return false
@@ -427,6 +480,9 @@ function isCredentialSafeGhArgs(args: readonly string[]): boolean {
427
480
  if (command === 'issue' && operation === 'create' && !isSafeCreateArgs(args)) {
428
481
  return false
429
482
  }
483
+ if (command === 'pr' && operation === 'edit' && !isSafePrEditArgs(args)) {
484
+ return false
485
+ }
430
486
 
431
487
  for (let i = 0; i < args.length; i++) {
432
488
  const arg = args[i] as string
@@ -434,10 +490,8 @@ function isCredentialSafeGhArgs(args: readonly string[]): boolean {
434
490
  if (CREDENTIAL_UNSAFE_FLAGS.has(flag)) return false
435
491
  if (flag.endsWith('-file') || flag.endsWith('-file-name')) return false
436
492
  if (arg.startsWith('-') && !CREDENTIAL_SAFE_FLAGS.has(flag)) return false
437
- if (
438
- (command === 'api' || command === 'workflow') &&
439
- (flag === '--raw-field' || flag === '-f' || flag === '--field' || flag === '-F')
440
- ) {
493
+ if (API_FIELD_FLAGS.has(flag) && !acceptsApiFieldFlag(command, flag)) return false
494
+ if ((command === 'api' || command === 'workflow') && API_FIELD_FLAGS.has(flag)) {
441
495
  const value = flagValue(args, i)
442
496
  if (value === null || fieldDereferencesFile(value)) return false
443
497
  }
@@ -470,6 +524,30 @@ function isSafeCreateArgs(args: readonly string[]): boolean {
470
524
  return true
471
525
  }
472
526
 
527
+ // `gh pr edit` with no field flag drops into an interactive survey and spawns
528
+ // $EDITOR for the body — a child process that inherits the minted token, the
529
+ // same shape `gh pr merge --delete-branch` is denied for. Requiring at least one
530
+ // recognized inline field flag keeps the invocation non-interactive. Identifier
531
+ // operands additionally reject `@` values, mirroring isSafeCreateArgs; `--title`
532
+ // and `--body` are free text where a leading `@mention` is legitimate and gh
533
+ // performs no file dereference.
534
+ function isSafePrEditArgs(args: readonly string[]): boolean {
535
+ let hasField = false
536
+ for (let i = 0; i < args.length; i++) {
537
+ const arg = args[i] as string
538
+ if (!arg.startsWith('-')) continue
539
+ const flag = arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg
540
+ const isIdentifierField = PR_EDIT_IDENTIFIER_FLAGS.has(flag)
541
+ if (!isIdentifierField && !PR_EDIT_TEXT_FLAGS.has(flag)) continue
542
+ hasField = true
543
+ if (flag === '--remove-milestone') continue
544
+ const value = flagValue(args, i)
545
+ if (value === null || value.trim() === '') return false
546
+ if (isIdentifierField && value.startsWith('@')) return false
547
+ }
548
+ return hasField
549
+ }
550
+
473
551
  function findFlagValue(args: readonly string[], names: readonly string[]): string | null {
474
552
  for (let i = 0; i < args.length; i++) {
475
553
  const arg = args[i] as string
@@ -1100,6 +1178,14 @@ const GH_FLAGS_WITH_VALUES = new Set([
1100
1178
  '--description',
1101
1179
  '--branch',
1102
1180
  '--event',
1181
+ '--add-label',
1182
+ '--remove-label',
1183
+ '--add-assignee',
1184
+ '--remove-assignee',
1185
+ '--add-reviewer',
1186
+ '--remove-reviewer',
1187
+ '--add-project',
1188
+ '--remove-project',
1103
1189
  ])
1104
1190
 
1105
1191
  const PR_REPO_SELECTOR_OPERATIONS = new Set([
@@ -1115,6 +1201,7 @@ const PR_REPO_SELECTOR_OPERATIONS = new Set([
1115
1201
  'ready',
1116
1202
  'merge',
1117
1203
  'checkout',
1204
+ 'edit',
1118
1205
  ])
1119
1206
  const ISSUE_REPO_SELECTOR_OPERATIONS = new Set(['view', 'list', 'status', 'comment', 'close', 'reopen'])
1120
1207
 
@@ -1401,12 +1488,22 @@ function findGhInvocations(tokens: readonly string[]): number[] {
1401
1488
  return starts
1402
1489
  }
1403
1490
 
1491
+ // bash treats `then`/`else`/`do` as reserved words ONLY in command position, and each
1492
+ // opens a fresh command position after it. Recognizing them is what makes
1493
+ // `if ...; then gh ...; fi` reach the composition gate — without it findGhInvocations
1494
+ // sees no invocation at all and the whole command silently passes through
1495
+ // unauthenticated, which is neither the documented policy nor a usable failure.
1496
+ // The recursion is what keeps `echo then gh` from registering: there, `then` is a
1497
+ // plain argument (not preceded by a boundary), so it opens nothing.
1498
+ const RESERVED_COMMAND_OPENERS = new Set(['then', 'else', 'do'])
1499
+
1404
1500
  function isCommandBoundaryBefore(tokens: readonly string[], index: number): boolean {
1405
1501
  let cursor = index - 1
1406
1502
  while (cursor >= 0) {
1407
1503
  const prev = tokens[cursor]
1408
1504
  if (prev === undefined) return false
1409
1505
  if (prev === '&&' || prev === '||' || prev === '|' || prev === ';' || prev === '\n') return true
1506
+ if (RESERVED_COMMAND_OPENERS.has(prev)) return isCommandBoundaryBefore(tokens, cursor)
1410
1507
  if (/^[A-Za-z_][A-Za-z0-9_]*=/.test(prev)) {
1411
1508
  cursor -= 1
1412
1509
  continue