typeclaw 0.48.13 → 0.49.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 (176) hide show
  1. package/package.json +5 -5
  2. package/scripts/dump-system-prompt.ts +52 -110
  3. package/src/agent/index.ts +144 -72
  4. package/src/agent/live-sessions.ts +2 -2
  5. package/src/agent/live-subagents.ts +1 -0
  6. package/src/agent/plugin-tools.ts +53 -11
  7. package/src/agent/prompt-cache-key.ts +42 -0
  8. package/src/agent/provider-error.ts +179 -10
  9. package/src/agent/restart-handoff/index.ts +7 -14
  10. package/src/agent/reviewer-activity.ts +68 -0
  11. package/src/agent/session-origin.ts +33 -0
  12. package/src/agent/subagents.ts +13 -1
  13. package/src/agent/system-prompt.ts +68 -202
  14. package/src/agent/todo/continuation-policy.ts +12 -4
  15. package/src/agent/tool-file-safety.ts +113 -14
  16. package/src/agent/tool-not-found-nudge.ts +1 -1
  17. package/src/agent/tools/channel-history-render.ts +2 -1
  18. package/src/agent/tools/channel-reply.ts +23 -5
  19. package/src/agent/tools/channel-send.ts +49 -7
  20. package/src/agent/tools/curl-impersonate.ts +11 -2
  21. package/src/agent/tools/post-github-review.ts +77 -15
  22. package/src/agent/tools/skip-response.ts +2 -2
  23. package/src/agent/tools/spawn-subagent.ts +163 -12
  24. package/src/agent/tools/subagent-output.ts +8 -0
  25. package/src/bundled-plugins/backup/README.md +10 -9
  26. package/src/bundled-plugins/backup/runner.ts +140 -58
  27. package/src/bundled-plugins/backup/subagents.ts +58 -26
  28. package/src/bundled-plugins/github-cli-auth/gh-command.ts +34 -2
  29. package/src/bundled-plugins/github-cli-auth/granted-push.ts +135 -0
  30. package/src/bundled-plugins/github-cli-auth/index.ts +83 -11
  31. package/src/bundled-plugins/github-cli-auth/review-account.ts +23 -0
  32. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -2
  33. package/src/bundled-plugins/github-cli-auth/review-recorder.ts +45 -7
  34. package/src/bundled-plugins/operator/operator.ts +15 -4
  35. package/src/bundled-plugins/reviewer/skills/code-review.ts +1 -1
  36. package/src/bundled-plugins/security/index.ts +50 -2
  37. package/src/bundled-plugins/security/policies/git-exfil.ts +24 -12
  38. package/src/channels/adapters/discord-bot-reactions.ts +18 -0
  39. package/src/channels/adapters/discord-bot.ts +122 -67
  40. package/src/channels/adapters/discord-reactions.ts +18 -0
  41. package/src/channels/adapters/discord.ts +114 -8
  42. package/src/channels/adapters/github/inbound.ts +103 -8
  43. package/src/channels/adapters/github/index.ts +251 -19
  44. package/src/channels/adapters/github/last-alive.ts +27 -0
  45. package/src/channels/adapters/github/outbound.ts +54 -18
  46. package/src/channels/adapters/github/pending-review-store.ts +141 -0
  47. package/src/channels/adapters/github/permission-guidance.ts +1 -0
  48. package/src/channels/adapters/github/reactions.ts +100 -0
  49. package/src/channels/adapters/github/reconcile-cooldown-store.ts +197 -67
  50. package/src/channels/adapters/github/reconcile-open-prs.ts +418 -33
  51. package/src/channels/adapters/github/recovery.ts +106 -0
  52. package/src/channels/adapters/github/review-check.ts +510 -0
  53. package/src/channels/adapters/github/review-submitter.ts +34 -2
  54. package/src/channels/adapters/instagram.ts +32 -14
  55. package/src/channels/adapters/kakaotalk.ts +22 -7
  56. package/src/channels/adapters/line.ts +18 -3
  57. package/src/channels/adapters/outbound-account.ts +20 -0
  58. package/src/channels/adapters/own-reactions.ts +66 -0
  59. package/src/channels/adapters/recovery-correlation.ts +214 -0
  60. package/src/channels/adapters/slack-bot-classify.ts +18 -11
  61. package/src/channels/adapters/slack-bot-dedupe.ts +111 -28
  62. package/src/channels/adapters/slack-bot-reactions.ts +18 -0
  63. package/src/channels/adapters/slack-bot.ts +125 -57
  64. package/src/channels/adapters/slack-classify.ts +25 -4
  65. package/src/channels/adapters/slack-inbound-revision.ts +96 -0
  66. package/src/channels/adapters/slack-reactions.ts +18 -0
  67. package/src/channels/adapters/slack-thread-ts.ts +6 -0
  68. package/src/channels/adapters/slack.ts +48 -3
  69. package/src/channels/adapters/teams.ts +14 -4
  70. package/src/channels/adapters/telegram-bot.ts +56 -10
  71. package/src/channels/adapters/webex-bot.ts +12 -2
  72. package/src/channels/adapters/webex.ts +12 -2
  73. package/src/channels/background-handoff.ts +434 -0
  74. package/src/channels/background-obligations.ts +893 -0
  75. package/src/channels/continuity-types.ts +271 -0
  76. package/src/channels/github-review-check.ts +598 -0
  77. package/src/channels/github-review-turn-ledger.ts +102 -28
  78. package/src/channels/github-review-verdict-coordinator.ts +72 -12
  79. package/src/channels/github-token-bridge.ts +11 -5
  80. package/src/channels/inbound-journal.ts +1738 -0
  81. package/src/channels/index.ts +6 -1
  82. package/src/channels/manager.ts +17 -7
  83. package/src/channels/recovery-dispatcher.ts +264 -0
  84. package/src/channels/recovery-notice.ts +94 -0
  85. package/src/channels/recovery-outbox.ts +459 -0
  86. package/src/channels/router.ts +2539 -615
  87. package/src/channels/schema.ts +8 -1
  88. package/src/channels/subagent-completion-bridge.ts +17 -14
  89. package/src/channels/types.ts +121 -16
  90. package/src/channels/waiting-reactions.ts +664 -0
  91. package/src/cli/compose.ts +7 -4
  92. package/src/cli/hostd.ts +49 -3
  93. package/src/cli/inspect.ts +11 -14
  94. package/src/coding-agent/broker-body.ts +38 -0
  95. package/src/coding-agent/broker.ts +290 -0
  96. package/src/coding-agent/claude.ts +95 -0
  97. package/src/coding-agent/codex.ts +104 -0
  98. package/src/coding-agent/index.ts +506 -0
  99. package/src/coding-agent/omo-state.ts +69 -0
  100. package/src/coding-agent/omo-stream.ts +98 -0
  101. package/src/coding-agent/omo.ts +192 -0
  102. package/src/coding-agent/runner.ts +263 -0
  103. package/src/coding-agent/tool.ts +62 -0
  104. package/src/coding-agent/worktree.ts +355 -0
  105. package/src/compose/restart.ts +10 -3
  106. package/src/compose/start.ts +20 -3
  107. package/src/config/config.ts +10 -3
  108. package/src/config/providers.ts +12 -9
  109. package/src/container/exit-reason.ts +44 -0
  110. package/src/container/index.ts +5 -0
  111. package/src/container/log-archive.ts +51 -13
  112. package/src/container/memory-limit.ts +1 -1
  113. package/src/container/memory-oversubscription.ts +36 -6
  114. package/src/container/oom-events.ts +86 -0
  115. package/src/container/restart.ts +2 -0
  116. package/src/container/shared.ts +8 -1
  117. package/src/container/start.ts +25 -13
  118. package/src/container/stop.ts +6 -2
  119. package/src/container/tool-oom-priority.ts +32 -0
  120. package/src/cron/consumer.ts +10 -4
  121. package/src/cron/reloadable.ts +23 -2
  122. package/src/doctor/checks.ts +14 -2
  123. package/src/hostd/daemon.ts +20 -10
  124. package/src/hostd/spawn.ts +106 -5
  125. package/src/hostd/version.ts +20 -0
  126. package/src/hostd/watchdog.ts +241 -0
  127. package/src/init/dockerfile.ts +57 -592
  128. package/src/init/index.ts +2 -3
  129. package/src/mcp/client.ts +3 -1
  130. package/src/operations/classify-tool-outcome.ts +45 -1
  131. package/src/operations/incidents.ts +10 -5
  132. package/src/plugin/core-tool-names.ts +1 -1
  133. package/src/plugin/define.ts +1 -0
  134. package/src/plugin/index.ts +1 -0
  135. package/src/plugin/types.ts +6 -1
  136. package/src/run/background-handoff-boot.ts +86 -0
  137. package/src/run/index.ts +83 -83
  138. package/src/run/resource-sample.ts +19 -0
  139. package/src/sandbox/build.ts +4 -0
  140. package/src/sandbox/coding-agent.ts +214 -0
  141. package/src/sandbox/policy.ts +1 -0
  142. package/src/sandbox/runtime-private.ts +4 -1
  143. package/src/secrets/coding-agent-auth.ts +97 -0
  144. package/src/secrets/index.ts +0 -16
  145. package/src/server/command-runner.ts +6 -2
  146. package/src/server/index.ts +101 -40
  147. package/src/skills/typeclaw-channel-github/SKILL.md +7 -5
  148. package/src/skills/typeclaw-claude-code/SKILL.md +25 -260
  149. package/src/skills/typeclaw-claude-code/references/auth-flow.md +7 -23
  150. package/src/skills/typeclaw-claude-code/references/headless-sessions.md +11 -0
  151. package/src/skills/typeclaw-claude-code/references/results-and-worktrees.md +13 -0
  152. package/src/skills/typeclaw-codex-cli/SKILL.md +35 -270
  153. package/src/skills/typeclaw-codex-cli/references/auth-flow.md +13 -20
  154. package/src/skills/typeclaw-codex-cli/references/headless-sessions.md +26 -0
  155. package/src/skills/typeclaw-codex-cli/references/results-and-worktrees.md +28 -0
  156. package/src/skills/typeclaw-config/SKILL.md +21 -21
  157. package/src/skills/typeclaw-config/references/dockerfile.md +14 -13
  158. package/src/skills/typeclaw-cron/SKILL.md +1 -1
  159. package/src/skills/typeclaw-github-contributing/SKILL.md +2 -2
  160. package/src/skills/typeclaw-memory/SKILL.md +3 -3
  161. package/src/skills/typeclaw-omo-cli/SKILL.md +52 -0
  162. package/src/skills/typeclaw-omo-cli/references/auth-flow.md +11 -0
  163. package/src/skills/typeclaw-omo-cli/references/headless-sessions.md +11 -0
  164. package/src/skills/typeclaw-omo-cli/references/results-and-worktrees.md +23 -0
  165. package/src/skills/typeclaw-plugins/SKILL.md +15 -15
  166. package/src/skills/typeclaw-skills/SKILL.md +19 -2
  167. package/src/skills/typeclaw-troubleshooting/SKILL.md +15 -2
  168. package/typeclaw.schema.json +12 -1
  169. package/src/secrets/claude-credentials-json.ts +0 -129
  170. package/src/secrets/codex-auth-json.ts +0 -102
  171. package/src/secrets/export-claude-credentials-file.ts +0 -270
  172. package/src/secrets/export-codex-auth-file.ts +0 -250
  173. package/src/skills/typeclaw-claude-code/references/stop-hook.md +0 -101
  174. package/src/skills/typeclaw-claude-code/references/tmux-driving.md +0 -243
  175. package/src/skills/typeclaw-codex-cli/references/stop-hook.md +0 -92
  176. package/src/skills/typeclaw-codex-cli/references/tmux-driving.md +0 -239
