typeclaw 0.45.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/README.md +1 -1
  2. package/package.json +3 -2
  3. package/src/agent/git-nudge.ts +2 -1
  4. package/src/agent/index.ts +67 -25
  5. package/src/agent/live-subagents.ts +18 -0
  6. package/src/agent/loop-guard.ts +208 -10
  7. package/src/agent/multimodal/index.ts +1 -1
  8. package/src/agent/multimodal/look-at.ts +78 -44
  9. package/src/agent/multimodal/looker.ts +151 -39
  10. package/src/agent/network/response-body.ts +26 -0
  11. package/src/agent/network/safe-http.ts +198 -0
  12. package/src/agent/plugin-tools.ts +438 -162
  13. package/src/agent/provider-error.ts +62 -4
  14. package/src/agent/restart/index.ts +61 -40
  15. package/src/agent/restart-handoff/index.ts +73 -4
  16. package/src/agent/retry-same-ref.ts +66 -0
  17. package/src/agent/reviewer-bash-policy.ts +42 -1
  18. package/src/agent/session-origin.ts +2 -0
  19. package/src/agent/subagent-drain.ts +117 -7
  20. package/src/agent/subagents.ts +77 -18
  21. package/src/agent/throttle-circuit.ts +25 -5
  22. package/src/agent/tool-error-remediation.ts +72 -0
  23. package/src/agent/tool-file-safety.ts +1050 -0
  24. package/src/agent/tools/channel-fetch-attachment.ts +10 -3
  25. package/src/agent/tools/channel-reply.ts +15 -1
  26. package/src/agent/tools/channel-send.ts +17 -1
  27. package/src/agent/tools/ddg.ts +16 -2
  28. package/src/agent/tools/post-github-review.ts +199 -0
  29. package/src/agent/tools/spawn-subagent.ts +21 -18
  30. package/src/agent/tools/webfetch/fetch.ts +143 -183
  31. package/src/agent/tools/webfetch/tool.ts +2 -3
  32. package/src/agent/tools/websearch.ts +23 -2
  33. package/src/agent/tools-without-local-file-operands.ts +27 -0
  34. package/src/agent/turn-runner.ts +109 -15
  35. package/src/bundled-plugins/backup/index.ts +2 -1
  36. package/src/bundled-plugins/backup/runner.ts +2 -1
  37. package/src/bundled-plugins/doc-render/render.ts +93 -12
  38. package/src/bundled-plugins/doc-render/skills/typeclaw-render-pdf/SKILL.md +13 -13
  39. package/src/bundled-plugins/github-cli-auth/effective-approval.ts +16 -6
  40. package/src/bundled-plugins/github-cli-auth/gh-command.ts +555 -15
  41. package/src/bundled-plugins/github-cli-auth/index.ts +131 -135
  42. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +138 -0
  43. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +2 -1
  44. package/src/bundled-plugins/memory/README.md +23 -11
  45. package/src/bundled-plugins/memory/append-tool.ts +15 -8
  46. package/src/bundled-plugins/memory/citations.ts +22 -9
  47. package/src/bundled-plugins/memory/dreaming.ts +13 -8
  48. package/src/bundled-plugins/memory/find-entry-tool.ts +4 -0
  49. package/src/bundled-plugins/memory/index.ts +0 -4
  50. package/src/bundled-plugins/memory/load-memory.ts +8 -3
  51. package/src/bundled-plugins/memory/provenance-index.ts +717 -0
  52. package/src/bundled-plugins/memory/provenance-sanitize.ts +40 -0
  53. package/src/bundled-plugins/memory/references/store-reference-tool.ts +4 -0
  54. package/src/bundled-plugins/memory/search-tool.ts +163 -60
  55. package/src/bundled-plugins/memory/stream-events.ts +2 -0
  56. package/src/bundled-plugins/memory/vector/hybrid.ts +126 -13
  57. package/src/bundled-plugins/researcher/write-report.ts +6 -3
  58. package/src/bundled-plugins/reviewer/index.ts +2 -2
  59. package/src/bundled-plugins/reviewer/reviewer.ts +10 -3
  60. package/src/bundled-plugins/reviewer/skills/code-review.ts +24 -9
  61. package/src/bundled-plugins/scout/scout.ts +8 -0
  62. package/src/bundled-plugins/security/index.ts +4 -4
  63. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +1 -0
  64. package/src/bundled-plugins/security/policies/private-surface-read.ts +220 -29
  65. package/src/bundled-plugins/security/policies/secret-exfil-read.ts +1 -0
  66. package/src/bundled-plugins/security/policies/ssrf.ts +29 -9
  67. package/src/channels/adapters/discord-bot-channel-resolver.ts +26 -14
  68. package/src/channels/adapters/discord-bot-thread-room.ts +44 -12
  69. package/src/channels/adapters/discord-bot.ts +91 -10
  70. package/src/channels/adapters/discord-channel-resolver.ts +91 -23
  71. package/src/channels/adapters/discord-id.ts +4 -0
  72. package/src/channels/adapters/discord-resolver-cache.ts +41 -0
  73. package/src/channels/adapters/discord.ts +57 -7
  74. package/src/channels/adapters/github/auth-app.ts +41 -12
  75. package/src/channels/adapters/github/index.ts +23 -11
  76. package/src/channels/adapters/github/review-submitter.ts +302 -0
  77. package/src/channels/adapters/kakaotalk-channel-resolver.ts +12 -1
  78. package/src/channels/adapters/kakaotalk-fetch-attachment.ts +8 -4
  79. package/src/channels/adapters/kakaotalk-typing.ts +127 -0
  80. package/src/channels/adapters/kakaotalk.ts +19 -0
  81. package/src/channels/adapters/slack-attachment-download.ts +71 -0
  82. package/src/channels/adapters/slack-bot.ts +19 -8
  83. package/src/channels/adapters/slack-classify.ts +21 -2
  84. package/src/channels/adapters/slack.ts +59 -7
  85. package/src/channels/adapters/telegram-bot.ts +18 -5
  86. package/src/channels/adapters/webex-bot.ts +8 -3
  87. package/src/channels/adapters/webex.ts +8 -3
  88. package/src/channels/fetch-attachment.ts +43 -0
  89. package/src/{bundled-plugins/github-cli-auth/approve-idempotency.ts → channels/github-review-verdict-coordinator.ts} +25 -1
  90. package/src/channels/github-token-bridge.ts +10 -3
  91. package/src/channels/manager.ts +9 -0
  92. package/src/channels/router.ts +568 -12
  93. package/src/channels/types.ts +28 -1
  94. package/src/cli/channel.ts +1 -1
  95. package/src/cli/init.ts +1 -1
  96. package/src/cli/model.ts +57 -7
  97. package/src/compose/stop.ts +17 -5
  98. package/src/config/config.ts +6 -6
  99. package/src/config/models-mutation.ts +13 -1
  100. package/src/config/providers.ts +176 -0
  101. package/src/container/start.ts +49 -10
  102. package/src/doctor/checks.ts +3 -1
  103. package/src/doctor/commit.ts +2 -1
  104. package/src/doctor/file-ownership.ts +52 -0
  105. package/src/dreams/git.ts +2 -1
  106. package/src/git/hookless.ts +5 -0
  107. package/src/git/reconcile-ignored.ts +18 -5
  108. package/src/git/secret-history.ts +371 -0
  109. package/src/git/system-commit.ts +12 -6
  110. package/src/init/dockerfile.ts +86 -5
  111. package/src/init/index.ts +17 -5
  112. package/src/init/models-dev.ts +4 -0
  113. package/src/init/validate-api-key.ts +2 -0
  114. package/src/mcp/tools.ts +16 -3
  115. package/src/permissions/builtins.ts +3 -1
  116. package/src/plugin/context.ts +2 -0
  117. package/src/plugin/index.ts +1 -0
  118. package/src/plugin/manager.ts +4 -0
  119. package/src/plugin/types.ts +21 -0
  120. package/src/run/index.ts +40 -0
  121. package/src/run/llm-fetch-observer.ts +188 -13
  122. package/src/sandbox/build.ts +37 -15
  123. package/src/sandbox/canonical-secrets.ts +18 -0
  124. package/src/sandbox/env-exposure.ts +80 -0
  125. package/src/sandbox/errors.ts +13 -6
  126. package/src/sandbox/hidden-paths.ts +102 -44
  127. package/src/sandbox/index.ts +22 -4
  128. package/src/sandbox/package-install.ts +3 -27
  129. package/src/sandbox/policy.ts +11 -25
  130. package/src/sandbox/privileged-runtime.ts +255 -0
  131. package/src/sandbox/session-tmp.ts +8 -2
  132. package/src/sandbox/writable-zones.ts +204 -140
  133. package/src/secrets/index.ts +8 -0
  134. package/src/secrets/refresh-provider-oauth.ts +128 -0
  135. package/src/server/command-runner.ts +48 -4
  136. package/src/server/index.ts +4 -0
  137. package/src/skills/typeclaw-channel-github/SKILL.md +49 -56
  138. package/src/skills/typeclaw-claude-code/SKILL.md +24 -60
  139. package/src/skills/typeclaw-claude-code/references/auth-flow.md +17 -158
  140. package/src/skills/typeclaw-codex-cli/SKILL.md +19 -49
  141. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +17 -154
  142. package/src/skills/typeclaw-config/SKILL.md +5 -5
  143. package/src/skills/typeclaw-config/references/recommended-mounts.md +24 -24
  144. package/src/skills/typeclaw-github-contributing/SKILL.md +23 -26
  145. package/src/skills/typeclaw-memory/SKILL.md +9 -3
  146. package/src/skills/typeclaw-permissions/SKILL.md +19 -15
  147. package/typeclaw.schema.json +20 -0
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: typeclaw-channel-github
3
- description: Use this skill BEFORE every `channel_reply` or `channel_send` call whose adapter is `github`, AND before composing replies to GitHub-originated inbounds, AND before opening new issues or PRs with `gh`, AND ALWAYS when you are asked to review a PR — whether the inbound says "requested your review on PR #N" / "requested a review from team @… on PR #N", or a human asks for a review in plain language in an issue/PR body or comment ("@bot review this", "can you take a look at #123"). On a review request you delegate the analysis to the `reviewer` subagent, which produces line-anchored findings, then you post them as an inline review via `gh api`. ALWAYS settle PR authorship first (triage #0): on a PR **you** opened you are the CONTRIBUTOR/author, not its reviewer — "address the review" / "리뷰 반영" / "fix the feedback" / a `CHANGES_REQUESTED` on your own PR means change the code, push, and reply, NOT spawn the reviewer or post a formal verdict; you never review your own PR. The reviewer persona is for other people's PRs only. GitHub renders **real markdown** — `**bold**`, `## headings`, `| tables |`, fenced code blocks, and `inline code` all render natively. Use rich markdown freely. GitHub cannot send file attachments via API — do not call `channel_send` with attachments on github chats. GitHub has no typing indicator. PR review threads use `thread` keyed on the root comment id; reply to a thread to stay in it, or omit `thread` to post a top-level issue/PR comment. When a review comment **you authored** gets addressed — the author pushed a fix or replied that resolves it — verify the fix at the PR's head SHA and then resolve the thread by acknowledging with `channel_reply({ …, resolve_review_thread: true })`, which resolves the thread before posting the reply (see "Resolving review threads you authored" below); resolving is the close-out that tells the author the concern is settled. To open new issues or PRs use the `gh` CLI — `GH_TOKEN` is pre-set by the adapter. Read this skill before composing anything on GitHub.
3
+ description: Use this skill BEFORE every `channel_reply` or `channel_send` call whose adapter is `github`, AND before composing replies to GitHub-originated inbounds, AND before opening new issues with model-driven `gh` or preparing a PR for host-stage operator creation, AND ALWAYS when you are asked to review a PR — whether the inbound says "requested your review on PR #N" / "requested a review from team @… on PR #N", or a human asks for a review in plain language in an issue/PR body or comment ("@bot review this", "can you take a look at #123"). On a review request you delegate the analysis to the `reviewer` subagent, which produces line-anchored findings, then you post them as a formal review via `post_github_review`. ALWAYS settle PR authorship first (triage #0): on a PR **you** opened you are the CONTRIBUTOR/author, not its reviewer — "address the review" / "리뷰 반영" / "fix the feedback" / a `CHANGES_REQUESTED` on your own PR means ask the operator for host-stage checkout, change and commit the code, ask the operator to push, and reply, NOT spawn the reviewer or post a formal verdict; you never review your own PR. The reviewer persona is for other people's PRs only. GitHub renders **real markdown** — `**bold**`, `## headings`, `| tables |`, fenced code blocks, and `inline code` all render natively. Use rich markdown freely. GitHub cannot send file attachments via API — do not call `channel_send` with attachments on github chats. GitHub has no typing indicator. PR review threads use `thread` keyed on the root comment id; reply to a thread to stay in it, or omit `thread` to post a top-level issue/PR comment. When a review comment **you authored** gets addressed — the author pushed a fix or replied that resolves it — verify the fix at the PR's head SHA and then resolve the thread by acknowledging with `channel_reply({ …, resolve_review_thread: true })`, which resolves the thread before posting the reply (see "Resolving review threads you authored" below); resolving is the close-out that tells the author the concern is settled. Model-driven `gh issue create` may open new issues with a command-scoped credential brokered by the adapter. PR creation, checkout, and push are host-stage operator actions. Read this skill before composing anything on GitHub.
4
4
  ---
5
5
 
6
6
  GitHub renders normal Markdown in issues, PRs, discussions, and review comments. Use headings, lists, tables, fenced code blocks, links, and inline code when they improve clarity.
@@ -24,10 +24,10 @@ Before you pick an action, classify the inbound. Skipping this step is how a PR
24
24
  gh pr view <N> --repo owner/repo --json author --jq '.author.login'
25
25
  ```
26
26
 
27
- - **The PR author is you (`<your-login>`).** You are the **contributor/author** on this PR, not its reviewer. Feedback on it — a review, a "리뷰 반영 부탁드려요" / "address the review" / "please apply the feedback" / "fixed?" comment, a `CHANGES_REQUESTED` someone else left — is yours to **address as the author**: read it, change the code, push, and reply. Go to the **contributor flow** ("When the PR is yours"). **You never review your own PR**, and you never spawn the `reviewer` subagent on it — GitHub does not even let an author formally review their own PR, so an attempt produces a self-addressed "review" comment, which is the exact persona-confusion bug to avoid. Gates 1–2 below (review obligations / review requests) describe the _reviewer_ persona and **do not apply when the PR is yours** — skip straight to the contributor flow.
28
- - **The PR author is someone else.** You may be its reviewer. Continue to gate 1.
27
+ - **The PR author is you (`<your-login>`).** You are the **contributor/author** on this PR, not its reviewer. Feedback on it — a review, a "리뷰 반영 부탁드려요" / "address the review" / "please apply the feedback" / "fixed?" comment, a `CHANGES_REQUESTED` someone else left — is yours to **address as the author**: read it, ask the operator for the required host-stage checkout, change and commit the code, ask the operator to push, and reply. Go to the **contributor flow** ("When the PR is yours"). **You never review your own PR**, and you never spawn the `reviewer` subagent on it — GitHub does not even let an author formally review their own PR, so an attempt produces a self-addressed "review" comment, which is the exact persona-confusion bug to avoid. Gates 1–2 below (review obligations / review requests) describe the _reviewer_ persona and **do not apply when the PR is yours** — skip straight to the contributor flow.
28
+ - **The PR author is someone else.** You may be its reviewer. Continue to gate 1.
29
29
 
30
- This gate is first because everything after it assumes the reviewer persona. "Address the review" sounds identical whether you wrote the PR or someone else did; only the author check disambiguates, and getting it wrong is what makes the agent review its own work.
30
+ This gate is first because everything after it assumes the reviewer persona. "Address the review" sounds identical whether you wrote the PR or someone else did; only the author check disambiguates, and getting it wrong is what makes the agent review its own work.
31
31
 
32
32
  1. **(Someone else's PR.) Do I have an unresolved blocking obligation on it?** On any `pr:N` inbound, before anything else, check whether you owe this PR a verdict you have not yet landed. Check **both** signals below — checking only formal review state misses the very failure this gate exists to catch, because a prior block may never have become formal state:
33
33
  - **Formal review state.** Run the step-1 re-review query in the PR review flow (`gh api --paginate --slurp /repos/owner/repo/pulls/<N>/reviews --jq '…'` filtered to `{CHANGES_REQUESTED, APPROVED}`). If your latest **blocking decision** is `CHANGES_REQUESTED`, you have a live sticky block.
@@ -47,16 +47,16 @@ Before you pick an action, classify the inbound. Skipping this step is how a PR
47
47
 
48
48
  Every GitHub inbound lands on a `chat` keyed by its subject: `issue:N`, `pr:N`, or `discussion:N`. **Run the triage above first.** Only if no triage branch matched do you pick an action from this table. The default action for anything addressed to you is a normal `channel_reply` in that thread; the **PR review flow** is the exception that requires delegation.
49
49
 
50
- | Inbound | Looks like | What to do |
51
- | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
52
- | **New issue** (`issue:N`) | A freshly opened issue body. | Triage or answer it. `channel_reply` on `issue:N`. Open follow-up issues/PRs with `gh` if needed. |
53
- | **Issue comment** (`issue:N`) | A comment on an issue. | Reply in the issue thread with `channel_reply`. |
54
- | **PR conversation comment** (`pr:N`, no `thread`) | A comment on a PR's main conversation (GitHub models PR comments as issue comments). | Reply on the PR with `channel_reply`. **If the text asks you to review → go to the PR review flow.** |
55
- | **PR review-thread reply** (`pr:N`, `thread` set) | A reply on an existing inline review comment thread. | Stay in the thread: `channel_reply` with `thread` kept as-is. **If it addresses a comment you authored → verify and resolve the thread (below).** |
56
- | **A submitted review** (`pr:N`) | Someone submitted a formal review (approve / changes / comment) on a PR. | **If the PR is yours (triage #0) → contributor flow:** address the feedback, then reply. Otherwise react if a response is warranted. `channel_reply` on `pr:N`. |
57
- | **Feedback on your own PR** (`pr:N`, author = `<your-login>`) | A review, a `CHANGES_REQUESTED`, or an "address the review / fixed?" comment on a PR **you** opened. | **Contributor flow** ("When the PR is yours"). Address the feedback as the author — never review or formally approve your own PR. |
58
- | **New discussion / discussion comment** (`discussion:N`) | A discussion thread or a comment in one. | Reply with `channel_reply` on `discussion:N`. |
59
- | **Review requested** (`pr:N`) | See "When you are being asked to review" below. | **PR review flow.** |
50
+ | Inbound | Looks like | What to do |
51
+ | ------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
52
+ | **New issue** (`issue:N`) | A freshly opened issue body. | Triage or answer it. `channel_reply` on `issue:N`. Model-driven `gh issue create` may open a follow-up issue; prepare any follow-up PR for host-stage operator creation. |
53
+ | **Issue comment** (`issue:N`) | A comment on an issue. | Reply in the issue thread with `channel_reply`. |
54
+ | **PR conversation comment** (`pr:N`, no `thread`) | A comment on a PR's main conversation (GitHub models PR comments as issue comments). | Reply on the PR with `channel_reply`. **If the text asks you to review → go to the PR review flow.** |
55
+ | **PR review-thread reply** (`pr:N`, `thread` set) | A reply on an existing inline review comment thread. | Stay in the thread: `channel_reply` with `thread` kept as-is. **If it addresses a comment you authored → verify and resolve the thread (below).** |
56
+ | **A submitted review** (`pr:N`) | Someone submitted a formal review (approve / changes / comment) on a PR. | **If the PR is yours (triage #0) → contributor flow:** address the feedback, then reply. Otherwise react if a response is warranted. `channel_reply` on `pr:N`. |
57
+ | **Feedback on your own PR** (`pr:N`, author = `<your-login>`) | A review, a `CHANGES_REQUESTED`, or an "address the review / fixed?" comment on a PR **you** opened. | **Contributor flow** ("When the PR is yours"). Address the feedback as the author — never review or formally approve your own PR. |
58
+ | **New discussion / discussion comment** (`discussion:N`) | A discussion thread or a comment in one. | Reply with `channel_reply` on `discussion:N`. |
59
+ | **Review requested** (`pr:N`) | See "When you are being asked to review" below. | **PR review flow.** |
60
60
 
61
61
  ### When the PR is yours — addressing review feedback (contributor)
62
62
 
@@ -70,27 +70,33 @@ The flow:
70
70
  1. **Read the feedback at the current head.** Pull the review comments and any `CHANGES_REQUESTED` summary so you know exactly what is being asked.
71
71
 
72
72
  ```sh
73
- gh pr view <N> --repo owner/repo --json reviews,comments,headRefOid \
74
- --jq '{reviews: [.reviews[] | {author: .author.login, state, body}], head: .headRefOid}'
73
+ gh pr view <N> --repo owner/repo --json reviews,comments,headRefOid --jq '{reviews: [.reviews[] | {author: .author.login, state, body}], head: .headRefOid}'
75
74
  gh api /repos/owner/repo/pulls/<N>/comments --jq '[.[] | {path, line, user: .user.login, body}]'
76
75
  ```
77
76
 
78
- 2. **Make the changes on the PR's branch.** Check out the PR's head branch, make the minimal fixes the feedback calls for, and push. Committing and pushing to your own branch is `typeclaw-git` territory — follow it for commit hygiene. Do **not** open a _new_ PR to fix your existing one; push to the same branch so the open PR updates in place.
77
+ 2. **Update the PR's branch with host-stage help.** Model-driven bash cannot run `gh pr checkout` or authenticated `git push`: both may execute local hooks while carrying reusable credentials. Ask the operator to run the checkout from the host-stage repository directory:
79
78
 
80
79
  ```sh
81
80
  gh pr checkout <N> --repo owner/repo
82
- # …edit files, then commit + push per typeclaw-git…
83
81
  ```
84
82
 
83
+ After the operator confirms the checkout, make the minimal fixes and commit them locally with `typeclaw-git` hygiene. Then ask the operator to push that same branch from the host stage:
84
+
85
+ ```sh
86
+ git push
87
+ ```
88
+
89
+ Do **not** open a _new_ PR to fix your existing one; the operator pushes to the same branch so the open PR updates in place.
90
+
85
91
  If a point is a genuine disagreement (the reviewer is mistaken, or the behavior is intentional), don't silently change it — reply in the thread with your reasoning instead.
86
92
 
87
93
  3. **Reply to the feedback as the author.** After pushing, acknowledge each addressed thread with a normal `channel_reply` (keep `thread` set to stay in the inline thread; omit it for the PR conversation). Say what you changed ("Fixed — switched to the wiki-link form in `abc1234`") or why you didn't ("Left as-is — this path can't be null because …"). Keep it short.
88
94
  - **Do not resolve the threads.** On your own PR the open inline threads were authored by your **reviewer**, not by you — and the base principle is _whoever opened the thread closes it_. Resolving is the reviewer's call once they're satisfied; the runtime enforces this (it only lets you resolve threads whose root comment **you** authored). Push the fix, reply, and leave the thread for the reviewer to close.
89
95
  - **Do not post a verdict.** "LGTM", "Approved", "Request changes" are reviewer words. As the author you reply in plain prose; you never emit a review verdict on your own PR.
90
96
 
91
- 4. **If CI is failing on your PR**, that's also contributor work: read the failing check, fix the cause on the branch, and push. You can't always read another system's CI logs — if you can't, say so and ask for the error rather than guessing.
97
+ 4. **If CI is failing on your PR**, that's also contributor work: read the failing check, fix the cause on the checked-out branch, commit locally, then ask the operator to run `git push` from the host stage. You can't always read another system's CI logs — if you can't, say so and ask for the error rather than guessing.
92
98
 
93
- That's the whole contributor loop: read feedback → fix on the branch → push → reply. No subagent, no formal review, no thread resolution.
99
+ That's the whole contributor loop: read feedback → operator checks out at the host stage → fix and commit locally → operator pushes at the host stage → reply. No subagent, no formal review, no thread resolution.
94
100
 
95
101
  ### When you are being asked to review
96
102
 
@@ -160,7 +166,12 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
160
166
  </review>
161
167
  ```
162
168
 
163
- 4. **Translate findings into a `gh api` review payload.** Each `<finding>` with `severity` of `blocker`, `concern`, or `nit` and a `location="path:line"` becomes one entry in `comments[]`. Compose the inline `body` from the reviewer's `<issue>` + `<evidence>` + `<suggestion>` verbatim (modulo markdown). Findings whose `location` is `general` (no file:line anchor) go into the top-level review `body` instead. **Skip `praise` findings when building `comments[]`** — if you want to surface them, weave them into the top-level `body`.
169
+ **If the reviewer could not complete — do not go silent, and do not fabricate a verdict.** Two shapes signal an incomplete review: a `subagent_output` result of _"reviewer completed in Nms with no final message"_ (no `<review>` block at all), or a `<review>` whose `<verdict>` is the runtime sentinel **`incomplete-review-not-a-verdict`** — the honest fallback the runtime installs when the reviewer exhausted its retries without reaching a verdict (its `<summary>` opens with `INCOMPLETE REVIEW — NOT A VERDICT`). Both mean the analysis did not land; a real verdict was never reached. Handle them identically:
170
+ - **This is NOT a real verdict — never map it to `APPROVE`/`REQUEST_CHANGES`/`COMMENT`.** In particular, the re-review override below (which upgrades a `comment` result to a decisive `approve`/`request-changes`) does **not** apply here: an incomplete review must never clear or re-assert a block, because no review actually happened. Leave existing review state untouched.
171
+ - **Re-spawn the reviewer once** (step 2) with the same target — a fresh `deep` context usually completes; if it now returns a real `<review>` block, post it normally.
172
+ - **If the re-spawn is still incomplete**, post a brief, honest `channel_reply` on the PR — e.g. _"리뷰를 자동 완료하지 못했어요 (reviewer returned no verdict). 다시 시도하거나 직접 확인이 필요합니다."_ — and remove your in-review label. An honest "couldn't complete the review" comment is the correct fallback; silence after you engaged, or a fabricated formal verdict, is not.
173
+
174
+ 4. **Translate findings into a `post_github_review` call.** Each `<finding>` with `severity` of `blocker`, `concern`, or `nit` and a `location="path:line"` becomes one entry in `comments[]`. Compose the inline `body` from the reviewer's `<issue>` + `<evidence>` + `<suggestion>` verbatim (modulo markdown). Findings whose `location` is `general` (no file:line anchor) go into the top-level review `body` instead. **Skip `praise` findings when building `comments[]`** — if you want to surface them, weave them into the top-level `body`.
164
175
 
165
176
  **The verdict and the inline comments are independent. The verdict sets only the `event` field; it never decides whether you post `comments[]`.** Whenever there is at least one actionable finding (`blocker`/`concern`/`nit`) with a `location="path:line"`, you MUST submit a formal review via `POST /pulls/<N>/reviews` carrying those findings in `comments[]` — including when the verdict is `approve`. An `approve` with three nits is still a formal `APPROVE` review with three inline comments, **not** a plain approval and **not** a flattened summary. Collapsing inline findings into a single `channel_reply` or issue comment loses the line anchors the reviewer worked to produce.
166
177
 
@@ -178,7 +189,7 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
178
189
  - **Prior block was a formal `CHANGES_REQUESTED`.** It is sticky: **only** a fresh `APPROVE` from you, or a dismissal of your prior review, clears it. A plain issue comment does **not** clear it, and — critically — **neither does a `COMMENT` review.**
179
190
  - **Prior block was a flat comment** (no formal `CHANGES_REQUESTED` exists). There is no sticky GitHub state to clear, but the obligation is still yours to discharge as a **formal** review so the verdict finally lands as review state: submit `APPROVE` (resolved, approval enabled) or `REQUEST_CHANGES` (not resolved). Do not discharge a flat-comment block with another flat comment — that re-strands the verdict, the original bug.
180
191
 
181
- So even if the reviewer returns zero actionable findings, do **not** take the `comment` → top-level-comment branch below for a re-review. The reviewer's skill is instructed not to return `comment` on a re-review; if it does anyway despite a reachable diff, prefer `approve` when the prior blockers are visibly resolved in the diff, otherwise `request-changes` — and say which in your reasoning. Resolve the re-review by verdict:
192
+ So even if the reviewer returns zero actionable findings, do **not** take the `comment` → top-level-comment branch below for a re-review. The reviewer's skill is instructed not to return `comment` on a re-review; if it does anyway despite a reachable diff, prefer `approve` when the prior blockers are visibly resolved in the diff, otherwise `request-changes` — and say which in your reasoning. **This override applies only to a real reviewer verdict — never to the incomplete-review fallback** (`<verdict>incomplete-review-not-a-verdict</verdict>`, or no `<review>` block at all): that is not a verdict and must never be upgraded to `approve`/`request-changes`, which would let a review that never ran clear or re-assert a block (see step 3's incomplete-review branch). Resolve the re-review by verdict:
182
193
  - **`request-changes`** — submit a fresh `REQUEST_CHANGES` review (re-asserts the block with the new findings). Straightforward.
183
194
  - **`approve`, approval enabled** — submit `APPROVE`. This clears the block.
184
195
  - **`approve`, approval disabled (`channels.github.review.approve: false`)** — you cannot `APPROVE`. How you close out depends on the prior block's form. **If the prior block was a flat comment** (no formal `CHANGES_REQUESTED`), there is no sticky state to clear: submit a `COMMENT` review carrying the `<summary>` so the verdict lands as review state, and you are done — nothing to dismiss. **If the prior block was a formal `CHANGES_REQUESTED`**, a `COMMENT` review will **not** clear the sticky block, so the PR would stay blocked by your stale review; clear it explicitly by **dismissing your own prior `CHANGES_REQUESTED` review**. Grab that review's `id` by re-running the step-1 formal-review query with the trailing filter changed from `| .state` to `| {state, id}` (same `select`), take the entry whose `state` is `CHANGES_REQUESTED`, then:
@@ -189,12 +200,10 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
189
200
 
190
201
  This transitions your review to `DISMISSED` and unblocks the PR without an approval. It needs the bot's installation to have **write** access (or to be on the branch's "who can dismiss reviews" list); if the dismissal returns 403, the block cannot be cleared under this policy — post the `<summary>` as a `COMMENT` review and say plainly in the body that the prior changes-request stands until a human dismisses it, rather than implying the PR is unblocked.
