@teamclaws/teamclaw 2026.8.1 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/cli.mjs +318 -17
  2. package/dist/index.js +54 -32
  3. package/dist/src/config.js +57 -2
  4. package/dist/src/controller/auth-routes.js +129 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-intake.js +895 -0
  7. package/dist/src/controller/controller-planning.js +814 -0
  8. package/dist/src/controller/controller-routes.js +195 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +338 -50
  11. package/dist/src/controller/controller-tools.js +14 -7
  12. package/dist/src/controller/github-auth.js +2 -1
  13. package/dist/src/controller/http-server.js +290 -6003
  14. package/dist/src/controller/kickoff-orchestrator.js +33 -43
  15. package/dist/src/controller/message-delivery.js +31 -0
  16. package/dist/src/controller/message-routes.js +114 -0
  17. package/dist/src/controller/orchestration-manifest.js +11 -93
  18. package/dist/src/controller/preview-manager.js +51 -3
  19. package/dist/src/controller/preview-proxy.js +98 -0
  20. package/dist/src/controller/profile-switch.js +309 -0
  21. package/dist/src/controller/project-registry.js +294 -0
  22. package/dist/src/controller/prompt-injector.js +19 -9
  23. package/dist/src/controller/provisioning/backend-contract.js +9 -0
  24. package/dist/src/controller/provisioning/container-shared.js +64 -0
  25. package/dist/src/controller/provisioning/docker.js +214 -0
  26. package/dist/src/controller/provisioning/kubernetes.js +244 -0
  27. package/dist/src/controller/provisioning/plugin-root.js +41 -0
  28. package/dist/src/controller/provisioning/process-supervisor.js +190 -0
  29. package/dist/src/controller/provisioning-config.js +239 -0
  30. package/dist/src/controller/repo-routes.js +129 -0
  31. package/dist/src/controller/report-routes.js +56 -0
  32. package/dist/src/controller/role-inference.js +231 -20
  33. package/dist/src/controller/route-table.js +375 -0
  34. package/dist/src/controller/security.js +775 -0
  35. package/dist/src/controller/status-routes.js +287 -0
  36. package/dist/src/controller/task-assignment.js +511 -0
  37. package/dist/src/controller/task-cleanup.js +258 -0
  38. package/dist/src/controller/task-execution.js +271 -0
  39. package/dist/src/controller/task-results.js +471 -0
  40. package/dist/src/controller/task-router.js +74 -4
  41. package/dist/src/controller/task-routes.js +703 -0
  42. package/dist/src/controller/teamauto-routes.js +124 -0
  43. package/dist/src/controller/tunnel-manager.js +41 -8
  44. package/dist/src/controller/tunnel-routes.js +225 -0
  45. package/dist/src/controller/ui-assets.js +68 -0
  46. package/dist/src/controller/websocket.js +6 -2
  47. package/dist/src/controller/webui-routes.js +49 -0
  48. package/dist/src/controller/worker-provisioning.js +69 -953
  49. package/dist/src/controller/worker-routes.js +188 -0
  50. package/dist/src/controller/workflow-routes.js +407 -0
  51. package/dist/src/controller/workspace-routes.js +200 -0
  52. package/dist/src/git-collaboration.js +4 -9
  53. package/dist/src/identity.js +15 -3
  54. package/dist/src/interaction-contracts.js +7 -7
  55. package/dist/src/openclaw-workspace.js +40 -18
  56. package/dist/src/profile-loader.js +604 -0
  57. package/dist/src/profiles/banking.json +202 -0
  58. package/dist/src/profiles/crossborder-ecom.json +253 -0
  59. package/dist/src/profiles/insurance.json +157 -0
  60. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  61. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  62. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  63. package/dist/src/profiles/schema.json +281 -0
  64. package/dist/src/profiles/securities.json +137 -0
  65. package/dist/src/profiles/software-rd.json +264 -0
  66. package/dist/src/profiles/trading-co.json +200 -0
  67. package/dist/src/prompt-policy.js +42 -17
  68. package/dist/src/protocol.js +66 -3
  69. package/dist/src/role-ids.js +29 -0
  70. package/dist/src/roles.js +54 -13
  71. package/dist/src/session-roles.js +14 -0
  72. package/dist/src/shared/clarification-schema.js +65 -0
  73. package/dist/src/shared/github-auth.js +15 -0
  74. package/dist/src/shared/kickoff-prompt.js +37 -0
  75. package/dist/src/shared/utils.js +47 -0
  76. package/dist/src/state.js +275 -11
  77. package/dist/src/task-executor.js +7 -17
  78. package/dist/src/teamauto/github-client.js +18 -0
  79. package/dist/src/teamauto/repo-sync.js +228 -6
  80. package/dist/src/teamauto/scanner.js +40 -12
  81. package/dist/src/teamauto/scheduler.js +231 -12
  82. package/dist/src/types.js +77 -16
  83. package/dist/src/ui/app.js +1434 -82
  84. package/dist/src/ui/github-login.html +1 -0
  85. package/dist/src/ui/index.html +144 -45
  86. package/dist/src/ui/style.css +194 -0
  87. package/dist/src/worker/http-handler.js +59 -0
  88. package/dist/src/worker/prompt-injector.js +44 -8
  89. package/dist/src/worker/skill-installer.js +6 -10
  90. package/dist/src/worker/tools.js +20 -10
  91. package/dist/src/worker/worker-service.js +93 -7
  92. package/index.ts +61 -32
  93. package/openclaw.plugin.json +50 -2
  94. package/package.json +3 -2
  95. package/src/config.ts +57 -2
  96. package/src/controller/auth-routes.ts +157 -0
  97. package/src/controller/clarification-routes.ts +404 -0
  98. package/src/controller/controller-intake.ts +1113 -0
  99. package/src/controller/controller-planning.ts +1037 -0
  100. package/src/controller/controller-routes.ts +237 -0
  101. package/src/controller/controller-runs.ts +239 -0
  102. package/src/controller/controller-service.ts +422 -50
  103. package/src/controller/controller-tools.ts +16 -9
  104. package/src/controller/github-auth.ts +28 -63
  105. package/src/controller/http-server.ts +336 -6964
  106. package/src/controller/kickoff-orchestrator.ts +69 -45
  107. package/src/controller/message-delivery.ts +52 -0
  108. package/src/controller/message-routes.ts +137 -0
  109. package/src/controller/orchestration-manifest.ts +14 -100
  110. package/src/controller/preview-manager.ts +53 -3
  111. package/src/controller/preview-proxy.ts +127 -0
  112. package/src/controller/profile-switch.ts +396 -0
  113. package/src/controller/project-registry.ts +361 -0
  114. package/src/controller/prompt-injector.ts +23 -8
  115. package/src/controller/provisioning/backend-contract.ts +51 -0
  116. package/src/controller/provisioning/container-shared.ts +84 -0
  117. package/src/controller/provisioning/docker.ts +260 -0
  118. package/src/controller/provisioning/kubernetes.ts +263 -0
  119. package/src/controller/provisioning/plugin-root.ts +42 -0
  120. package/src/controller/provisioning/process-supervisor.ts +214 -0
  121. package/src/controller/provisioning-config.ts +289 -0
  122. package/src/controller/repo-routes.ts +163 -0
  123. package/src/controller/report-routes.ts +64 -0
  124. package/src/controller/role-inference.ts +260 -22
  125. package/src/controller/route-table.ts +597 -0
  126. package/src/controller/security.ts +899 -0
  127. package/src/controller/status-routes.ts +354 -0
  128. package/src/controller/task-assignment.ts +622 -0
  129. package/src/controller/task-cleanup.ts +344 -0
  130. package/src/controller/task-execution.ts +399 -0
  131. package/src/controller/task-results.ts +556 -0
  132. package/src/controller/task-router.ts +98 -6
  133. package/src/controller/task-routes.ts +812 -0
  134. package/src/controller/teamauto-routes.ts +121 -0
  135. package/src/controller/tunnel-manager.ts +45 -8
  136. package/src/controller/tunnel-routes.ts +231 -0
  137. package/src/controller/ui-assets.ts +70 -0
  138. package/src/controller/websocket.ts +32 -4
  139. package/src/controller/webui-routes.ts +55 -0
  140. package/src/controller/worker-provisioning.ts +83 -1121
  141. package/src/controller/worker-routes.ts +241 -0
  142. package/src/controller/workflow-routes.ts +498 -0
  143. package/src/controller/workspace-routes.ts +222 -0
  144. package/src/git-collaboration.ts +4 -9
  145. package/src/identity.ts +16 -3
  146. package/src/interaction-contracts.ts +7 -7
  147. package/src/openclaw-workspace.ts +44 -18
  148. package/src/profile-loader.ts +816 -0
  149. package/src/profiles/banking.json +202 -0
  150. package/src/profiles/crossborder-ecom.json +253 -0
  151. package/src/profiles/insurance.json +157 -0
  152. package/src/profiles/knowledge/hs-structure.md +97 -0
  153. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  154. package/src/profiles/knowledge/vat-principles.md +85 -0
  155. package/src/profiles/schema.json +281 -0
  156. package/src/profiles/securities.json +137 -0
  157. package/src/profiles/software-rd.json +264 -0
  158. package/src/profiles/trading-co.json +200 -0
  159. package/src/prompt-policy.ts +44 -17
  160. package/src/protocol.ts +72 -2
  161. package/src/role-ids.ts +31 -0
  162. package/src/roles.ts +60 -14
  163. package/src/session-roles.ts +14 -0
  164. package/src/shared/clarification-schema.ts +81 -0
  165. package/src/shared/github-auth.ts +92 -0
  166. package/src/shared/kickoff-prompt.ts +47 -0
  167. package/src/shared/utils.ts +51 -0
  168. package/src/state.ts +326 -10
  169. package/src/task-executor.ts +7 -18
  170. package/src/teamauto/github-client.ts +23 -1
  171. package/src/teamauto/repo-sync.ts +248 -7
  172. package/src/teamauto/scanner.ts +47 -13
  173. package/src/teamauto/scheduler.ts +261 -17
  174. package/src/teamauto/store.ts +12 -0
  175. package/src/types.ts +263 -17
  176. package/src/ui/app.js +1434 -82
  177. package/src/ui/github-login.html +1 -0
  178. package/src/ui/index.html +144 -45
  179. package/src/ui/style.css +194 -0
  180. package/src/worker/http-handler.ts +64 -1
  181. package/src/worker/prompt-injector.ts +48 -8
  182. package/src/worker/skill-installer.ts +6 -10
  183. package/src/worker/tools.ts +21 -10
  184. package/src/worker/worker-service.ts +101 -7