@@ -1,4 +1,6 @@
1
1
  import { lstatSync } from 'node:fs'
2
+ import { mkdtemp, rm } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
2
4
  import { join } from 'node:path'
3
5
 
4
6
  import { hooklessGitArgs } from '@/git/hookless'
@@ -100,79 +102,148 @@ export async function runBackup(options: BackupRunnerOptions, deps: BackupRunner
100
102
  timeoutMs: COMMIT_TIMEOUT_MS,
101
103
  })
102
104
  if (status.exitCode !== 0) return { ok: false, kind: 'aborted', reason: `git status failed: ${shortErr(status)}` }
103
- const snapshot = selectStagingSnapshot(parsePorcelain(status.stdout), cwd)
104
- if (snapshot.paths.length === 0 && snapshot.forcePaths.length === 0) return { ok: true, kind: 'clean' }
105
-
106
- if (snapshot.paths.length > 0) {
107
- const add = await deps.gitSpawn([...repo.gitArgs, 'add', '--', ...snapshot.paths], {
105
+ const entries = parsePorcelain(status.stdout)
106
+ // Only index-known, absent worktree paths that were NEVER in HEAD are
107
+ // stale additions (including removed intent-to-add entries). A tracked
108
+ // deletion still in HEAD is backup work; memory/ belongs to another writer.
109
+ const missing = uniquePaths(
110
+ entries
111
+ .filter((entry) => entry.kind === 'tracked' && (entry.status[0] === 'A' || entry.status[1] === 'D'))
112
+ .flatMap((entry) => entry.paths)
113
+ .filter((path) => !isAgentOwned(path) && !hasDirectoryEntry(join(cwd, path))),
114
+ )
115
+ const head =
116
+ missing.length > 0
117
+ ? await deps.gitSpawn([...repo.gitArgs, 'ls-tree', '-r', '--name-only', '-z', 'HEAD', '--', ...missing], {
118
+ cwd,
119
+ timeoutMs: COMMIT_TIMEOUT_MS,
120
+ })
121
+ : { exitCode: 0, stdout: '', stderr: '', timedOut: false }
122
+ if (head.exitCode !== 0) {
123
+ const exists = await deps.gitSpawn([...repo.gitArgs, 'rev-parse', '--verify', 'HEAD'], {
108
124
  cwd,
109
125
  timeoutMs: COMMIT_TIMEOUT_MS,
110
126
  })
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)}` }
115
- }
116
- }
127
+ if (exists.exitCode === 0)
128
+ return { ok: false, kind: 'commit-failed', reason: `git ls-tree failed: ${shortErr(head)}` }
117
129
  }
118
- if (snapshot.forcePaths.length > 0) {
119
- const addF = await deps.gitSpawn([...repo.gitArgs, 'add', '-f', '--', ...snapshot.forcePaths], {
130
+ const headPaths = new Set(head.stdout.split('\0'))
131
+ const missingAdds = missing.filter((path) => !headPaths.has(path))
132
+ if (missingAdds.length > 0) {
133
+ const removed = await deps.gitSpawn([...repo.gitArgs, 'add', '-u', '--', ...missingAdds], {
120
134
  cwd,
121
135
  timeoutMs: COMMIT_TIMEOUT_MS,
122
136
  })
123
- if (addF.exitCode !== 0) {
124
- return { ok: false, kind: 'commit-failed', reason: `git add -f failed: ${shortErr(addF)}` }
125
- }
137
+ if (removed.exitCode !== 0)
138
+ return { ok: false, kind: 'commit-failed', reason: `git add -u failed: ${shortErr(removed)}` }
126
139
  }
127
-
128
- const stagedCheck = await deps.gitSpawn([...repo.gitArgs, 'diff', '--cached', '--quiet'], {
140
+ const removedPaths = new Set(missingAdds)
141
+ const snapshot = selectStagingSnapshot(
142
+ entries.filter((entry) => !entry.paths.every((path) => removedPaths.has(path))),
129
143
  cwd,
130
- timeoutMs: COMMIT_TIMEOUT_MS,
131
- })
132
- if (stagedCheck.exitCode === 0) return { ok: true, kind: 'clean' }
144
+ )
145
+ if (snapshot.paths.length === 0 && snapshot.forcePaths.length === 0) return { ok: true, kind: 'clean' }
133
146
 
134
- const diffstat = await deps.gitSpawn([...repo.gitArgs, 'diff', '--cached', '--stat'], {
135
- cwd,
136
- timeoutMs: COMMIT_TIMEOUT_MS,
137
- })
138
- const message = await deps.pickCommitMessage({
139
- status: status.stdout.replaceAll('\0', '\n').slice(0, 4096),
140
- diffstat: diffstat.stdout.slice(0, 4096),
141
- })
147
+ // Keep the staged snapshot out of the shared index while the message subagent
148
+ // runs. Other writers may commit the entire shared index during that window.
149
+ const indexDir = await mkdtemp(join(tmpdir(), 'typeclaw-backup-index-'))
150
+ const indexEnv = { GIT_INDEX_FILE: join(indexDir, 'index') }
151
+ const privateGit = (args: string[]) =>
152
+ deps.gitSpawn([...repo.gitArgs, ...args], { cwd, timeoutMs: COMMIT_TIMEOUT_MS, env: indexEnv })
153
+ const readHead = async (): Promise<GitSpawnResult> => {
154
+ const result = await privateGit(['read-tree', 'HEAD'])
155
+ if (result.exitCode === 0) return result
156
+ const head = await privateGit(['rev-parse', '--verify', 'HEAD'])
157
+ return head.exitCode === 0 ? result : privateGit(['read-tree', '--empty'])
158
+ }
159
+ const stageSnapshot = async (paths: string[], forcePaths: string[]): Promise<GitSpawnResult | undefined> => {
160
+ if (paths.length > 0) {
161
+ const add = await privateGit(['add', '-f', '--', ...paths])
162
+ if (add.exitCode !== 0) {
163
+ const retry = await retryAfterVanishedUntracked(cwd, deps, repo, snapshot, indexEnv, true)
164
+ if (!retry || retry.exitCode !== 0) return retry ?? add
165
+ }
166
+ }
167
+ if (forcePaths.length > 0) {
168
+ const add = await privateGit(['add', '-f', '--', ...forcePaths])
169
+ if (add.exitCode !== 0) return add
170
+ }
171
+ return undefined
172
+ }
173
+ try {
174
+ const init = await readHead()
175
+ if (init.exitCode !== 0)
176
+ return { ok: false, kind: 'commit-failed', reason: `git read-tree failed: ${shortErr(init)}` }
177
+ const staged = await stageSnapshot(snapshot.paths, snapshot.forcePaths)
178
+ if (staged) return { ok: false, kind: 'commit-failed', reason: `git add failed: ${shortErr(staged)}` }
179
+
180
+ const stagedCheck = await privateGit(['diff', '--cached', '--quiet'])
181
+ if (stagedCheck.exitCode === 0) return { ok: true, kind: 'clean' }
182
+ if (stagedCheck.exitCode !== 1)
183
+ return { ok: false, kind: 'commit-failed', reason: `git diff failed: ${shortErr(stagedCheck)}` }
184
+
185
+ const diffstat = await privateGit(['diff', '--cached', '--stat'])
186
+ const message = await deps.pickCommitMessage({
187
+ status: status.stdout.replaceAll('\0', '\n').slice(0, 4096),
188
+ diffstat: diffstat.stdout.slice(0, 4096),
189
+ })
142
190
 
143
- // `pickCommitMessage` may spawn a subagent (the backup plugin's
144
- // `backup-message`) whose session JSONL lands under `sessions/` after we
145
- // already staged. Without this second pass that file would sit dirty in
146
- // the worktree until the NEXT backup cycle, which would then commit it
147
- // and create another orphan via the same path — a steady-state of
148
- // one-cycle-behind churn. Re-status, filter to `sessions/` additions
149
- // only (don't accidentally stage user work that arrived during the
150
- // window), and force-add anything new.
151
- const reStatus = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
152
- cwd,
153
- timeoutMs: COMMIT_TIMEOUT_MS,
154
- })
155
- if (reStatus.exitCode === 0) {
156
- const lateForce = selectForcePaths(parsePorcelain(reStatus.stdout), cwd, ['sessions/'])
157
- if (lateForce.length > 0) {
158
- const lateAdd = await deps.gitSpawn([...repo.gitArgs, 'add', '-f', '--', ...lateForce], {
191
+ // The message subagent may create a sessions/ path after the first snapshot.
192
+ // Re-read only for those paths; other new work must wait for the next pass.
193
+ const reStatus = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
194
+ cwd,
195
+ timeoutMs: COMMIT_TIMEOUT_MS,
196
+ })
197
+ const lateEntries = reStatus.exitCode === 0 ? parsePorcelain(reStatus.stdout) : []
198
+ const lateForce = selectForcePaths(lateEntries, cwd, ['sessions/'])
199
+ const selected = uniquePaths([...snapshot.paths, ...snapshot.forcePaths, ...lateForce]).filter(
200
+ (path) => !snapshot.untrackedPaths.has(path) || hasDirectoryEntry(join(cwd, path)),
201
+ )
202
+ const selectedSet = new Set(selected)
203
+ // Porcelain still reports tracked deletions not yet committed by another
204
+ // writer; absent paths no longer reported after the message window were
205
+ // already committed and cannot be passed to git commit --only.
206
+ const reported = new Set((reStatus.exitCode === 0 ? lateEntries : entries).flatMap((entry) => entry.paths))
207
+ const paths = selected.filter((path) => hasDirectoryEntry(join(cwd, path)) || reported.has(path))
208
+ if (paths.length === 0) return { ok: true, kind: 'clean' }
209
+
210
+ // --only constructs Git's own temporary index from the current HEAD and
211
+ // refreshes the real index for just these paths. Only previously untracked
212
+ // paths need intent-to-add entries in the real index for pathspec matching.
213
+ const candidates = uniquePaths(
214
+ [...entries, ...lateEntries]
215
+ .filter((entry) => entry.kind === 'untracked')
216
+ .flatMap((entry) => entry.paths)
217
+ .filter((path) => selectedSet.has(path) && hasDirectoryEntry(join(cwd, path))),
218
+ )
219
+ if (candidates.length > 0) {
220
+ const intent = await deps.gitSpawn([...repo.gitArgs, 'add', '-N', '-f', '--', ...candidates], {
159
221
  cwd,
160
222
  timeoutMs: COMMIT_TIMEOUT_MS,
161
223
  })
162
- if (lateAdd.exitCode !== 0) {
163
- return { ok: false, kind: 'commit-failed', reason: `git add -f (post-message) failed: ${shortErr(lateAdd)}` }
164
- }
224
+ if (intent.exitCode !== 0)
225
+ return { ok: false, kind: 'commit-failed', reason: `git add -N failed: ${shortErr(intent)}` }
226
+ }
227
+ const commit = await deps.gitSpawn(
228
+ [...repo.gitArgs, 'commit', '--only', '-m', sanitizeCommitMessage(message), '--', ...paths],
229
+ {
230
+ cwd,
231
+ timeoutMs: COMMIT_TIMEOUT_MS,
232
+ },
233
+ )
234
+ if (commit.exitCode !== 0) {
235
+ // A concurrent whole-index commit may have consumed the selected paths.
236
+ const pending = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--', ...paths], {
237
+ cwd,
238
+ timeoutMs: COMMIT_TIMEOUT_MS,
239
+ })
240
+ if (pending.exitCode === 0 && pending.stdout === '') return { ok: true, kind: 'clean' }
241
+ return { ok: false, kind: 'commit-failed', reason: `git commit failed: ${shortErr(commit)}` }
165
242
  }
243
+ } finally {
244
+ await rm(indexDir, { recursive: true, force: true })
166
245
  }
167
246
 
168
- const safeMessage = sanitizeCommitMessage(message)
169
- const commit = await deps.gitSpawn([...repo.gitArgs, 'commit', '-m', safeMessage], {
170
- cwd,
171
- timeoutMs: COMMIT_TIMEOUT_MS,
172
- })
173
- if (commit.exitCode !== 0)
174
- return { ok: false, kind: 'commit-failed', reason: `git commit failed: ${shortErr(commit)}` }
175
-
176
247
  if (!pushToOrigin) return { ok: true, kind: 'committed' }
177
248
 
178
249
  const plan = await resolvePushPlan(cwd, deps, repo)
@@ -422,7 +493,7 @@ function selectStagingSnapshot(entries: readonly PorcelainEntry[], cwd: string):
422
493
  if (isAgentOwned(path)) continue
423
494
  const forceAdded = FORCE_ADD_PREFIXES.some((prefix) => path.startsWith(prefix))
424
495
  if (entry.kind === 'untracked') {
425
- if (forceAdded || !hasDirectoryEntry(join(cwd, path))) continue
496
+ if (forceAdded || !hasDirectoryEntry(join(cwd, path)) || isNestedRepository(join(cwd, path))) continue
426
497
  untrackedPaths.add(path)
427
498
  }
428
499
  paths.push(path)
@@ -436,6 +507,8 @@ async function retryAfterVanishedUntracked(
436
507
  deps: BackupRunnerDeps,
437
508
  repo: AgentGit,
438
509
  snapshot: StagingSnapshot,
510
+ env?: Record<string, string>,
511
+ force = false,
439
512
  ): Promise<GitSpawnResult | undefined> {
440
513
  const reread = await deps.gitSpawn([...repo.gitArgs, 'status', '--porcelain=v1', '-z', '--untracked-files=all'], {
441
514
  cwd,
@@ -455,7 +528,11 @@ async function retryAfterVanishedUntracked(
455
528
 
456
529
  const retryPaths = snapshot.paths.filter((path) => !vanished.has(path))
457
530
  if (retryPaths.length === 0) return { exitCode: 0, stdout: '', stderr: '', timedOut: false }
458
- return deps.gitSpawn([...repo.gitArgs, 'add', '--', ...retryPaths], { cwd, timeoutMs: COMMIT_TIMEOUT_MS })
531
+ return deps.gitSpawn([...repo.gitArgs, 'add', ...(force ? ['-f'] : []), '--', ...retryPaths], {
532
+ cwd,
533
+ timeoutMs: COMMIT_TIMEOUT_MS,
534
+ env,
535
+ })
459
536
  }
460
537
 
461
538
  function selectForcePaths(
@@ -476,6 +553,11 @@ function hasDirectoryEntry(path: string): boolean {
476
553
  return lstatSync(path, { throwIfNoEntry: false }) !== undefined
477
554
  }
478
555
 
556
+ function isNestedRepository(path: string): boolean {
557
+ if (!lstatSync(path, { throwIfNoEntry: false })?.isDirectory()) return false
558
+ return hasDirectoryEntry(join(path, '.git'))
559
+ }
560
+
479
561
  function uniquePaths(paths: readonly string[]): string[] {
480
562
  return [...new Set(paths)]
481
563
  }
@@ -1,9 +1,9 @@
1
- import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
1
+ import { appendFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
2
2
  import { join } from 'node:path'
3
3
 
4
4
  import { z } from 'zod'
5
5
 
6
- import { bashTool, readTool, type Subagent, writeTool } from '@/plugin'
6
+ import { bashTool, readTool, type Subagent } from '@/plugin'
7
7
 
8
8
  const messagePayloadSchema = z.object({
9
9
  agentDir: z.string(),
@@ -33,9 +33,8 @@ A periodic backup is about to commit dirty files in the agent folder. Your only
33
33
  The user message gives you:
34
34
  - The output of \`git status --porcelain=v1 --untracked-files=all\` (truncated)
35
35
  - The output of \`git diff --cached --stat\` (truncated)
36
- - An absolute file path you must write the commit message to
37
36
 
38
- # What to write
37
+ # What to return
39
38
 
40
39
  A single commit message in conventional-commit-ish style:
41
40
  - Subject line under 72 characters, imperative mood, lowercase first word, no trailing period.
@@ -49,11 +48,9 @@ Examples:
49
48
 
50
49
  # Hard rules
51
50
 
52
- 1. **Write exactly one file.** Use the \`write\` tool with the absolute path the user gave you. Do not write anywhere else. Do not read other files. Do not run commands.
53
- 2. **Output is the file contents only.** No prose to the user, no explanation, no apologies. The runner ignores everything except the file you wrote.
54
- 3. **Be honest about uncertainty.** If the diff looks like a mix of unrelated changes, write \`chore: backup\` rather than guessing a misleading subject.
55
- 4. **Never include secrets, API keys, or paths that would identify the user's machine.** Stick to repo-relative descriptions.
56
- 5. **Stop when the file is written.** Do not continue after the \`write\` succeeds.`
51
+ 1. **Return only the commit message as your final answer.** No prose, explanation, or apologies. Do not write files, read other files, or run commands.
52
+ 2. **Be honest about uncertainty.** If the diff looks like a mix of unrelated changes, return \`chore: backup\` rather than guessing a misleading subject.
53
+ 3. **Never include secrets, API keys, or paths that would identify the user's machine.** Stick to repo-relative descriptions.`
57
54
 
58
55
  export const DIAGNOSE_FAILURE_SYSTEM_PROMPT = `You are typeclaw's backup failure-diagnosis subagent.
59
56
 
@@ -68,7 +65,7 @@ The user message gives you:
68
65
 
69
66
  # Tools
70
67
 
71
- You have \`bash\`, \`read\`, and \`write\`. Use \`bash\` to inspect git state (\`git status\`, \`git remote -v\`, \`git log -5 --oneline\`, \`git config --get remote.origin.url\`).
68
+ You have \`bash\` and \`read\`. Use \`bash\` to inspect git state (\`git status\`, \`git remote -v\`, \`git log -5 --oneline\`, \`git config --get remote.origin.url\`).
72
69
 
73
70
  # Allowed actions
74
71
 
@@ -77,7 +74,7 @@ You MAY:
77
74
  - Set up a missing upstream branch via \`git push -u origin <branch>\` if it's clear that's the only issue.
78
75
  - Retry \`git push\` once after fixing a clear, narrow issue.
79
76
 
80
- **When you run \`git push\` (either to set upstream or to retry), do not add an acknowledgement argument.** Security guards are permission-only; this recovery subagent inherits the operator role that launched the approved backup workflow. If your push retry fails again, write the diagnosis and stop.
77
+ **When you run \`git push\` (either to set upstream or to retry), do not add an acknowledgement argument.** Security guards are permission-only; this recovery subagent inherits the operator role that launched the approved backup workflow. If your push retry fails again, return the diagnosis and stop.
81
78
 
82
79
  You MUST NOT:
83
80
  - Force-push (\`--force\`, \`--force-with-lease\`).
@@ -87,16 +84,16 @@ You MUST NOT:
87
84
 
88
85
  # Output
89
86
 
90
- Write a brief diagnosis (3-8 lines) describing:
87
+ Return a brief diagnosis (3-8 lines) describing:
91
88
  1. What the actual cause was (e.g. "no upstream tracking branch", "remote is ahead and rebase conflicted", "auth failed").
92
89
  2. What you did about it (or why you didn't).
93
90
  3. What the user should do next, if anything.
94
91
 
95
- Append your diagnosis to \`<agentDir>/sessions/backup-diagnostics.log\` with a timestamp prefix. Keep it short — this log is for the human, not the model.
92
+ Return only the diagnosis as your final answer. The backup runtime appends it with a timestamp to \`<agentDir>/sessions/backup-diagnostics.log\`; do not write that file yourself. Keep it short — this log is for the human, not the model.
96
93
 
97
94
  # When in doubt
98
95
 
99
- Do nothing destructive. Write the diagnosis and stop. The user can recover manually.`
96
+ Do nothing destructive. Return the diagnosis and stop. The user can recover manually.`
100
97
 
101
98
  export type CreateCommitMessageSubagentOptions = {
102
99
  fallbackMessage?: string
@@ -108,16 +105,24 @@ export function createCommitMessageSubagent(
108
105
  const fallback = options.fallbackMessage ?? 'chore: backup'
109
106
  return {
110
107
  systemPrompt: COMMIT_MESSAGE_SYSTEM_PROMPT,
111
- tools: [writeTool],
108
+ tools: [],
112
109
  payloadSchema: messagePayloadSchema,
113
110
  inFlightKey: (payload) => payload.agentDir,
114
111
  handler: async (ctx, runSession) => {
115
- const userPrompt = buildCommitMessagePrompt(ctx.payload)
112
+ let message = ''
116
113
  try {
117
- await runSession({ userPrompt })
114
+ await runSession({
115
+ userPrompt: buildCommitMessagePrompt(ctx.payload),
116
+ onFinalMessage: (text) => {
117
+ message = text ?? ''
118
+ },
119
+ })
118
120
  } catch {
119
- await writeFile(ctx.payload.outputPath, fallback, 'utf8').catch(() => undefined)
121
+ message = ''
120
122
  }
123
+ await writeFile(ctx.payload.outputPath, normalizeCommitMessageResponse(message) || fallback, 'utf8').catch(
124
+ () => undefined,
125
+ )
121
126
  },
122
127
  }
123
128
  }
@@ -125,24 +130,51 @@ export function createCommitMessageSubagent(
125
130
  export function createDiagnoseFailureSubagent(): Subagent<DiagnoseFailurePayload> {
126
131
  return {
127
132
  systemPrompt: DIAGNOSE_FAILURE_SYSTEM_PROMPT,
128
- tools: [bashTool, readTool, writeTool],
133
+ tools: [bashTool, readTool],
129
134
  payloadSchema: diagnosePayloadSchema,
130
135
  inFlightKey: (payload) => payload.agentDir,
131
136
  handler: async (ctx, runSession) => {
132
- const userPrompt = buildDiagnosePrompt(ctx.payload)
137
+ let diagnosis = ''
133
138
  try {
134
- await runSession({ userPrompt })
139
+ await runSession({
140
+ userPrompt: buildDiagnosePrompt(ctx.payload),
141
+ onFinalMessage: (text) => {
142
+ diagnosis = text ?? ''
143
+ },
144
+ })
135
145
  } catch {
136
- // Diagnosis is advisory; failures here must not propagate.
146
+ return
147
+ }
148
+ if (diagnosis.trim()) {
149
+ await appendFile(
150
+ join(ctx.payload.agentDir, 'sessions', 'backup-diagnostics.log'),
151
+ `${new Date().toISOString()} ${diagnosis.trim()}\n`,
152
+ 'utf8',
153
+ ).catch(() => undefined)
137
154
  }
138
155
  },
139
156
  }
140
157
  }
141
158
 
159
+ // The runner already bounds subject length and preserves an optional body.
160
+ // Remove model presentation wrappers here so neither a fence label nor quotes
161
+ // can become the Git subject line.
162
+ function normalizeCommitMessageResponse(raw: string): string {
163
+ const trimmed = raw.trim()
164
+ const fenced = trimmed.match(/^```[^\n]*\n([\s\S]*?)\n```$/)
165
+ const content = (fenced?.[1] ?? trimmed).trim()
166
+ const pair =
167
+ content.startsWith('"') && content.endsWith('"')
168
+ ? '"'
169
+ : content.startsWith("'") && content.endsWith("'")
170
+ ? "'"
171
+ : null
172
+ return (pair && content.length >= 2 ? content.slice(1, -1) : content).trim()
173
+ }
174
+
142
175
  function buildCommitMessagePrompt(p: CommitMessagePayload): string {
143
176
  return [
144
- `Agent folder: ${p.agentDir}`,
145
- `Write the commit message to: ${p.outputPath}`,
177
+ 'Choose a commit message for these changes:',
146
178
  '',
147
179
  '## git status --porcelain=v1 --untracked-files=all',
148
180
  '```',
@@ -154,7 +186,7 @@ function buildCommitMessagePrompt(p: CommitMessagePayload): string {
154
186
  p.diffstat.trim() || '(empty)',
155
187
  '```',
156
188
  '',
157
- 'Write the commit message and stop.',
189
+ 'Return the commit message and stop.',
158
190
  ].join('\n')
159
191
  }
160
192
 
@@ -174,7 +206,7 @@ function buildDiagnosePrompt(p: DiagnoseFailurePayload): string {
174
206
  p.stdout.trim() || '(empty)',
175
207
  '```',
176
208
  '',
177
- 'Inspect the repo, do the smallest safe action if any, and write your diagnosis to the log file.',
209
+ 'Inspect the repo, do the smallest safe action if any, and return your diagnosis.',
178
210
  ].join('\n')
179
211
  }