191
202
 
192
- Then submit the review. **Write the JSON payload to a file with the `write` tool, then run a single bare `gh api --input <file>`** — two steps:
193
-
194
- First write `/tmp/review-<N>.json` (via the `write` tool, not bash) — `/tmp` is per-session scratch, and the `<N>` keeps concurrent reviews in one session from colliding. **Every `gh api --input` payload — review JSON, dismissal JSON, top-level issue-comment JSON — is throwaway scratch and MUST be written under `/tmp/`, never the workspace/agent folder.** A path with no leading `/tmp/` (e.g. a bare `review.json`, `review_comment.json`, or `review-<N>-approve.json`) lands in the agent root and gets force-committed by the backup loop, littering the repo with review payloads. Always prefix the path with `/tmp/`; never write a `*.json` scratch file to the workspace:
203
+ Then submit the review with the first-class tool:
195
204
 
196
205
  ```json
197
- {
206
+ post_github_review({
198
207
  "event": "COMMENT",
199
208
  "body": "<reviewer's <summary> goes here>",
200
209
  "comments": [
@@ -206,38 +215,22 @@ The `reviewer` subagent is the analyst; you are the integration layer between it
206
215
  },
207
216
  { "path": "src/bar.ts", "line": 10, "side": "RIGHT", "body": "..." }
208
217
  ]
209
- }
210
- ```
211
-
212
- Then post it:
213
-
214
- ```sh
215
- gh api -X POST /repos/owner/repo/pulls/<N>/reviews --input /tmp/review-<N>.json
218
+ })
216
219
  ```