@@ -1,11 +1,16 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
 
3
3
  import type { PluginLogger } from "../../api.js";
4
- import type { GithubAuthManager } from "../controller/github-auth.js";
5
- import type { RoleId, TaskInfo, TeamState } from "../types.js";
4
+ // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
5
+ import type { GithubAuthManager } from "../shared/github-auth.js";
6
+ // Phase 2.3/2.5 (cross-review adopted suggestion): manual-proposal roles
7
+ // validate against the ACTIVE profile and default to its defaultRole instead
8
+ // of hardcoded software role literals.
9
+ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js";
10
+ import type { TaskInfo, TeamState } from "../types.js";
6
11
  import { createGithubClient } from "./github-client.js";
7
12
  import { learnNorms, renderNormsBlock } from "./norms.js";
8
- import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
13
+ import { createRepoSync, teamAutoProjectDir, type TaskDeliveryOracle } from "./repo-sync.js";
9
14
  import { nextFireMs } from "./schedule.js";
10
15
  import { advanceCursors, sweepRepo, type Candidate } from "./scanner.js";
11
16
  import {
@@ -20,6 +25,7 @@ import {
20
25
  type TeamAutoRepoNorms,
21
26
  type TeamAutoRepoProvision,
22
27
  type TeamAutoStore,
28
+ type TeamAutoWriteBack,
23
29
  } from "./store.js";
24
30
 
25
31
  /**
@@ -99,6 +105,31 @@ export function sweepRetryDueAt(failures: number, lastErrorAt: number): number {
99
105
  return lastErrorAt + sweepBackoffMinutes(failures) * 60_000;
100
106
  }
101
107
 
108
+ /**
109
+ * Issue #24: max write-back delivery attempts before the entry is marked
110
+ * terminally failed (failedAt) and never retried again.
111
+ */
112
+ export const TEAMAUTO_WRITEBACK_MAX_ATTEMPTS = 6;
113
+
114
+ /**
115
+ * Issue #24: write-back retry backoff - 1 minute after the 1st failure,
116
+ * doubling per attempt, capped at 2 hours. Over
117
+ * TEAMAUTO_WRITEBACK_MAX_ATTEMPTS attempts this spaces transient GitHub API
118
+ * failures (secondary rate limits, 5xx, token refresh races) across roughly
119
+ * an hour before giving up, instead of the pre-fix behavior (sticky error
120
+ * with no retry/no visibility, then a 20s hammer once the self-heal landed).
121
+ */
122
+ export const WRITEBACK_RETRY_BASE_MS = 60_000;
123
+ export const WRITEBACK_RETRY_MAX_MS = 2 * 60 * 60_000;
124
+ export function writebackBackoffMs(attempts: number): number {
125
+ return Math.min(WRITEBACK_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1), WRITEBACK_RETRY_MAX_MS);
126
+ }
127
+
128
+ /** Epoch ms when a failed write-back becomes due for its next retry. */
129
+ export function writebackRetryDueAt(attempts: number, lastErrorAt: number): number {
130
+ return lastErrorAt + writebackBackoffMs(attempts);
131
+ }
132
+
102
133
  /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
