typeclaw 0.48.8 → 0.48.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.48.8",
3
+ "version": "0.48.10",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -0,0 +1,106 @@
1
+ #!/usr/bin/env bash
2
+ # Acceptance check for the --ro-bind-data file-mask contract (appendMasks in
3
+ # src/sandbox/build.ts). Not a unit test: it needs the bubblewrap that actually
4
+ # ships in the base image, which the macOS dev host cannot provide and which
5
+ # `ubuntu-latest` does not match — so the bwrap-gated unit test silently skips
6
+ # on every CI runner we have.
7
+ #
8
+ # Why it exists: bwrap copies a --ro-bind-data operand out of its fd and then
9
+ # close()s it, so each mask needs its OWN fd. Sharing one appeared to work on
10
+ # bubblewrap <= 0.11.0 (the next mkstemp reclaimed the just-freed slot and
11
+ # copied the empty temp file onto itself) and hard-fails on 0.12.0 with
12
+ # "Can't write data to file <dest>: Bad file descriptor" — which aborts the
13
+ # WHOLE bwrap invocation, not just the mask, taking down every sandboxed bash
14
+ # call down to `echo`. That shipped in 0.48.8.
15
+ #
16
+ # `bubblewrap` is installed unpinned (BASELINE_APT_PACKAGES), so this behaviour
17
+ # can change under us on any base-image rebuild with no typeclaw commit. Wired
18
+ # into release.yml's merge-base job, which runs before the irreversible npm
19
+ # publish, so a bwrap that rejects our rendered command blocks the release.
20
+ #
21
+ # Asserts only the property we depend on — N masks over N distinct fds succeed
22
+ # and every target reads back empty. It deliberately does NOT assert that a
23
+ # SHARED fd fails: that pins upstream behaviour we neither control nor need.
24
+ #
25
+ # Usage: scripts/verify-mask-fd-sandbox.sh [image] [platform]
26
+ # image defaults to ghcr.io/typeclaw/typeclaw-base:<version-from-package.json>
27
+ # platform e.g. linux/amd64; defaults to the daemon's native platform
28
+ set -euo pipefail
29
+
30
+ IMAGE="${1:-}"
31
+ PLATFORM="${2:-}"
32
+ if [ -z "$IMAGE" ]; then
33
+ version="$(node -p "require('./package.json').version" 2>/dev/null || echo latest)"
34
+ IMAGE="ghcr.io/typeclaw/typeclaw-base:${version}"
35
+ fi
36
+
37
+ # Mirrors CANONICAL_AGENT_SECRET_FILES + CANONICAL_AGENT_RUNTIME_PRIVATE_FILES.
38
+ # The count is what matters here (one fd per mask); keep in sync if that grows.
39
+ runner='
40
+ set -u
41
+ d=/tmp/maskcheck
42
+ mkdir -p "$d"
43
+ for f in env secrets.json auth.json incidents.json; do printf CANARY > "$d/$f"; done
44
+
45
+ # The argv shape mirrors buildArgv()/appendMasks() in src/sandbox/build.ts:
46
+ # masks render after the broad parent bind, and the rendered commandString
47
+ # self-opens one /dev/null fd per masked file. Keep in sync if that changes.
48
+ set +e
49
+ out="$(bwrap --unshare-all \
50
+ --new-session --die-with-parent --clearenv \
51
+ --setenv PATH /usr/local/bin:/usr/bin:/bin --setenv HOME /tmp --setenv LANG C.UTF-8 \
52
+ --ro-bind /usr /usr --ro-bind /etc /etc --dev /dev --tmpfs /tmp \
53
+ --ro-bind-try /bin /bin --ro-bind-try /sbin /sbin --ro-bind-try /lib /lib --ro-bind-try /lib64 /lib64 \
54
+ --bind "$d" "$d" \
55
+ --ro-bind-data 3 "$d/env" \
56
+ --ro-bind-data 4 "$d/secrets.json" \
57
+ --ro-bind-data 5 "$d/auth.json" \
58
+ --ro-bind-data 6 "$d/incidents.json" \
59
+ bash -c "cat $d/env $d/secrets.json $d/auth.json $d/incidents.json" \
60
+ 3</dev/null 4</dev/null 5</dev/null 6</dev/null 2>/tmp/maskcheck.err)"
61
+ rc=$?
62
+ set -e
63
+
64
+ echo "bwrap: $(bwrap --version)"
65
+ if [ $rc -ne 0 ]; then
66
+ echo "MASK_BWRAP_FAILED rc=$rc"
67
+ cat /tmp/maskcheck.err
68
+ exit 1
69
+ fi
70
+ if [ -n "$out" ]; then
71
+ echo "MASK_LEAKED: masked files were readable: [$out]"
72
+ exit 1
73
+ fi
74
+ echo "MASK_CONTRACT_OK: 4 masks over 4 distinct fds, all empty"
75
+ '
76
+
77
+ echo "Image: $IMAGE${PLATFORM:+ ($PLATFORM)}"
78
+
79
+ # --pull=always plus an explicit platform, because the caller may have pulled
80
+ # several architectures under this one tag. The classic Docker image store maps
81
+ # a tag to exactly ONE image, so a preceding `docker pull --platform linux/amd64`
82
+ # followed by `--platform linux/arm64` leaves the tag on whichever came LAST.
83
+ # An unqualified `docker run` would then execute a foreign-arch image — and with
84
+ # no QEMU registered that dies on exec format, failing the release for a reason
85
+ # that has nothing to do with bwrap. Re-resolving the tag here keeps the check
86
+ # honest on both the classic and containerd image stores.
87
+ # --privileged so `bwrap --unshare-all` can actually build its namespaces here.
88
+ # The runners restrict namespace creation in layers, and each one aborts the
89
+ # invocation before a single mask is evaluated — so the step fails for reasons
90
+ # that say nothing about the contract under test: docker-default AppArmor denies
91
+ # the opening mount(NULL, "/", MS_SLAVE|MS_REC) ("Failed to make / slave"), and
92
+ # the loopback bring-up in the new netns fails RTM_NEWADDR "Operation not
93
+ # permitted" even with seccomp and AppArmor unconfined and NET_ADMIN added,
94
+ # because the restriction is on the user namespace that would confer it.
95
+ #
96
+ # This is scaffolding for a throwaway container running a known image inside the
97
+ # release pipeline, NOT a runtime capability grant — agent containers get
98
+ # seccomp=unconfined and nothing more. What the gate certifies is unchanged: the
99
+ # bwrap argv still mirrors buildArgv()/appendMasks(), and MASK_BWRAP_FAILED,
100
+ # MASK_LEAKED and MASK_CONTRACT_OK all still fail the release on a real break.
101
+ run_args=(--rm --pull=always --privileged)
102
+ if [ -n "$PLATFORM" ]; then
103
+ run_args+=(--platform "$PLATFORM")
104
+ fi
105
+
106
+ docker run "${run_args[@]}" "$IMAGE" bash -c "$runner"
@@ -407,6 +407,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
407
407
  stream: options.stream,