217
220
 
218
- **A repo-targeting `gh` command must be a single bare `gh` invocation — no pipes, `;`, `&&`, heredocs, or command substitution.** The `github-cli-auth` plugin injects the GitHub App token into the command's environment, so any sibling/upstream stage in a pipeline would inherit a live token; the runtime blocks those shapes. That is why the old `cat <<'JSON' | gh api --input -` heredoc-pipe no longer works: write the JSON to a file and feed it with `--input <file>` instead. Do **not** use `-f body=...` or `-F 'comments[][body]=...'`: those go through shell argument parsing, so backticks trigger command substitution. The file passes the JSON through untouched — backticks, newlines, and `${...}` all survive verbatim. The same file-then-`--input` pattern applies to any `gh api` POST whose body contains backticks, embedded newlines, or shell metacharacters.
219
-
220
- Anchor mechanics: `line` is a line number **in the file**, not a position in the diff. `side: RIGHT` is the new revision (default for additions); `side: LEFT` is the old revision (use for comments on removed lines). For multi-line comments, also set `start_line` and `start_side` (same semantics). If you need to read whole files at the PR's head SHA to validate an anchor before posting, use `gh api /repos/owner/repo/contents/<path>?ref=<headRefOid>`.
221
+ Anchor mechanics: `line` is a line number **in the file**, not a position in the diff. `side: RIGHT` is the new revision (default for additions); `side: LEFT` is the old revision (use for comments on removed lines). For multi-line comments, also set `start_line` and `start_side` (same semantics). The tool resolves the head SHA, validates anchors against the complete PR diff, moves out-of-diff findings into the top-level body, enforces approval policy, and verifies the exact returned review id/state. Its successful receipt is proof that the formal review landed. On failure, fix the payload or policy issue and retry; never post a flat comment claiming the review succeeded.
221
222
 