103
134
  export function isAutoPause(reason: string | null | undefined): boolean {
104
135
  return !!reason && reason.startsWith("sweep failed:");
@@ -111,8 +142,103 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
111
142
  pushTeamAutoActivity(store, entry);
112
143
  deps.onActivity?.(entry);
113
144
  }
145
+
146
+ /**
147
+ * Issue #24: a failed write-back used to be a sticky `error` field whose
148
+ * only trace was one warn log line - the completed task's result never
149
+ * reached GitHub and nothing surfaced it. Centralized failure handling:
150
+ * persist the failure (attempts/backoff), expose it in the activity feed,
151
+ * and give up terminally (failedAt) once attempts are exhausted or the
152
+ * caller flags the failure undeliverable.
153
+ */
154
+ function markWritebackFailure(store: TeamAutoStore, entry: TeamAutoWriteBack, message: string, options: { terminal?: boolean } = {}): void {
155
+ entry.error = message;
156
+ entry.attempts = (entry.attempts ?? 0) + 1;
157
+ entry.lastErrorAt = Date.now();
158
+ entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
159
+ const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
160
+ if (gaveUp && !entry.doneAt) {
161
+ entry.failedAt = Date.now();
162
+ recordActivity(store, {
163
+ at: Date.now(),
164
+ repoId: entry.repoId,
165
+ kind: "writeback",
166
+ text: `failed permanently after ${entry.attempts} attempt(s) (${entry.action} #${entry.targetId ?? "-"}, task ${entry.taskId}): ${message}`,
167
+ });
168
+ logger.warn(`TeamAuto: write-back ${entry.taskId} (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}) gave up after ${entry.attempts} attempts: ${message}`);
169
+ return;
170
+ }
171
+ recordActivity(store, {
172
+ at: Date.now(),
173
+ repoId: entry.repoId,
174
+ kind: "writeback",
175
+ text: `failed (attempt ${entry.attempts}/${TEAMAUTO_WRITEBACK_MAX_ATTEMPTS}, retry in ~${Math.max(1, Math.round(writebackBackoffMs(entry.attempts) / 60_000))}min) (${entry.action} #${entry.targetId ?? "-"}): ${message}`,
176
+ });
177
+ logger.warn(`TeamAuto: writeback failed (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}): ${message}`);
178
+ }
179
+
180
+ /**
181
+ * Issue #24: write-back delivery stats surfaced through getStatus() so the
182
+ * repos endpoint, the teamclaw_teamauto_status tool, and the activity feed
183
+ * can see stuck/failed deliveries instead of only warn logs.
184
+ */
185
+ function summarizeWritebacks(store: TeamAutoStore): {
186
+ pending: number;
187
+ errored: number;
188
+ failed: number;
189
+ lastError: {
190
+ taskId: string;
191
+ repoId: string;
192
+ action: string;
193
+ targetId: number | null;
194
+ attempts: number;
195
+ terminal: boolean;
196
+ at: number | null;
197
+ message: string | null;
198
+ } | null;
199
+ } {
200
+ const open = store.writebacks.filter((w) => !w.doneAt);
201
+ const failed = open.filter((w) => w.failedAt);
202
+ const errored = open.filter((w) => w.error && !w.failedAt);
203
+ const lastErrorEntry = open
204
+ .filter((w) => w.error)
205
+ .sort((a, b) => (b.lastErrorAt ?? 0) - (a.lastErrorAt ?? 0))[0];
206
+ return {
207
+ pending: open.length - failed.length - errored.length,
208
+ errored: errored.length,
209
+ failed: failed.length,
210
+ lastError: lastErrorEntry
211
+ ? {
212
+ taskId: lastErrorEntry.taskId,
213
+ repoId: lastErrorEntry.repoId,
214
+ action: lastErrorEntry.action,
215
+ targetId: lastErrorEntry.targetId,
216
+ attempts: lastErrorEntry.attempts ?? 0,
217
+ terminal: Boolean(lastErrorEntry.failedAt),
218
+ at: lastErrorEntry.lastErrorAt ?? null,
219
+ message: lastErrorEntry.error,
220
+ }
221
+ : null,
222
+ };
223
+ }
114
224
  const client = createGithubClient(auth);
