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