222
- 5. **Verify the review actually landed before announcing it.** The `gh api` call can fail silently from the model's perspective — a permission denial, a bad `line` anchor, or a malformed payload returns an error you must not paper over. After submitting, confirm the review exists:
223
+ 5. **The decoy reviewer is dropped for you — no action needed.** Under **GitHub App** auth, the adapter automatically removes the decoy reviewer from the PR's requested-reviewers list the moment your formal review lands (it reacts to your own `pull_request_review.submitted` webhook). Why this matters: GitHub auto-adds **you** (the App account) to the PR's reviewers when your review posts, but the **decoy** account would otherwise stay pinned as a perpetual "review requested", as if the review never happened. You do **not** need to issue a `DELETE /requested_reviewers` yourself — and you should not, since it would race the adapter's own cleanup. The removal is self-loop-safe: the adapter's `DELETE` is authenticated as the App, so the `review_request_removed` webhook carries your bot actor (`slug[bot]`) as `sender`, which the classifier drops (see "Self-loop safety" below). This is a no-op under **PAT** auth (no decoy) and for **plain-language**/**team** requests (no decoy user was placed). See [GitHub decoy reviewer](/docs/internals/github-decoy-reviewer).
223
224
 
224
- ```sh
225
- gh api /repos/owner/repo/pulls/<N>/reviews --jq '.[-1] | {id, state, user: .user.login}'
226
- ```
227
-
228
- The returned `id`/`state` is your proof the formal review posted. If the call errored or the review is absent, do **not** fall back to a top-level `channel_reply` that _claims_ a review was posted — fix the payload (most often a `line` that isn't part of the diff; re-anchor it or move that finding to the top-level `body`) and resubmit. A trace reply that says "Posted review" when no review exists is worse than silence.
229
-
230
- 6. **The decoy reviewer is dropped for you — no action needed.** Under **GitHub App** auth, the adapter automatically removes the decoy reviewer from the PR's requested-reviewers list the moment your formal review lands (it reacts to your own `pull_request_review.submitted` webhook). Why this matters: GitHub auto-adds **you** (the App account) to the PR's reviewers when your review posts, but the **decoy** account would otherwise stay pinned as a perpetual "review requested", as if the review never happened. You do **not** need to issue a `DELETE /requested_reviewers` yourself — and you should not, since it would race the adapter's own cleanup. The removal is self-loop-safe: the adapter's `DELETE` is authenticated as the App, so the `review_request_removed` webhook carries your bot actor (`slug[bot]`) as `sender`, which the classifier drops (see "Self-loop safety" below). This is a no-op under **PAT** auth (no decoy) and for **plain-language**/**team** requests (no decoy user was placed). See [GitHub decoy reviewer](/docs/internals/github-decoy-reviewer).
231
-
232
- 7. **End the turn with `skip_response`, not a trace reply.** The formal review from step 4 already landed _in this PR_ — it carries the summary, the verdict, and the inline comments. A `channel_reply` here does **not** go to a separate operator channel; on GitHub it posts another public comment on the same PR. A one-line "Posted review on PR #N: …" narrated into the PR thread is meta-commentary addressed to a phantom operator, and it reads absurdly next to the review it claims to point at. So once step 5 confirms the review exists, call `skip_response({ reason: "review posted via gh api" })` to close the turn silently. Only fall back to `channel_reply` when there was **no** formal review to post — the zero-actionable-findings branch below uses `channel_reply`/issue comments _as_ the substantive reply.
225
+ 6. **End the turn with `skip_response`, not a trace reply.** The formal review from step 4 already landed _in this PR_ — it carries the summary, the verdict, and the inline comments. A `channel_reply` here does **not** go to a separate operator channel; on GitHub it posts another public comment on the same PR. A one-line "Posted review on PR #N: …" narrated into the PR thread is meta-commentary addressed to a phantom operator, and it reads absurdly next to the review it claims to point at. So once `post_github_review` confirms success, call `skip_response({ reason: "review posted via post_github_review" })` to close the turn silently. Only fall back to `channel_reply` when there was **no** formal review to post — the zero-actionable-findings branch below uses `channel_reply` as the substantive reply.
233
226
 