115
225
  const sync = createRepoSync(auth, logger);
226
+ // #173 follow-up 5: squash-merge delivery oracle for worktree GC. After a
227
+ // squash merge + branch deletion the task commits are unreachable from
228
+ // origin/<default>, so the rev-list own-count never drains and the worktree
229
+ // is retained forever. Positive proof = a merged PR whose head tip is exactly
230
+ // the worktree's HEAD. Every failure path resolves false (fail toward keep).
231
+ const squashDeliveryOracle: TaskDeliveryOracle = async (repoId, taskId, headTip) => {
232
+ try {
233
+ const [owner, name] = repoId.split("/");
234
+ if (!owner || !name) {
235
+ return false;
236
+ }
237
+ return await client.prHeadDelivered(owner, name, sync.taskBranchName(taskId), headTip);
238
+ } catch {
239
+ return false;
240
+ }
241
+ };
116
242
  const timers = new Map<string, NodeJS.Timeout>();
117
243
  const sweeping = new Set<string>();
118
244
  let running = false;
@@ -426,7 +552,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
426
552
  ].join("\n"),
427
553
  status: "pending",
428
554
  priority: candidate.kind === "takeOwnership" ? "high" : "medium",
429
- assignedRole: candidate.role as RoleId,
555
+ // Candidate.role is RoleId since Phase 2.3 debt item 4 (scanner role
556
+ // set derives from the active team profile) - no cast needed.
557
+ assignedRole: candidate.role,
430
558
  writeMode: candidate.writeMode === "write" ? "write" : "read-only",