408
408
  allowBackgroundFromSubagent: options.allowBackgroundFromSubagent,
409
409
  coalescer: options.subagentCoalescer,
410
+ channelRouter: options.channelRouter,
410
411
  }),
411
412
  ]
412
413
  : [
@@ -449,6 +450,7 @@ export async function createSessionWithDispose(options: CreateSessionOptions = {
449
450
  permissions: options.permissions,
450
451
  stream: options.stream,
451
452
  coalescer: options.subagentCoalescer,
453
+ channelRouter: options.channelRouter,
452
454
  }),
453
455
  ...buildRoleGrantTools({
454
456
  agentDir: options.plugins?.agentDir,
@@ -862,6 +864,7 @@ export function buildSubagentOrchestrationTools(opts: {
862
864
  stream: Stream | undefined
863
865
  allowBackgroundFromSubagent?: boolean
864
866
  coalescer?: SubagentCoalescer
867
+ channelRouter?: ChannelRouter
865
868
  }): ToolDefinition[] {
866
869
  if (
867
870
  opts.liveRegistry === undefined ||
@@ -896,6 +899,12 @@ export function buildSubagentOrchestrationTools(opts: {
896
899
  liveRegistry: opts.liveRegistry,
897
900
  getOrigin: opts.getOrigin,
898
901
  callerSessionId: opts.parentSessionId,
902
+ ...(opts.channelRouter !== undefined
903
+ ? {
904
+ hasOutstandingReviewThreadCloseout: (sessionId: string) =>
905
+ opts.channelRouter?.hasOutstandingGithubReviewThreadCloseout?.(sessionId) ?? false,
906
+ }
907
+ : {}),
899
908
  ...(opts.permissions ? { permissions: opts.permissions } : {}),
900
909
  }),
901
910
  ]
@@ -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