234
227
  ### Zero actionable findings
235
228
 
236
229
  A finding is "actionable" if its severity is `blocker`, `concern`, or `nit`. The inline-review post in step 4 applies whenever the actionable count is **at least one**. When the reviewer returns **exactly zero** actionable findings (only `praise`, or none), there is nothing to anchor inline — handle by verdict:
237
230
 
238
- - `approve` → post a plain `APPROVE` with the `<summary>` as the review body (no `comments[]` array). **Post the `<summary>` verbatim — do not pad it back into a play-by-play.** The reviewer's contract already makes the summary a terse, author-facing verdict justification (no process narration, no "I loaded the X skill", no recap of what the PR does); your job is to forward it, not re-expand it. **This is still a formal review via `POST /pulls/<N>/reviews`, NOT a `channel_reply`.** A zero-findings approval is the single most common place this goes wrong: with nothing to anchor inline, the model is tempted to just `channel_reply({ text: "Approved …" })` and end the turn. That posts a plain PR comment and leaves the PR **"awaiting review"** with no approval — the verdict never reaches GitHub's review API. Never start a top-level `channel_reply` on a `pr:N` with "Approved" / "LGTM" / "Request changes": those are verdicts, and verdicts are always formal reviews. Submit the `APPROVE` via `gh api`, confirm it landed (step 5), then `skip_response`. **If the operator approval policy above disabled approval, submit a `COMMENT` review instead — same `<summary>` as the review body, `event: "COMMENT"`, no `comments[]` array. Keep it a formal review, not a top-level issue comment, so the review metadata and flow are preserved.** (Re-review caveat: a `COMMENT` review does **not** clear a sticky `CHANGES_REQUESTED` block. If this is a re-review under approval-disabled policy, follow the step-4 re-review branch — dismiss your prior review — instead of relying on this `COMMENT`.)
239
- - `comment` → post the summary as a top-level PR comment via `gh api -X POST /repos/.../issues/<N>/comments`, feeding the body from a `/tmp/` scratch file: write `/tmp/review-comment-<N>.json` (e.g. `{ "body": "<summary>" }`) with the `write` tool, then `gh api -X POST /repos/owner/repo/issues/<N>/comments --input /tmp/review-comment-<N>.json`. As with the review payload, this scratch file goes under `/tmp/`, **never** a bare `review_comment.json` in the workspace — the file-then-`--input` shape also keeps backticks/newlines in the summary from being mangled by shell parsing. Submit an empty review instead of this comment only when a formal review is required. **Exception — re-reviews:** if this is a re-review (you have an unresolved blocking obligation — a formal `CHANGES_REQUESTED` **or** an unretracted flat-comment blocker), a top-level comment discharges neither. Do not use this branch; resolve it via the step-4 re-review branch (`APPROVE` if resolved and approval is enabled, the dismissal endpoint if a formal block is resolved but approval is disabled, `REQUEST_CHANGES` if not resolved).
240
- - `request-changes` → submit `REQUEST_CHANGES` with the `<summary>` as the review body and no `comments[]` array. This combination is rare (the reviewer's contract says `request-changes` requires at least one blocker or load-bearing concern); if it happens, faithfully encode the verdict and trust the reviewer's reasoning is in the summary.
231
+ - `approve` → call `post_github_review({ event: "APPROVE", body: "<summary>" })`. **Post the `<summary>` verbatim — do not pad it back into a play-by-play.** The tool enforces approval policy and verifies the formal review. Never replace it with an "Approved"/"LGTM" `channel_reply`, which leaves GitHub awaiting a formal review.
232
+ - `comment` → post the summary as the substantive top-level PR reply with `channel_reply`. **Exception — re-reviews:** if an unresolved blocking obligation exists, a top-level comment discharges neither form of block. Use `post_github_review` to land a fresh formal verdict instead.
233
+ - `request-changes` → call `post_github_review({ event: "REQUEST_CHANGES", body: "<summary>" })`. This combination is rare; faithfully encode the reviewer's verdict.
241
234
 
242
235
  The bundled `agent-browser` is **not** for PR reviews — `gh api` is faster and more reliable. Only use the browser when the API genuinely can't reach what you need.
243
236
 
@@ -285,7 +278,7 @@ Prefer the flag above. Reach for the raw mutation only when you need to resolve
285
278
  1. **Find the node id of the thread you authored.** Query the PR's review threads and pick the one whose root comment is yours and matches the `thread` you're replying in:
286
279
 
287
280
  ```sh
288
- gh api graphql -f query='query($owner:String!,$name:String!,$number:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved comments(first:1){nodes{databaseId author{login}}}}}}}}' -F owner=OWNER -F name=REPO -F number=N
281
+ gh api graphql -R OWNER/REPO -f query='query($owner:String!,$name:String!,$number:Int!,$after:String){repository(owner:$owner,name:$name){pullRequest(number:$number){reviewThreads(first:100,after:$after){pageInfo{hasNextPage endCursor}nodes{id isResolved comments(first:1){nodes{databaseId author{login}}}}}}}}' -F owner=OWNER -F name=REPO -F number=N
289
282
  ```
290
283
 
291
284
  Match on the root comment: its `comments.nodes[0].databaseId` equals the root comment id (the `thread` value the inbound carried), and `author.login` is you. Skip threads already `isResolved: true`.
@@ -295,7 +288,7 @@ Prefer the flag above. Reach for the raw mutation only when you need to resolve
295
288
  2. **Resolve it** with the node id from step 1:
296
289
 
297
290
  ```sh
298
- gh api graphql -f query='mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{id isResolved}}}' -F threadId=PRRT_xxx
291
+ gh api graphql -R OWNER/REPO -f query='mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{id isResolved}}}' -F threadId=PRRT_xxx
299
292
  ```
300
293
 
301
294
  The returned `isResolved: true` is your proof it landed. As with every repo-targeting `gh` call, this is a **single bare `gh` invocation** — no pipes, `;`, `&&`, heredocs, or command substitution (the `github-cli-auth` plugin injects the App token into the command's environment; a pipeline would leak it). `-F` passes the id as a typed variable, so there is no shell-metacharacter hazard for the simple id/number values here.
@@ -306,17 +299,17 @@ Resolving your own thread is safe from the self-response loop. The `pull_request
306
299
 
307
300
  ## Opening new issues and PRs
308
301
 
309
- The `gh` CLI is pre-authenticated via `GH_TOKEN` (injected by the adapter at startup). Use it to open new issues or PRs:
302
+ TypeClaw brokers a command-scoped credential only to a supported, statically repo-targeted `gh` invocation. Do not inspect or assume a process-wide `GH_TOKEN`. Model-driven bash can open an issue with the narrow form below:
310
303
 
311
304
  ```sh
312
305
  # Open a new issue
313
- gh issue create --repo owner/repo --title "Bug: ..." --body "..."
306
+ gh issue create --repo owner/repo --title 'Bug: ...' --body '...'
314
307
 
315
- # Open a new PR
316
- gh pr create --repo owner/repo --title "Fix: ..." --head my-branch --base main --body "..."
317
308
  ```
318
309
 
319
- For App auth, `GH_TOKEN` is an installation access token that refreshes automatically — it stays current as long as the adapter is running.
310
+ For a pull request, prepare the exact title, body, pushed head branch, and base branch, then ask the operator to run `gh pr create --repo owner/repo --title 'Fix: ...' --head my-branch --base main --body '...'` at the host stage from the repository checkout. Model-driven bash cannot push or create a PR because network Git and `gh pr create` may execute local Git hooks with reusable credentials.
311
+
312
+ For the supported issue form under App auth, TypeClaw mints a short-lived token for the explicit `--repo owner/repo` target and withholds it from sibling commands and shell expansions.
320
313
 
321
314
  Before you compose the issue/PR body, read `typeclaw-github-contributing` — it covers the target repo's contribution etiquette (fill the issue/PR template if one exists, honor `CONTRIBUTING.md`, match the repo's title conventions, search for duplicates first). Opening an issue or PR that ignores the repo's template reads as careless; following it reads as someone who belongs. That skill applies whenever you open a new issue/PR, whether or not the work arrived through this channel.
322
315
 
@@ -5,6 +5,8 @@ description: Use this skill whenever you decide to delegate substantial coding o
5
5
 
6
6
  # typeclaw-claude-code
7
7
 
8
+ > **Current security boundary:** authenticated Claude Code delegation is unavailable from model-driven TypeClaw tools. The bash sandbox never receives Anthropic keys, OAuth tokens, or Claude credential profiles, regardless of role. Do not start the tmux/worktree delegation flow for work that requires authentication. A direct operator may authenticate and run Claude Code themselves from the host side, outside the model tool boundary. The mechanics below are retained for unauthenticated diagnostics and for a future explicitly brokered runtime, not as a credential workaround.
9
+
8
10
  You can delegate work to Claude Code, Anthropic's official coding agent. The agent runs as an interactive TUI: it plans, uses sub-agents, edits files, runs tools — the full loop. You drive it through tmux because your own process has no TTY, you isolate it in a dedicated `git worktree` so its experiments never touch the live agent checkout, and you detect "turn done" through a `Stop` hook that writes a sentinel file (not by parsing the TUI buffer).
9
11
 
10
12
  This skill is for the case where Claude Code is the right tool: hard architecture work, multi-file refactors, deep code analysis, a second-opinion read on something you wrote. It is **not** for trivial edits — the round-trip cost (worktree setup + process spawn + auth check + TUI init + at least one full Claude turn) is 15–45 seconds and several thousand tokens of someone else's context window. Do trivial edits yourself.
@@ -13,7 +15,7 @@ This skill is for the case where Claude Code is the right tool: hard architectur
13
15
 
14
16
  Once you've decided Claude Code is the right tool, spawn the bundled `operator` subagent to do the actual driving — don't run the worktree setup, the tmux session, the polling loop, the multi-turn decision loop, and the cleanup inline in your own context. The whole loop typically takes several minutes and produces large amounts of intermediate output (TUI buffer captures, Stop sentinels per turn, JSONL transcript references); running it inline blocks the user from talking to you and burns through your context window before you ever get to the synthesis step. `operator` is write-capable and runs the same loop, then returns a clean final report (what claude produced, what `git diff main..cc-<id>` shows, what you should review). You ship the worktree, the prompt, and the safety constraints to operator; operator ships you back the diff and the summary.
15
17
 
16
- Exception: a quick sanity ping (`claude --version` to check the binary exists, `env | grep ANTHROPIC` to check auth). Those are single fast bash calls — do them inline. The "spawn through operator" rule applies to anything that runs `claude` itself as an interactive TUI.
18
+ Exception: a quick unauthenticated sanity ping (`claude --version` to check the binary exists). Do it inline. Do not probe authentication state. The "spawn through operator" rule applies to anything that runs `claude` itself as an interactive TUI.
17
19
 
18
20
  ## When to delegate to Claude Code
19
21
 
@@ -30,50 +32,15 @@ Do **not** use Claude Code for:
30
32
  - Anything where the user is watching your tool calls and wants to see each step — Claude's intermediate output is captured but not streamed back to the user.
31
33
  - Tasks that depend on context you haven't extracted yet. Claude won't have repo-wide context either; you have to brief it explicitly.
32
34
 
33
- ## First-time auth (interactive)
34
-
35
- If `claude` is installed but no credential is set up, you have to broker the auth flow yourself. The user is talking to you through the TUI (or a channel); you walk them through one of two paths.
36
-
37
- **Decision rule, top to bottom:**
38
-
39
- 1. **`~/.claude/.credentials.json` already populated?** When typeclaw is configured with an `anthropic` OAuth credential (via `typeclaw provider add anthropic` or the init wizard) AND `docker.file.claudeCode: true`, the agent boot auto-emits the credential to `~/.claude/.credentials.json`. Check with `test -s ~/.claude/.credentials.json && jq -e '.claudeAiOauth.accessToken' ~/.claude/.credentials.json` — if it returns a string, Claude Code reads it on its own with no env var needed. Skip auth entirely.
40
- 2. **Already authenticated via env?** Run `env | grep -E '^(ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN)='` — if either is present, skip auth entirely.
41
- 3. **User has an Anthropic Console workspace** (API billing, no subscription) → API key path.
42
- 4. **User has a Claude Pro/Max/Team/Enterprise subscription** → OAuth token path.
43
- 5. **User is unsure** → ask which kind of Claude account they have. Both paths are now equally low-friction (one user action each — paste an API key, or run one command on their machine and paste the result), so the old "prefer API key when unsure" bias is gone. Pick by account shape, not by flow complexity.
44
-
45
- Both paths converge on the same final steps: read `.env`, merge one new `KEY=value` line, write back with the `nonWorkspaceWrite` guard ack, verify, and prompt the user to restart the container. Only the credential differs.
35
+ ## Authentication boundary
46
36
 
47
- ### API key path
37
+ Authentication is an **operator-owned host action**. Model-driven tools cannot read or write `.env`, `secrets.json`, `auth.json`, `~/.claude/.credentials.json`, or the persistent credential directories, and must never ask a user to paste an API key or OAuth token into chat.
48
38
 
49
- 1. Ask the user: "Paste your Anthropic API key (starts with `sk-ant-`) — or say 'cancel' to use OAuth instead."
50
- 2. **Validate** the pasted value before writing: `/^sk-ant-[A-Za-z0-9_-]{20,}$/`. If it doesn't match, refuse and ask again — neither the guard nor the restart tool catches a malformed token.
51
- 3. **Read** the existing `.env` first (if any). Parse it into a key→value map so you don't clobber unrelated entries.
52
- 4. **Reconstruct** the full `.env` content with `ANTHROPIC_API_KEY=<value>` added or replaced.
53
- 5. **Write** with `acknowledgeGuards: { nonWorkspaceWrite: true }`. `.env` is in the `nonWorkspaceWrite` guard's deny set; the call fails without the ack flag.
54
- 6. **Verify** by re-reading the file.
55
- 7. **Ask the user**: "Auth is on disk. The container needs to restart to load it (TUI will briefly disconnect). May I restart now, or do you have other changes to make first?"
56
- 8. On yes → call the `restart` tool. On no → tell them to run `typeclaw restart` themselves when ready.
39
+ Even when TypeClaw's trusted runtime has provider credentials, model-driven bash does not inherit them and cannot open the exported profile. There is no readiness check that turns authenticated delegation on.
57
40
 
58
- ### OAuth path
41
+ Stop and tell the operator that they must authenticate and invoke Claude Code directly from the **host side**. Do not promise that `typeclaw restart`, a role grant, a guard acknowledgement, or an existing provider login will make authenticated model-driven delegation available. Any direct Claude Code login or token setup must be completed entirely by the operator; do not request its output.
59
42
 
60
- The OAuth flow runs **on the user's own machine**, not inside the container. The user generates a long-lived `CLAUDE_CODE_OAUTH_TOKEN` with `claude setup-token` on whatever local machine they're already authenticated on, copies the printed token, and pastes it back to you. You write it to `.env` exactly like the API key path.
61
-
62
- Why this works: `claude setup-token` is Anthropic's documented path for "CI pipelines, scripts, or other environments where interactive browser login isn't available" ([code.claude.com/docs/en/authentication](https://code.claude.com/docs/en/authentication)). A typeclaw container is exactly that environment. The token is one-year-lived, authenticates against the user's Claude subscription, and is scoped to inference only — it can't establish Remote Control sessions or otherwise act outside of `claude` CLI calls.
63
-
64
- Do **not** run `claude setup-token` inside the container. The container has no browser, no display, and (for remote-host typeclaw deployments) is on a different machine from the user's browser anyway. The user's local machine already has `claude` installed for them to be a subscriber in the first place — they're the right place to run the one-off `setup-token` command.
65
-
66
- 1. Confirm with the user: "Do you have the `claude` CLI installed on your local machine and are you signed in to it with your Claude Pro/Max/Team/Enterprise account? If not, install it from claude.com/code and `claude login` first."
67
- 2. Once they confirm, instruct them: "Run `claude setup-token` on your machine. It opens a browser, you authorize, and the terminal prints a long token (looks like `sk-ant-oat01-...` or similar). Copy that token and paste it back to me. The token is long-lived (one year) and authenticates against your Claude subscription — keep it private."
68
- 3. When they paste, **validate** before writing: `/^[A-Za-z0-9_-]{30,}$/`. Strip surrounding whitespace first. If it doesn't match (too short, contains slashes, looks like a URL or a sentence), refuse and ask again — the user may have pasted a partial copy or the wrong line.
69
- 4. **Read** the existing `.env` first. Parse it into a key→value map.
70
- 5. **Reconstruct** the full `.env` content with `CLAUDE_CODE_OAUTH_TOKEN=<value>` added or replaced.
71
- 6. **Write** with `acknowledgeGuards: { nonWorkspaceWrite: true }`.
72
- 7. **Verify** by re-reading the file.
73
- 8. **Ask before restart** (same prompt as the API key path).
74
- 9. On yes → call the `restart` tool. On no → `typeclaw restart` themselves when ready.
75
-
76
- The full validation rules, the failure modes on the user's side (their `claude` CLI is signed out, their `setup-token` command 401s, their subscription is expired), and the rationale for not doing the OAuth dance in-container are in `references/auth-flow.md`.
43
+ If Claude Code presents an auth prompt or API-key confirmation that would require entering or inspecting a credential, abort and report that host-side authentication is required. Never transmit a credential through tmux, a prompt, a tool argument, or a file writable by the model. See `references/auth-flow.md`.
77
44
 
78
45
  ### Cost-cap warning
79
46
 
@@ -85,8 +52,8 @@ Before you spawn `claude` for any real work:
85
52
 
86
53
  - **`docker.file.claudeCode: true`** in `typeclaw.json`. Verify with `which claude`; if missing, the toggle isn't on. Tell the user to enable it and `typeclaw start --build`.
87
54
  - **`docker.file.tmux: true`** (default `true`, but check). Verify with `which tmux`.
88
- - **Auth set up** — see above. Verify with `env | grep -E '^(ANTHROPIC_API_KEY|CLAUDE_CODE_OAUTH_TOKEN)='`.
89
- - **Onboarding pre-seeded.** The Dockerfile layer writes `~/.claude.json` with `hasCompletedOnboarding: true` and `theme: "dark"` so the first `claude` invocation skips the TTY-only theme picker / welcome wizard. **This is necessary but not sufficient** — even with the seed, Claude Code can still land on two other pre-prompt modals: the "Detected a custom API key from environment. Do you want to use this API key?" confirmation (when `ANTHROPIC_API_KEY` is set in env — default focus is **No**, so `Down Enter` is needed to accept) and the workspace trust dialog ("Do you trust the files in this folder?", default focus already on **Yes**, so a bare `Enter` accepts). The "Driving the session" section below clears them as a loop. If `~/.claude.json` is empty or missing entirely (custom mount, manual `rm`, a `CLAUDE_CONFIG_DIR` pointing at a fresh directory), the theme picker also reappears. Self-heal: `printf '%s\n' '{"hasCompletedOnboarding":true,"theme":"dark","installMethod":"native","numStartups":1}' > "$HOME/.claude.json"` before spawning, then retry.
55
+ - **No authenticated model-driven path.** If the task requires a Claude account, stop and hand execution to the direct host-side operator. Do not probe env vars or credential files.
56
+ - **Onboarding pre-seeded.** The Dockerfile layer writes non-secret onboarding preferences. A workspace-trust dialog may still appear. Any API-key or sign-in dialog means the command requires authentication that model-driven tools cannot receive: abort rather than navigating it.
90
57
  - **Agent folder is a git repo.** Verify with `git -C /agent rev-parse --is-inside-work-tree`. The worktree model below requires it. If the user's agent folder somehow isn't a repo (rare — `typeclaw init` scaffolds one), tell them to `git init && git add -A && git commit -m "initial"` first.
91
58
  - **No uncommitted changes that you care about.** `git -C /agent status --porcelain` should be clean, or you should be willing to set the working tree aside before delegating. The worktree is a separate checkout, so claude can't see your uncommitted changes — meaning claude operates on the last committed state. If the user wants claude to work with in-progress edits, commit them first (even on a WIP branch).
92
59
 
@@ -194,26 +161,24 @@ The minimum protocol — translate to your actual tool calls:
194
161
  4. **Clear startup dialogs (BEFORE sending the task prompt).** Even with `~/.claude.json` pre-seeded, claude can land on one or both pre-prompt modals. Run this as a **loop**, not a one-shot: clearing one dialog can immediately reveal the next, and you must keep polling until claude's actual input prompt is visible (it renders a bottom-of-pane input box with a `╭` / `╰` border). **Do NOT poll `.session-id` before this step** — per anthropics/claude-code#11519, SessionStart is suppressed while workspace trust is pending, so `.session-id` will not appear until you've accepted trust here.
195
162
 
196
163
  The two known modals, with the exact keystrokes for each (Claude Code's select widget does NOT wrap — pressing `Up` from the first option is a no-op, so the direction must match the dialog's option order):
197
- - **Custom API key confirmation** — "Detected a custom API key from environment. Do you want to use this API key?" Fires when `ANTHROPIC_API_KEY` is set (exactly typeclaw's auth path). Options are `[No (recommended), Yes]` with focus initialized on **No**. Resolution: `tmux send-keys -t cc-<id> Down Enter` to advance to **Yes** and submit. Sending `Up Enter` would submit the **No** answer, which can persist as a rejection in `customApiKeyResponses.rejected` and break subsequent launches — never do that here.
164
+ - **Custom API key or sign-in prompt** — abort the session and tell the direct operator to authenticate and run Claude Code host-side. Never accept the prompt or enter a credential.
198
165
 
199
166
  - **Workspace trust** — "Do you trust the files in this folder?" Fires on first launch in any new cwd, so every fresh `/tmp/cc-<id>/` worktree triggers it. Options are `[Yes, proceed, No, exit]` with focus on the first option (**Yes**) by default. Resolution: bare `tmux send-keys -t cc-<id> Enter` — no arrow key needed. Always verify the pane text matches the trust dialog before pressing Enter; a misidentified modal would submit a different default.
200
167
 
201
168
  Loop shape (translate to your tool calls):
202
169
  1. Capture the last ~15 lines: `tmux capture-pane -t cc-<id> -p -S -15`.
203
- 2. If the capture contains the API key dialog text → `send-keys Down Enter`, sleep 500ms, goto 1.
204
- 3. If the capture contains the trust dialog text → `send-keys Enter`, sleep 500ms, goto 1.
205
- 4. If the capture shows the input box (`╭` border on a bottom line, no dialog text above it) → ready; exit the loop.
206
- 5. Otherwise sleep 500ms, goto 1. Apply a wall-clock budget of ~10 seconds; if the loop hasn't reached step 4 by then, abort with `/exit` and surface to the user — claude is in a state this skill doesn't model.
170
+
171
+ 5. If the capture contains an API-key or sign-in dialog → send `/exit` (or terminate the unauthenticated session if no input box is available), then report that the direct host-side operator must authenticate and run Claude Code. Never select a credential option or enter a key. 3. If the capture contains the trust dialog text → `send-keys Enter`, sleep 500ms, goto 1. 4. If the capture shows the input box (`╭` border on a bottom line, no dialog text above it) → ready; exit the loop. 5. Otherwise sleep 500ms, goto 1. Apply a wall-clock budget of ~10 seconds; if the loop hasn't reached step 4 by then, abort with `/exit` and surface to the user — claude is in a state this skill doesn't model.
207
172
 
208
173
  Do not use a fixed 2-second wait then send the prompt — cold-start and slow-disk cases can deliver a dialog at 2.5s+, and sending the task prompt into a modal corrupts the session.
209
174
 
210
175
  **Safety note**: accepting workspace trust on a fresh `/tmp/cc-<id>/` worktree is the right call **only when its `HEAD` is the intended clean state** — typically the agent folder's last good commit on a branch the user controls. If the user just merged a third-party PR, pulled a remote branch, or checked out an untrusted ref, the worktree carries that content too and "trusting" it gives claude tool access on potentially hostile code. Before auto-accepting trust, sanity-check: if the user hasn't said something equivalent to "delegate this to Claude Code", or if you're not confident the current `HEAD` is one the user authored or reviewed, surface the trust dialog to them instead. Do NOT extend even a legitimate trust acceptance to in-session permission prompts (Bash, Edit, etc.) — those still need per-turn judgment per the multi-turn decision loop below.
211
176
 
212
- 5. `tmux send-keys -t cc-<id> "<your prompt>" Enter`.
213
- 6. **Discover the session UUID from the newest unprocessed Stop sentinel.** Poll `/tmp/cc-<id>/.done-*` in a loop: each iteration, enumerate the files sorted by mtime (`ls -t`), filter out any UUIDs you've already processed (initially empty), and pick the first one whose UUID is a real hex UUID (not `malformed`). That UUID becomes `cc_session_id`. On every poll, also check `tmux has-session -t cc-<id>` — if the session died, claude crashed or auth failed. (Fast-path optimization: if `/tmp/cc-<id>/.session-id` happened to appear before the first prompt, you can use it instead and skip the glob — see `references/tmux-driving.md` for the fast-path snippet.) If the only marker that appears is `.done-malformed`, the Stop hook fired but couldn't extract a UUID-shape `session_id` from the payload — bail and surface to the user.
214
- 7. Read `/tmp/cc-<id>/sentinel-${cc_session_id}.json`, examine `last_assistant_message`, then `rm /tmp/cc-<id>/.done-${cc_session_id}` (the SPECIFIC file you just processed, NOT a glob — globbing wipes any in-flight new sentinel from a concurrent compact rotation).
215
- 8. Decide using the multi-turn loop below. **Track which UUIDs you've already processed.** On the next poll, again pick the newest unprocessed `.done-<uuid>`. If the UUID differs from the previous `cc_session_id`, claude has compacted (anthropics/claude-code#29094) — update `cc_session_id` to the new value and continue. Polling is edge-triggered: don't wait on `.done-${cc_session_id}` specifically, because if compact rotated the UUID, that file will never appear.
216
- 9. When done: `tmux send-keys -t cc-<id> "/exit" Enter && sleep 1 && tmux kill-session -t cc-<id>`.
177
+ 6. `tmux send-keys -t cc-<id> "<your prompt>" Enter`.
178
+ 7. **Discover the session UUID from the newest unprocessed Stop sentinel.** Poll `/tmp/cc-<id>/.done-*` in a loop: each iteration, enumerate the files sorted by mtime (`ls -t`), filter out any UUIDs you've already processed (initially empty), and pick the first one whose UUID is a real hex UUID (not `malformed`). That UUID becomes `cc_session_id`. On every poll, also check `tmux has-session -t cc-<id>` — if the session died, claude crashed or auth failed. (Fast-path optimization: if `/tmp/cc-<id>/.session-id` happened to appear before the first prompt, you can use it instead and skip the glob — see `references/tmux-driving.md` for the fast-path snippet.) If the only marker that appears is `.done-malformed`, the Stop hook fired but couldn't extract a UUID-shape `session_id` from the payload — bail and surface to the user.
179
+ 8. Read `/tmp/cc-<id>/sentinel-${cc_session_id}.json`, examine `last_assistant_message`, then `rm /tmp/cc-<id>/.done-${cc_session_id}` (the SPECIFIC file you just processed, NOT a glob — globbing wipes any in-flight new sentinel from a concurrent compact rotation).
180
+ 9. Decide using the multi-turn loop below. **Track which UUIDs you've already processed.** On the next poll, again pick the newest unprocessed `.done-<uuid>`. If the UUID differs from the previous `cc_session_id`, claude has compacted (anthropics/claude-code#29094) — update `cc_session_id` to the new value and continue. Polling is edge-triggered: don't wait on `.done-${cc_session_id}` specifically, because if compact rotated the UUID, that file will never appear.
181
+ 10. When done: `tmux send-keys -t cc-<id> "/exit" Enter && sleep 1 && tmux kill-session -t cc-<id>`.
217
182
 
218
183
  The full polling implementation, the ANSI-handling rules for `capture-pane` fallbacks, and the "tmux session died unexpectedly" recovery path are in `references/tmux-driving.md`.
219
184
 
@@ -284,7 +249,7 @@ A re-statement, because this is where the skill is most often misused:
284
249
  - **Trivial edits**: the round-trip cost dominates. Do it yourself.
285
250
  - **Tasks needing live user visibility**: claude's tool calls don't stream back through TypeClaw. The user sees a long pause, not progress. Use your own tools.
286
251
  - **Tasks where you don't have the context to brief claude**: spend tokens narrowing the problem first. A vague delegation produces a vague result.
287
- - **Anything secret beyond `ANTHROPIC_API_KEY`**: claude only sees the prompt you send it and the files in its worktree (which is everything at `HEAD`). Don't try to pass secrets through the prompt — they'll land in claude's transcript and in your sentinel.
252
+ - **Any secret, including Anthropic credentials**: never pass it through the prompt or worktree. It would land in Claude's transcript and sentinels.
288
253
 
289
254
  ## Things you must not do
290
255
 
@@ -297,19 +262,18 @@ A re-statement, because this is where the skill is most often misused:
297
262
  - **Do not merge claude's branch into main without reviewing the diff.** The `git diff main..cc-<id>` is your review surface. Skipping the diff and merging blindly means you don't actually know what shipped.
298
263
  - **Do not commit `/tmp/cc-<id>/` artifacts back to the agent folder.** The sentinel, the hook script, the captured pane content are scratch — they live in `/tmp/`, they die with `worktree remove`.
299
264
  - **Do not paste Claude's output verbatim into a commit message or a user reply.** Summarize and attribute. You're accountable for the work you ship.
300
- - **Do not put `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN` in `typeclaw.json`, in a prompt, or in any committed file.** They live in `.env`, which is gitignored. Period.
265
+ - **Do not put `ANTHROPIC_API_KEY` or `CLAUDE_CODE_OAUTH_TOKEN` in `typeclaw.json`, a prompt, a worktree, or any model-accessible file.** Credential provisioning is direct-operator host work; the model does not edit `.env`.
301
266
  - **Do not poll the JSONL transcript directly as the done-signal.** The JSONL has documented race conditions (the file can be stale when `Stop` fires, or occasionally missing entirely). The sentinel is the reliable signal; the JSONL is for content, not lifecycle.
302
- - **Do not write to `.env` without `acknowledgeGuards: { nonWorkspaceWrite: true }`.** The guard will refuse, the agent loop will retry the same broken write, and you'll waste tokens fighting the guard. The ack is required every write, not just the first one.
303
- - **Do not edit `.env` with the `edit` tool's patch semantics.** Use read-modify-write: read the whole file, reconstruct the new content, write the whole file. `.env` is a flat KV store; a fragile `oldText` match could corrupt unrelated lines.
304
- - **Do not run `claude setup-token` inside the container.** It's a TUI OAuth flow that wants a browser. The container has no display, no browser, and is often on a different machine from the user anyway. Always have the user run `setup-token` on their own machine and paste the resulting token back; never spawn it in tmux on this side.
305
- - **Do not echo, log, or transcribe the pasted `CLAUDE_CODE_OAUTH_TOKEN` value back to the user, into a sentinel, into a commit message, or into any message you send.** It's a one-year credential. Confirm receipt with "got it, validating" — never with the token itself.
267
+ - **Do not read, write, edit, parse, or verify `.env`, `secrets.json`, `auth.json`, `~/.claude/.credentials.json`, or any credential value.** These are outside the model-driven tool boundary; guard acknowledgements do not make credential handling acceptable.
268
+ - **Do not run `claude setup-token` inside the container, and do not ask the user to paste its output.** Authentication remains entirely on the operator's host side.
269
+ - **Do not ask for, receive, echo, log, or transcribe credentials.** If a user offers one, tell them not to send it and direct them to host-side setup.
306
270
  - **Do not invent answers to Claude's clarifying questions.** If you can't derive the answer from the original task brief, surface the question to the user. Wrong answers compound across multi-turn delegations.
307
271
  - **Do not exceed 8 turns per delegation.** Abort, capture what you have, surface. Long delegations almost always mean the task wasn't shaped right.
308
272
  - **Do not assume `claude` exists.** If `which claude` returns empty, the `docker.file.claudeCode` toggle isn't on. Tell the user, don't try to install it yourself.
309
273
 
310
274
  ## Cross-references
311
275
 
312
- - **`references/auth-flow.md`** — both auth paths in detail: the API-key recap, the OAuth user-machine flow (what to tell the user, what their `claude setup-token` output looks like, validation rules), and the failure-mode catalogue (expired subscription, wrong account, malformed paste).
276
+ - **`references/auth-flow.md`** — the authentication boundary: authenticated delegation is unavailable to model-driven tools, and direct host-side setup and execution belong to the operator.
313
277
  - **`references/tmux-driving.md`** — full polling implementation, ANSI handling, session-died recovery, the `capture-pane` fallback details, the worktree-is-not-scratch distinction.
314
278
  - **`references/stop-hook.md`** — complete `Stop` event JSON schema, `SubagentStop` differences, transcript JSONL schema (unofficial but reverse-engineered), documented race conditions to handle.
315
279
  - **`typeclaw-config`** — the `docker.file.claudeCode` toggle that gates the install.