431
559
  createdBy: "teamauto",
432
560
  projectDir: teamAutoProjectDir(candidate.repoId),
@@ -456,12 +584,17 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
456
584
  throw new Error(`${repoId} not bound`);
457
585
  }
458
586
  const kind: Candidate["kind"] = input.kind === "takeOwnership" || input.kind === "issueReview" || input.kind === "prReview" || input.kind === "fullReview" ? input.kind : "issueReview";
587
+ // Cross-review adopted suggestion: the caller-supplied role is untrusted
588
+ // input - validate it against the ACTIVE profile (drops unknown and
589
+ // not-in-this-profile ids) and fall back to the profile defaultRole
590
+ // instead of the old hardcoded "developer"/"architect" software literals.
591
+ const role = validateActiveRoleId(input.role) ?? getActiveDefaultRole();
459
592
  const candidate: Candidate = {
460
593
  repoId,
461
594
  key: `${repoId}#manual-${Date.now()}`,
462
595
  kind,
463
596
  number: 0,
464
- role: (input.role || (kind === "takeOwnership" ? "developer" : "architect")) as Candidate["role"],
597
+ role,
465
598
  writeMode: input.writeMode ?? (kind === "takeOwnership" ? "write" : "read-only"),
466
599
  title: input.title.slice(0, 120),
467
600
  reason: "manual proposal from agent tool",
@@ -488,29 +621,54 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
488
621
  // never deliver - drop them instead of accumulating forever.
489
622
  if (state0) {
490
623
  const before = s.writebacks.length;
624
+ const deadOnes: typeof s.writebacks = [];
491
625
  s.writebacks = s.writebacks.filter((w) => {
492
626
  if (w.doneAt) { return true; }
493
627
  const t = state0.tasks[w.taskId];
494
628
  const dead = !t || (t.status === "failed" && !t.result);
495
629
  if (dead) {
496
630
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
631
+ deadOnes.push(w);
497
632
  }
498
633
  return !dead;
499
634
  });
500
635
  if (s.writebacks.length !== before) { await saveTeamAutoStore(s); }
636
+ // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
637
+ // failed-without-result tasks BEFORE the pending loop below, so the
638
+ // terminal worktree cleanup there never ran for them - the single
639
+ // largest leak source. Safety-clean here too (same contract). The
640
+ // filter callback cannot await, hence the post-filter pass.
641
+ for (const w of deadOnes) {
642
+ const t = state0.tasks[w.taskId];
643
+ if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
644
+ const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
645
+ if (r.removed) {
646
+ // #173 follow-up 4: positive removal line - without it a successful
647
+ // terminal cleanup is invisible in logs (only kept/failed logged).
648
+ logger.warn(`TeamAuto: terminal task ${w.taskId} worktree removed (${r.reason})`);
649
+ } else if (!r.reason.includes("already gone")) {
650
+ logger.warn(`TeamAuto: terminal task ${w.taskId} worktree kept: ${r.reason}`);
651
+ }
652
+ }
653
+ }
501
654
  }