180
212
 
@@ -345,6 +345,7 @@ const SAFE_GH_OPERATIONS: Readonly<Record<string, ReadonlySet<string>>> = {
345
345
  'ready',
346
346
  'merge',
347
347
  'edit',
348
+ 'create',
348
349
  ]),
349
350
  issue: new Set(['view', 'list', 'status', 'comment', 'close', 'reopen', 'create']),
350
351
  label: new Set(['list', 'create', 'edit', 'delete', 'clone']),
@@ -483,7 +484,7 @@ function isCredentialSafeGhArgs(args: readonly string[]): boolean {
483
484
  if (endpoint === null || endpoint.includes('://')) return false
484
485
  }
485
486
  if (!SAFE_GH_OPERATIONS[command]?.has(operation)) return false
486
- if (command === 'issue' && operation === 'create' && !isSafeCreateArgs(args)) {
487
+ if ((command === 'issue' || command === 'pr') && operation === 'create' && !isSafeCreateArgs(command, args)) {
487
488
  return false
488
489
  }
489
490
  if (command === 'pr' && operation === 'edit' && !isSafePrEditArgs(args)) {
@@ -509,7 +510,7 @@ function isCredentialSafeGhArgs(args: readonly string[]): boolean {
509
510
  return true
510
511
  }
511
512
 
512
- function isSafeCreateArgs(args: readonly string[]): boolean {
513
+ function isSafeCreateArgs(command: 'issue' | 'pr', args: readonly string[]): boolean {
513
514
  if (extractRepoFlag(args) === null) return false
514
515
  const title = findFlagValue(args, ['--title'])
515
516
  const body = findFlagValue(args, ['--body', '-b'])
@@ -527,9 +528,35 @@ function isSafeCreateArgs(args: readonly string[]): boolean {
527
528
  '--fill-verbose',
528
529
  ])
529
530
  if (args.some((arg) => forbidden.has(arg.includes('=') ? arg.slice(0, arg.indexOf('=')) : arg))) return false
531
+ if (command === 'pr' && !hasExplicitPrRefs(args)) return false
530
532
  return true
531
533
  }
532
534
 
535
+ // Without `--head`, `gh pr create` interrogates the checkout and offers to push
536
+ // or fork, running git with the minted token in its environment. An explicit
537
+ // head (plus `--repo`, required above) keeps gh to read-only remote/config
538
+ // lookups that tolerate running outside any checkout. gh's flag parser keeps
539
+ // the LAST value of a repeated flag, so a later `--head=` or `-H ''` would
540
+ // silently empty the head this check saw first: repeats are refused outright.
541
+ const PR_CREATE_REF_FLAGS: readonly (readonly string[])[] = [
542
+ ['--head', '-H'],
543
+ ['--base', '-B'],
544
+ ['--repo', '-R'],
545
+ ['--title', '-t'],
546
+ ['--body', '-b'],
547
+ ]
548
+
549
+ function hasExplicitPrRefs(args: readonly string[]): boolean {
550
+ for (const names of PR_CREATE_REF_FLAGS) {
551
+ const occurrences = args.filter((arg) => names.some((name) => arg === name || arg.startsWith(`${name}=`)))
552
+ if (occurrences.length > 1) return false
553
+ }
554
+ const head = findFlagValue(args, ['--head', '-H'])
555
+ const base = findFlagValue(args, ['--base', '-B'])
556
+ if (head === null || head.trim() === '' || base === null || base.trim() === '') return false
557
+ return !head.startsWith('@') && !base.startsWith('@')
558
+ }
559
+
533
560
  // `gh pr edit` with no field flag drops into an interactive survey and spawns
534
561
  // $EDITOR for the body — a child process that inherits the minted token, the
535
562
  // same shape `gh pr merge --delete-branch` is denied for. Requiring at least one
@@ -1443,6 +1470,11 @@ export function effectiveGhTokensForAuthenticatedUserEndpoint(
1443
1470
  return result
1444
1471
  }
1445
1472
 
1473
+ export function effectiveGhTokensForCommand(command: string, env: GhAuthEnv): Array<string | undefined> {
1474
+ const tokens = tokenize(command)
1475
+ return findGhInvocations(tokens).map((start) => effectiveGhTokenForInvocation(tokens, start, env))
1476
+ }
1477
+
1446
1478
  export function usesGhApiAuthenticatedUserEndpoint(command: string): boolean {
1447
1479
  return effectiveGhTokensForAuthenticatedUserEndpoint(command, {}).length > 0
1448
1480
  }
@@ -0,0 +1,135 @@
1
+ import type { GitCommandDecision, GitResolvers } from './git-command'
2
+
3
+ // Destination grant for `git push` by actors that lack the `gitExfil` bypass:
4
+ // the repos the operator configured for the GitHub channel
5
+ // (`channels.github.repos`) under App auth. The security plugin asks
6
+ // this module whether a push it would otherwise block targets a granted repo;
7
+ // github-cli-auth then re-resolves the same command to fund it and must land on
8
+ // the exact destination the grant authorized, or the push is refused.
9
+ //
10
+ // The grant authorizes publishing branch CONTENT to that repo. It is not a
11
+ // confidentiality control: git objects are not scanned for secrets.
12
+
13
+ export type GithubPushGrant = { repos: readonly string[] }
14
+ // `command` is what actually runs: the model's spelling is discarded so repo
15
+ // config (remote.<name>.push mappings with `+`, push.default=upstream,
16
+ // push.followTags, submodule recursion) and abbreviated tag names cannot widen a
17
+ // one-branch grant. A source that is not refs/heads/<branch> fails to resolve.
18
+ export type GrantedPush = { repoSlug: string; pushUrls: readonly string[]; command: string }
19
+ export type GrantedPushDecision = { kind: 'allow'; push: GrantedPush } | { kind: 'deny'; reason: string }
20
+
21
+ // One local branch name (or HEAD) pushed to the same-named remote branch.
22
+ // Excludes `src:dst` retargeting, `:dst` deletion, `+` force, reflog `@{`,
23
+ // `..` traversal, leading `-`, and tag/full refs.
24
+ const PLAIN_BRANCH = /^(?!-)(?!refs\/)(?!.*\.\.)(?!.*@\{)[A-Za-z0-9._/-]+$/
25
+
26
+ export async function resolveGrantedPush(
27
+ decision: GitCommandDecision,
28
+ grant: GithubPushGrant,
29
+ resolvers: Pick<GitResolvers, 'resolveCurrentBranch'>,
30
+ ): Promise<GrantedPushDecision> {
31
+ const provenance = decision.kind === 'inject' ? decision.pushProvenance : undefined
32
+ const needsHead = provenance?.kind === 'configured-remote' && provenance.refspecs[0] === 'HEAD'
33
+ let currentBranch: string | null = null
34
+ if (needsHead) {
35
+ try {
36
+ currentBranch = await resolvers.resolveCurrentBranch(provenance.sourceCwd)
37
+ } catch {
38
+ currentBranch = null
39
+ }
40
+ }
41
+ return authorizeGrantedPush(decision, grant, currentBranch)
42
+ }
43
+
44
+ export function authorizeGrantedPush(
45
+ decision: GitCommandDecision,
46
+ grant: GithubPushGrant,
47
+ currentBranch: string | null = null,
48
+ ): GrantedPushDecision {
49
+ if (decision.kind !== 'inject' || decision.access !== 'write') {
50
+ return deny('the push could not be resolved to a single GitHub repository')
51
+ }
52
+ const provenance = decision.pushProvenance
53
+ if (provenance?.kind !== 'configured-remote' || !provenance.complete) {
54
+ return deny('only a push through a configured remote of a resolvable checkout can use the grant')
55
+ }
56
+ const [repoSlug, ...extra] = provenance.repoSlugs.map(canonical)
57
+ if (repoSlug === undefined || extra.length > 0) {
58
+ return deny('the remote must point at exactly one GitHub repository')
59
+ }
60
+ if (!grant.repos.map(canonical).includes(repoSlug)) {
61
+ return deny(`\`${repoSlug}\` is not listed in channels.github.repos`)
62
+ }
63
+ const [refspec, ...moreRefspecs] = provenance.refspecs
64
+ if (refspec === undefined || moreRefspecs.length > 0 || !PLAIN_BRANCH.test(refspec)) {
65
+ return deny('the grant covers pushing exactly one branch by name (e.g. `git -C <checkout> push <remote> <branch>`)')
66
+ }
67
+ const branch = refspec === 'HEAD' ? currentBranch : refspec
68
+ if (branch === null || branch === 'HEAD' || !PLAIN_BRANCH.test(branch)) {
69
+ return deny('`HEAD` must be a checked-out branch; name the branch explicitly')
70
+ }
71
+ const command = buildGrantedPushCommand({
72
+ cwd: provenance.sourceCwd,
73
+ remote: provenance.remote,
74
+ branch,
75
+ setUpstream: provenance.setUpstream,
76
+ })
77
+ return { kind: 'allow', push: { repoSlug, pushUrls: provenance.pushUrls, command } }
78
+ }
79
+
80
+ export function buildGrantedPushCommand(options: {
81
+ cwd: string
82
+ remote: string
83
+ branch: string
84
+ setUpstream: boolean
85
+ }): string {
86
+ const ref = `refs/heads/${options.branch}`
87
+ return [
88
+ 'git',
89
+ '-C',
90
+ quote(options.cwd),
91
+ 'push',
92
+ '--no-follow-tags',
93
+ '--recurse-submodules=no',
94
+ ...(options.setUpstream ? ['--set-upstream'] : []),
95
+ quote(options.remote),
96
+ quote(`${ref}:${ref}`),
97
+ ].join(' ')
98
+ }
99
+
100
+ function quote(value: string): string {
101
+ return `'${value.replaceAll("'", "'\\''")}'`
102
+ }
103
+
104
+ const grantedPushes = new Map<string, GrantedPush>()
105
+
106
+ export function recordGrantedPush(callId: string, push: GrantedPush): void {
107
+ grantedPushes.set(callId, push)
108
+ }
109
+
110
+ export function takeGrantedPush(callId: string): GrantedPush | undefined {
111
+ const push = grantedPushes.get(callId)
112
+ grantedPushes.delete(callId)
113
+ return push
114
+ }
115
+
116
+ export function matchesGrantedPush(decision: GitCommandDecision, granted: GrantedPush): boolean {
117
+ if (decision.kind !== 'inject' || decision.access !== 'write') return false
118
+ const provenance = decision.pushProvenance
119
+ if (provenance?.kind !== 'configured-remote') return false
120
+ const slugs = provenance.repoSlugs.map(canonical)
121
+ return (
122
+ slugs.length === 1 &&
123
+ slugs[0] === granted.repoSlug &&
124
+ provenance.pushUrls.length === granted.pushUrls.length &&
125
+ provenance.pushUrls.every((url, index) => url === granted.pushUrls[index])
126
+ )
127
+ }
128
+
129
+ function canonical(slug: string): string {
130
+ return slug.toLocaleLowerCase().replace(/\.git$/i, '')
131
+ }
132
+
133
+ function deny(reason: string): GrantedPushDecision {
134
+ return { kind: 'deny', reason }
135
+ }