502
655
  // Self-heal: an entry whose task later COMPLETED with a result (e.g. the
503
656
  // completion gate rejected an early submission, then a retry succeeded)
504
657
  // must be retried - a sticky error here would silently drop delivery.
658
+ // Issue #24: the retry now respects the per-entry backoff (nextAttemptAt)
659
+ // so a failing write-back no longer hammers GitHub on every 20s pass;
660
+ // legacy entries without a nextAttemptAt (pre-#24 stores) retry once
661
+ // immediately and then enter the normal backoff ladder. Terminally
662
+ // failed entries (failedAt) are never retried again.
505
663
  for (const w of s.writebacks) {
506
- if (w.error && !w.doneAt && state0) {
664
+ if (w.error && !w.doneAt && !w.failedAt && state0) {
507
665
  const t = state0.tasks[w.taskId];
508
- if (t && t.status === "completed" && t.result) {
666
+ if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
509
667
  w.error = null;
510
668
  }
511
669
  }
512
670
  }
513
- const pending = s.writebacks.filter((w) => !w.doneAt && !w.error);
671
+ const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
514
672
  if (!pending.length) {
515
673
  return;
516
674
  }
@@ -527,7 +685,31 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
527
685
  const [owner, name] = entry.repoId.split("/");
528
686
  try {
529
687
  if (task.status === "failed" || !task.result) {
530
- entry.error = task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result";
688
+ // Undeliverable in every future pass: a failed task never gains a
689
+ // result, and "completed without result" cannot recover either.
690
+ // Mark terminal (issue #24) so the entry is counted, surfaced via
691
+ // activity/stats, and never pointlessly retried. Failed-without-
692
+ // result entries are additionally dropped by the dead-letter pass
693
+ // on the next reconcile.
694
+ markWritebackFailure(
695
+ s,
696
+ entry,
697
+ task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result",
698
+ { terminal: true },
699
+ );
700
+ // Terminal write task: its dispatch-time worktree has no delivery
701
+ // path left - remove it when the worker never produced deliverable
702
+ // commits (safety-checked, undelivered work is retained + logged).
703
+ if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
704
+ const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
705
+ if (r.removed) {
706
+ // #173 follow-up 4: positive removal line - symmetric with the
707
+ // boot-GC path which logs both directions.
708
+ logger.warn(`TeamAuto: terminal task ${task.id} worktree removed (${r.reason})`);
709
+ } else if (!r.reason.includes("already gone")) {
710
+ logger.warn(`TeamAuto: terminal task ${task.id} worktree kept: ${r.reason}`);
711
+ }
712
+ }
531
713
  } else {
532
714
  const role = (task.assignedRole ?? "qa") as string;
533
715
  let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
@@ -555,8 +737,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
555
737
  }
556
738
  await sync.removeTaskWorktree(repoId, task.id);
557
739
  } catch (prErr) {
558
- entry.error = `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`;
559
- logger.warn(`TeamAuto: ${entry.error} (${task.id})`);
740
+ markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
560
741
  }
561
742
  }
562
743
  if (entry.action === "issueComment" && entry.targetId) {
@@ -610,15 +791,19 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
610
791
  writebackDone = true;
611
792
  }
612
793
  } else {
613
- entry.error = `unsupported action ${entry.action}`;
794
+ markWritebackFailure(s, entry, `unsupported action ${entry.action}`, { terminal: true });
614
795
  }
615
796
  if (writebackDone) {
616
- recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id})` });
797
+ // Delivery succeeded: clear any transient failure state so a
798
+ // partially-failed entry (e.g. PR opened on an earlier retry)
799
+ // does not linger in the errored/failed stats (issue #24).
800
+ entry.error = null;
801
+ entry.failedAt = null;
802
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id}${entry.attempts ? `, after ${entry.attempts} failed attempt(s)` : ""})` });
617
803
  }
618
804
  }
619
805
  } catch (err) {
620
- entry.error = err instanceof Error ? err.message : String(err);
621
- logger.warn(`TeamAuto: writeback failed (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}): ${entry.error}`);
806
+ markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
622
807
  }
623
808
  void repo;
624
809
  }
@@ -706,6 +891,57 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
706
891
  void reconcileWritebacks();
707
892
  }, 20_000);
708
893
  writebackTimer.unref?.();
894
+ // Boot reconciliation: heal leftover task worktrees whose task is
895
+ // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
896
+ // on its own. Safety-checked: undelivered work is kept and logged.
897
+ void (async () => {
898
+ try {
899
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
900
+ // predicate below classifies EVERY task as terminal - boot GC must
901
+ // not run blind over an unloaded team state (fails toward skip).
902
+ if (!deps.getTeamState()) {
903
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
904
+ return;
905
+ }
906
+ let removed = 0;
907
+ let retained = 0;
908
+ let stale = 0;
909
+ const retainedDetails: string[] = [];
910
+ for (const repo of s.repos) {
911
+ if (!repo.enabled) continue;
912
+ const isTerminal = (taskId: string): boolean => {
913
+ const t = deps.getTeamState()?.tasks[taskId];
914
+ if (t && t.status !== "completed" && t.status !== "failed") return false;
915
+ // Review F1: a terminal task with a pending write-back (push
916
+ // ok / PR failed, 20s-retry window) still needs its worktree -
917
+ // the retry delivers the PR from the surviving branch. Do not
918
+ // GC until the write-back settles (doneAt or dropped). Issue
919
+ // #24: terminally failed write-backs (failedAt) count as settled
920
+ // too - safeRemoveTaskWorktree still retains unpushed work.
921
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
922
+ };
923
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
924
+ removed += r.removed.length;
925
+ retained += r.retained.length;
926
+ stale += r.stale;
927
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
928
+ }
929
+ if (removed || retained || stale) {
930
+ // #173 follow-up 4: per-task retain reasons recorded as activity
931
+ // (PR #167 promised "outcome logged + recorded as activity"); the
932
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
933
+ const detail = retainedDetails.length
934
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
935
+ : "";
936
+ const stalePart = stale ? `, stale ${stale}` : "";
937
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
938
+ await saveTeamAutoStore(s);
939
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
940
+ }
941
+ } catch (err) {
942
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
943
+ }
944
+ })();
709
945
  }
710
946
 
711
947
  async function stop(): Promise<void> {
@@ -720,9 +956,17 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
720
956
  }
721
957
  }
722
958
 
723
- async function getStatus(): Promise<{ repos: TeamAutoRepo[]; budget: TeamAutoStore["budget"]; activity: NonNullable<TeamAutoStore["activity"]> }> {
959
+ async function getStatus(): Promise<{
960
+ repos: TeamAutoRepo[];
961
+ budget: TeamAutoStore["budget"];
962
+ activity: NonNullable<TeamAutoStore["activity"]>;
963
+ writebacks: ReturnType<typeof summarizeWritebacks>;
964
+ }> {
724
965
  const s = await ensureStore();
725
- return { repos: s.repos, budget: s.budget, activity: s.activity ?? [] };
966
+ // Issue #24: failed/stuck write-back deliveries are part of the status
967
+ // payload (repos endpoint + teamclaw_teamauto_status tool) instead of
968
+ // being invisible outside warn logs.
969
+ return { repos: s.repos, budget: s.budget, activity: s.activity ?? [], writebacks: summarizeWritebacks(s) };
726
970
  }
727
971
 
728
972
  async function getActivity(): Promise<NonNullable<TeamAutoStore["activity"]>> {
@@ -88,6 +88,18 @@ export type TeamAutoWriteBack = {
88
88
  error: string | null;
89
89
  /** Joint full-review cycle id: same-cycle sections share one umbrella issue. */
90
90
  cycleKey?: string;
91
+ /**
92
+ * Issue #24: failed delivery attempts so far. Drives the retry backoff and
93
+ * the terminal give-up marker instead of a sticky error that nothing ever
94
+ * retried or surfaced.
95
+ */
96
+ attempts?: number;
97
+ /** Epoch ms of the last failed delivery attempt. */
98
+ lastErrorAt?: number;
99
+ /** Epoch ms when the next retry becomes due (exponential backoff gate). */
100
+ nextAttemptAt?: number;
101
+ /** Terminal marker: set when retry attempts are exhausted; never retried again. */
102
+ failedAt?: number | null;
91
103
  };
92
104
 
93
105
  export type TeamAutoActivityKind = "bind" | "provision" | "sweep" | "task" | "writeback";