@teamclaws/teamclaw 2026.8.0 → 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 (149) hide show
  1. package/cli.mjs +46 -15
  2. package/dist/api.js +1 -0
  3. package/dist/index.js +325 -0
  4. package/dist/src/config.js +412 -0
  5. package/dist/src/controller/clarification-routes.js +315 -0
  6. package/dist/src/controller/controller-capacity.js +14 -0
  7. package/dist/src/controller/controller-intake.js +895 -0
  8. package/dist/src/controller/controller-planning.js +813 -0
  9. package/dist/src/controller/controller-runs.js +175 -0
  10. package/dist/src/controller/controller-service.js +624 -0
  11. package/dist/src/controller/controller-tools.js +587 -0
  12. package/dist/src/controller/delivery-report.js +458 -0
  13. package/dist/src/controller/github-auth.js +564 -0
  14. package/dist/src/controller/http-server.js +284 -0
  15. package/dist/src/controller/kickoff-orchestrator.js +246 -0
  16. package/dist/src/controller/managed-gateway-process.js +286 -0
  17. package/dist/src/controller/message-delivery.js +28 -0
  18. package/dist/src/controller/message-router.js +38 -0
  19. package/dist/src/controller/message-routes.js +114 -0
  20. package/dist/src/controller/orchestration-manifest.js +151 -0
  21. package/dist/src/controller/preview-manager.js +586 -0
  22. package/dist/src/controller/preview-proxy.js +98 -0
  23. package/dist/src/controller/profile-switch.js +289 -0
  24. package/dist/src/controller/project-registry.js +294 -0
  25. package/dist/src/controller/prompt-injector.js +197 -0
  26. package/dist/src/controller/repo-routes.js +63 -0
  27. package/dist/src/controller/role-inference.js +246 -0
  28. package/dist/src/controller/route-table.js +1353 -0
  29. package/dist/src/controller/task-assignment.js +508 -0
  30. package/dist/src/controller/task-cleanup.js +258 -0
  31. package/dist/src/controller/task-execution.js +240 -0
  32. package/dist/src/controller/task-results.js +461 -0
  33. package/dist/src/controller/task-router.js +137 -0
  34. package/dist/src/controller/task-routes.js +703 -0
  35. package/dist/src/controller/teamauto-routes.js +124 -0
  36. package/dist/src/controller/tunnel-manager.js +548 -0
  37. package/dist/src/controller/ui-assets.js +68 -0
  38. package/dist/src/controller/websocket.js +42 -0
  39. package/dist/src/controller/worker-provisioning.js +1674 -0
  40. package/dist/src/controller/worker-routes.js +188 -0
  41. package/dist/src/discovery.js +86 -0
  42. package/dist/src/git-collaboration.js +694 -0
  43. package/dist/src/identity.js +132 -0
  44. package/dist/src/install-defaults.js +1 -0
  45. package/dist/src/interaction-contracts.js +531 -0
  46. package/dist/src/networking.js +91 -0
  47. package/dist/src/openclaw-workspace.js +925 -0
  48. package/dist/src/profile-loader.js +486 -0
  49. package/dist/src/profiles/banking.json +178 -0
  50. package/dist/src/profiles/crossborder-ecom.json +253 -0
  51. package/dist/src/profiles/insurance.json +157 -0
  52. package/dist/src/profiles/knowledge/hs-structure.md +97 -0
  53. package/dist/src/profiles/knowledge/incoterms-2020.md +188 -0
  54. package/dist/src/profiles/knowledge/vat-principles.md +85 -0
  55. package/dist/src/profiles/schema.json +201 -0
  56. package/dist/src/profiles/securities.json +137 -0
  57. package/dist/src/profiles/software-rd.json +264 -0
  58. package/dist/src/profiles/trading-co.json +200 -0
  59. package/dist/src/prompt-policy.js +386 -0
  60. package/dist/src/protocol.js +58 -0
  61. package/dist/src/role-ids.js +29 -0
  62. package/dist/src/roles.js +390 -0
  63. package/dist/src/session-roles.js +14 -0
  64. package/dist/src/state.js +361 -0
  65. package/dist/src/task-executor.js +1023 -0
  66. package/dist/src/teamauto/github-client.js +210 -0
  67. package/dist/src/teamauto/norms.js +85 -0
  68. package/dist/src/teamauto/repo-sync.js +423 -0
  69. package/dist/src/teamauto/scanner.js +207 -0
  70. package/dist/src/teamauto/schedule.js +123 -0
  71. package/dist/src/teamauto/scheduler.js +907 -0
  72. package/dist/src/teamauto/store.js +133 -0
  73. package/dist/src/types.js +290 -0
  74. package/dist/src/ui/app.js +4860 -0
  75. package/dist/src/ui/assets/teamclaw-app-icon.png +0 -0
  76. package/dist/src/ui/github-login.html +296 -0
  77. package/dist/src/ui/index.html +447 -0
  78. package/dist/src/ui/style.css +2805 -0
  79. package/dist/src/worker/http-handler.js +146 -0
  80. package/dist/src/worker/message-queue.js +24 -0
  81. package/dist/src/worker/prompt-injector.js +78 -0
  82. package/dist/src/worker/skill-installer.js +255 -0
  83. package/dist/src/worker/tools.js +541 -0
  84. package/dist/src/worker/worker-service.js +307 -0
  85. package/dist/src/workspace-browser.js +269 -0
  86. package/openclaw.plugin.json +28 -1
  87. package/package.json +3 -2
  88. package/src/config.ts +33 -2
  89. package/src/controller/clarification-routes.ts +404 -0
  90. package/src/controller/controller-intake.ts +1113 -0
  91. package/src/controller/controller-planning.ts +1029 -0
  92. package/src/controller/controller-runs.ts +239 -0
  93. package/src/controller/controller-service.ts +295 -41
  94. package/src/controller/controller-tools.ts +11 -7
  95. package/src/controller/http-server.ts +294 -6971
  96. package/src/controller/kickoff-orchestrator.ts +70 -7
  97. package/src/controller/message-delivery.ts +49 -0
  98. package/src/controller/message-routes.ts +137 -0
  99. package/src/controller/orchestration-manifest.ts +6 -29
  100. package/src/controller/preview-proxy.ts +127 -0
  101. package/src/controller/profile-switch.ts +366 -0
  102. package/src/controller/project-registry.ts +361 -0
  103. package/src/controller/prompt-injector.ts +23 -8
  104. package/src/controller/repo-routes.ts +91 -0
  105. package/src/controller/role-inference.ts +260 -22
  106. package/src/controller/route-table.ts +1616 -0
  107. package/src/controller/task-assignment.ts +618 -0
  108. package/src/controller/task-cleanup.ts +344 -0
  109. package/src/controller/task-execution.ts +356 -0
  110. package/src/controller/task-results.ts +544 -0
  111. package/src/controller/task-router.ts +98 -6
  112. package/src/controller/task-routes.ts +812 -0
  113. package/src/controller/teamauto-routes.ts +121 -0
  114. package/src/controller/ui-assets.ts +70 -0
  115. package/src/controller/websocket.ts +13 -1
  116. package/src/controller/worker-provisioning.ts +32 -4
  117. package/src/controller/worker-routes.ts +241 -0
  118. package/src/identity.ts +3 -2
  119. package/src/interaction-contracts.ts +7 -7
  120. package/src/openclaw-workspace.ts +44 -18
  121. package/src/profile-loader.ts +650 -0
  122. package/src/profiles/banking.json +178 -0
  123. package/src/profiles/crossborder-ecom.json +253 -0
  124. package/src/profiles/insurance.json +157 -0
  125. package/src/profiles/knowledge/hs-structure.md +97 -0
  126. package/src/profiles/knowledge/incoterms-2020.md +188 -0
  127. package/src/profiles/knowledge/vat-principles.md +85 -0
  128. package/src/profiles/schema.json +201 -0
  129. package/src/profiles/securities.json +137 -0
  130. package/src/profiles/software-rd.json +264 -0
  131. package/src/profiles/trading-co.json +200 -0
  132. package/src/prompt-policy.ts +27 -13
  133. package/src/role-ids.ts +31 -0
  134. package/src/roles.ts +60 -14
  135. package/src/session-roles.ts +14 -0
  136. package/src/state.ts +236 -9
  137. package/src/task-executor.ts +7 -18
  138. package/src/teamauto/github-client.ts +21 -0
  139. package/src/teamauto/repo-sync.ts +246 -6
  140. package/src/teamauto/scanner.ts +47 -13
  141. package/src/teamauto/scheduler.ts +259 -16
  142. package/src/teamauto/store.ts +12 -0
  143. package/src/types.ts +133 -16
  144. package/src/ui/app.js +592 -24
  145. package/src/ui/index.html +44 -11
  146. package/src/ui/style.css +194 -0
  147. package/src/worker/prompt-injector.ts +48 -8
  148. package/src/worker/skill-installer.ts +3 -1
  149. package/src/worker/worker-service.ts +83 -3
@@ -0,0 +1,907 @@
1
+ import { randomBytes } from "node:crypto";
2
+ // Phase 2.3/2.5 (cross-review adopted suggestion): manual-proposal roles
3
+ // validate against the ACTIVE profile and default to its defaultRole instead
4
+ // of hardcoded software role literals.
5
+ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js";
6
+ import { createGithubClient } from "./github-client.js";
7
+ import { learnNorms, renderNormsBlock } from "./norms.js";
8
+ import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
9
+ import { nextFireMs } from "./schedule.js";
10
+ import { advanceCursors, sweepRepo } from "./scanner.js";
11
+ import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, } from "./store.js";
12
+ /**
13
+ * TeamAuto scheduler: per-repo cron sweeps -> TeamClaw tasks -> GitHub
14
+ * write-backs. Fully autonomous per the user's decisions (TEAMAUTO_DESIGN.md):
15
+ * comments/PRs/issues are posted directly; ambiguous work goes through the
16
+ * normal clarification blocking flow.
17
+ */
18
+ const MARKER_FOOTER = (role) => `\n---\n[teamclaw:${role}] autonomous via TeamClaw`;
19
+ function newId(prefix) {
20
+ return `${prefix}-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
21
+ }
22
+ export { nextFireMs, ScheduleParseError } from "./schedule.js";
23
+ /** Max HARD (non-transient) failures before a candidate is dead-lettered. */
24
+ export const TEAMAUTO_DEAD_LETTER_ATTEMPTS = 3;
25
+ /** Max TOTAL failures (transient included) before a candidate is dead-lettered. */
26
+ export const TEAMAUTO_DEAD_LETTER_TRANSIENT_ATTEMPTS = 6;
27
+ /**
28
+ * Failure signatures that are environmental, not the task's fault - the same
29
+ * candidate is likely to succeed on a later sweep. Observed live (92-task
30
+ * dump): upstream rate limiting ("AI service needs a short break"), shared
31
+ * workspace snapshot races ("Workspace filesystem changed"), worker gateway
32
+ * lifecycle races ("Gateway request entry is closed"). These get a wider
33
+ * retry allowance than hard failures so they do not dead-letter good work.
34
+ */
35
+ export const TRANSIENT_FAILURE_RE = /workspace filesystem changed|ai service needs a short break|gateway request entry is closed|rate.?limit|timed? ?out|econnreset|socket hang up|bad gateway|service unavailable/i;
36
+ /** The dedup marker for a candidate as embedded in task descriptions. */
37
+ export function idempotencyMarker(candidate) {
38
+ return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
39
+ }
40
+ /** Failed task attempts for a candidate (task history is the attempt log). */
41
+ export function failedAttemptCount(state, candidate) {
42
+ const marker = idempotencyMarker(candidate);
43
+ return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed").length;
44
+ }
45
+ /** Failed attempts whose error is NOT a known transient signature. */
46
+ export function hardAttemptCount(state, candidate) {
47
+ const marker = idempotencyMarker(candidate);
48
+ return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed" && !(t.error && TRANSIENT_FAILURE_RE.test(t.error))).length;
49
+ }
50
+ /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
51
+ export const SWEEP_RETRY_BASE_MINUTES = 30;
52
+ export const SWEEP_RETRY_MAX_MINUTES = 240;
53
+ export function sweepBackoffMinutes(failures) {
54
+ return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
55
+ }
56
+ /** Epoch ms when an auto-paused repo becomes due for its next retry attempt. */
57
+ export function sweepRetryDueAt(failures, lastErrorAt) {
58
+ return lastErrorAt + sweepBackoffMinutes(failures) * 60_000;
59
+ }
60
+ /**
61
+ * Issue #24: max write-back delivery attempts before the entry is marked
62
+ * terminally failed (failedAt) and never retried again.
63
+ */
64
+ export const TEAMAUTO_WRITEBACK_MAX_ATTEMPTS = 6;
65
+ /**
66
+ * Issue #24: write-back retry backoff - 1 minute after the 1st failure,
67
+ * doubling per attempt, capped at 2 hours. Over
68
+ * TEAMAUTO_WRITEBACK_MAX_ATTEMPTS attempts this spaces transient GitHub API
69
+ * failures (secondary rate limits, 5xx, token refresh races) across roughly
70
+ * an hour before giving up, instead of the pre-fix behavior (sticky error
71
+ * with no retry/no visibility, then a 20s hammer once the self-heal landed).
72
+ */
73
+ export const WRITEBACK_RETRY_BASE_MS = 60_000;
74
+ export const WRITEBACK_RETRY_MAX_MS = 2 * 60 * 60_000;
75
+ export function writebackBackoffMs(attempts) {
76
+ return Math.min(WRITEBACK_RETRY_BASE_MS * 2 ** Math.max(0, attempts - 1), WRITEBACK_RETRY_MAX_MS);
77
+ }
78
+ /** Epoch ms when a failed write-back becomes due for its next retry. */
79
+ export function writebackRetryDueAt(attempts, lastErrorAt) {
80
+ return lastErrorAt + writebackBackoffMs(attempts);
81
+ }
82
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
83
+ export function isAutoPause(reason) {
84
+ return !!reason && reason.startsWith("sweep failed:");
85
+ }
86
+ export function createTeamAutoScheduler(deps) {
87
+ const { logger, auth } = deps;
88
+ function recordActivity(store, entry) {
89
+ pushTeamAutoActivity(store, entry);
90
+ deps.onActivity?.(entry);
91
+ }
92
+ /**
93
+ * Issue #24: a failed write-back used to be a sticky `error` field whose
94
+ * only trace was one warn log line - the completed task's result never
95
+ * reached GitHub and nothing surfaced it. Centralized failure handling:
96
+ * persist the failure (attempts/backoff), expose it in the activity feed,
97
+ * and give up terminally (failedAt) once attempts are exhausted or the
98
+ * caller flags the failure undeliverable.
99
+ */
100
+ function markWritebackFailure(store, entry, message, options = {}) {
101
+ entry.error = message;
102
+ entry.attempts = (entry.attempts ?? 0) + 1;
103
+ entry.lastErrorAt = Date.now();
104
+ entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
105
+ const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
106
+ if (gaveUp && !entry.doneAt) {
107
+ entry.failedAt = Date.now();
108
+ recordActivity(store, {
109
+ at: Date.now(),
110
+ repoId: entry.repoId,
111
+ kind: "writeback",
112
+ text: `failed permanently after ${entry.attempts} attempt(s) (${entry.action} #${entry.targetId ?? "-"}, task ${entry.taskId}): ${message}`,
113
+ });
114
+ logger.warn(`TeamAuto: write-back ${entry.taskId} (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}) gave up after ${entry.attempts} attempts: ${message}`);
115
+ return;
116
+ }
117
+ recordActivity(store, {
118
+ at: Date.now(),
119
+ repoId: entry.repoId,
120
+ kind: "writeback",
121
+ 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}`,
122
+ });
123
+ logger.warn(`TeamAuto: writeback failed (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}): ${message}`);
124
+ }
125
+ /**
126
+ * Issue #24: write-back delivery stats surfaced through getStatus() so the
127
+ * repos endpoint, the teamclaw_teamauto_status tool, and the activity feed
128
+ * can see stuck/failed deliveries instead of only warn logs.
129
+ */
130
+ function summarizeWritebacks(store) {
131
+ const open = store.writebacks.filter((w) => !w.doneAt);
132
+ const failed = open.filter((w) => w.failedAt);
133
+ const errored = open.filter((w) => w.error && !w.failedAt);
134
+ const lastErrorEntry = open
135
+ .filter((w) => w.error)
136
+ .sort((a, b) => (b.lastErrorAt ?? 0) - (a.lastErrorAt ?? 0))[0];
137
+ return {
138
+ pending: open.length - failed.length - errored.length,
139
+ errored: errored.length,
140
+ failed: failed.length,
141
+ lastError: lastErrorEntry
142
+ ? {
143
+ taskId: lastErrorEntry.taskId,
144
+ repoId: lastErrorEntry.repoId,
145
+ action: lastErrorEntry.action,
146
+ targetId: lastErrorEntry.targetId,
147
+ attempts: lastErrorEntry.attempts ?? 0,
148
+ terminal: Boolean(lastErrorEntry.failedAt),
149
+ at: lastErrorEntry.lastErrorAt ?? null,
150
+ message: lastErrorEntry.error,
151
+ }
152
+ : null,
153
+ };
154
+ }
155
+ const client = createGithubClient(auth);
156
+ const sync = createRepoSync(auth, logger);
157
+ // #173 follow-up 5: squash-merge delivery oracle for worktree GC. After a
158
+ // squash merge + branch deletion the task commits are unreachable from
159
+ // origin/<default>, so the rev-list own-count never drains and the worktree
160
+ // is retained forever. Positive proof = a merged PR whose head tip is exactly
161
+ // the worktree's HEAD. Every failure path resolves false (fail toward keep).
162
+ const squashDeliveryOracle = async (repoId, taskId, headTip) => {
163
+ try {
164
+ const [owner, name] = repoId.split("/");
165
+ if (!owner || !name) {
166
+ return false;
167
+ }
168
+ return await client.prHeadDelivered(owner, name, sync.taskBranchName(taskId), headTip);
169
+ }
170
+ catch {
171
+ return false;
172
+ }
173
+ };
174
+ const timers = new Map();
175
+ const sweeping = new Set();
176
+ let running = false;
177
+ let store = null;
178
+ let writebackTimer = null;
179
+ async function ensureStore() {
180
+ if (!store) {
181
+ store = await loadTeamAutoStore();
182
+ }
183
+ return store;
184
+ }
185
+ // ---------- public repo management ----------
186
+ async function addRepo(repoId, options = {}) {
187
+ const s = await ensureStore();
188
+ const normalized = repoId.trim().replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, "");
189
+ if (!/^[\w.-]+\/[\w.-]+$/.test(normalized)) {
190
+ throw new Error(`invalid repo id: ${repoId} (expected owner/repo)`);
191
+ }
192
+ if (s.repos.some((r) => r.id === normalized)) {
193
+ throw new Error(`${normalized} is already bound`);
194
+ }
195
+ const [owner, name] = normalized.split("/");
196
+ const info = await client.getRepoInfo(owner, name);
197
+ if (!info.permissions.pull) {
198
+ throw new Error(`no read access to ${normalized}`);
199
+ }
200
+ const schedule = options.schedule?.trim() || "*/30 * * * *";
201
+ nextFireMs(schedule); // validates: throws ScheduleParseError for unsupported expressions
202
+ const repo = {
203
+ id: normalized,
204
+ enabled: true,
205
+ schedule,
206
+ addedAt: Date.now(),
207
+ lastSweepAt: 0,
208
+ lastSweepSummary: null,
209
+ pausedReason: null,
210
+ dryRunDone: !s.budget.firstSweepDryRun,
211
+ policy: defaultPolicy(),
212
+ cursors: defaultCursors(),
213
+ norms: null,
214
+ };
215
+ if (options.keywordInclude?.length) {
216
+ repo.policy.keywordFilter.include = options.keywordInclude;
217
+ }
218
+ if (options.keywordExclude?.length) {
219
+ repo.policy.keywordFilter.exclude = options.keywordExclude;
220
+ }
221
+ // Provision (clone + norms learning) runs in the background so bind
222
+ // returns immediately; sweeps stay gated until provision completes.
223
+ repo.provision = { status: "provisioning", message: "cloning repo", startedAt: Date.now(), updatedAt: Date.now() };
224
+ s.repos.push(repo);
225
+ recordActivity(s, { at: Date.now(), repoId: normalized, kind: "bind", text: `bound (schedule ${repo.schedule})` });
226
+ await saveTeamAutoStore(s);
227
+ scheduleRepo(repo);
228
+ void provisionRepoInBackground(normalized, info.cloneUrl, info.defaultBranch);
229
+ logger.info(`TeamAuto: bound ${normalized} (schedule ${repo.schedule}${repo.dryRunDone ? "" : ", first sweep dry-run"}; provisioning in background)`);
230
+ return repo;
231
+ }
232
+ async function provisionRepoInBackground(repoId, cloneUrl, defaultBranch) {
233
+ try {
234
+ const s0 = await ensureStore();
235
+ const repoRef = s0.repos.find((r) => r.id === repoId);
236
+ if (!repoRef) {
237
+ return;
238
+ }
239
+ await updateRepoProvision(repoId, { status: "provisioning", message: "learning repo norms" });
240
+ const norms = await learnNorms(repoRef, client, sync, cloneUrl, defaultBranch);
241
+ await updateRepoProvision(repoId, { status: "ready", message: "ready", norms });
242
+ const sReady = await ensureStore();
243
+ recordActivity(sReady, { at: Date.now(), repoId, kind: "provision", text: "ready (clone + norms done)" });
244
+ logger.info(`TeamAuto: provisioned ${repoId} (clone + norms done)`);
245
+ }
246
+ catch (err) {
247
+ const message = err instanceof Error ? err.message : String(err);
248
+ logger.warn(`TeamAuto: provisioning failed for ${repoId}: ${message}`);
249
+ await updateRepoProvision(repoId, { status: "failed", message });
250
+ const sFailed = await ensureStore();
251
+ recordActivity(sFailed, { at: Date.now(), repoId, kind: "provision", text: `failed: ${message}` });
252
+ }
253
+ }
254
+ async function updateRepoProvision(repoId, patch) {
255
+ const s = await ensureStore();
256
+ const repo = s.repos.find((r) => r.id === repoId);
257
+ if (!repo) {
258
+ return;
259
+ }
260
+ repo.provision = { status: patch.status ?? repo.provision?.status ?? "provisioning", message: patch.message ?? repo.provision?.message ?? "", startedAt: repo.provision?.startedAt ?? Date.now(), updatedAt: Date.now() };
261
+ if (patch.norms) {
262
+ repo.norms = patch.norms;
263
+ }
264
+ await saveTeamAutoStore(s);
265
+ }
266
+ async function removeRepo(repoId) {
267
+ const s = await ensureStore();
268
+ s.repos = s.repos.filter((r) => r.id !== repoId);
269
+ await saveTeamAutoStore(s);
270
+ const timer = timers.get(repoId);
271
+ if (timer) {
272
+ clearTimeout(timer);
273
+ timers.delete(repoId);
274
+ }
275
+ }
276
+ async function setRepoEnabled(repoId, enabled) {
277
+ const s = await ensureStore();
278
+ const repo = s.repos.find((r) => r.id === repoId);
279
+ if (!repo) {
280
+ throw new Error(`${repoId} not bound`);
281
+ }
282
+ repo.enabled = enabled;
283
+ repo.pausedReason = enabled ? null : (repo.pausedReason ?? "disabled by user");
284
+ await saveTeamAutoStore(s);
285
+ if (enabled) {
286
+ scheduleRepo(repo);
287
+ }
288
+ }
289
+ async function updateRepo(repoId, patch = {}) {
290
+ const s = await ensureStore();
291
+ const repo = s.repos.find((r) => r.id === repoId);
292
+ if (!repo) {
293
+ throw new Error(`${repoId} not bound`);
294
+ }
295
+ if (patch.schedule?.trim()) {
296
+ const schedule = patch.schedule.trim();
297
+ nextFireMs(schedule); // validates before persisting
298
+ repo.schedule = schedule;
299
+ }
300
+ if (typeof patch.maxTasksPerSweep === "number" && patch.maxTasksPerSweep > 0) {
301
+ repo.policy.maxTasksPerSweep = Math.min(20, Math.floor(patch.maxTasksPerSweep));
302
+ }
303
+ if (patch.fullReview) {
304
+ repo.policy.actions.fullReview = patch.fullReview;
305
+ }
306
+ if (typeof patch.takeOwnership === "boolean") {
307
+ repo.policy.actions.takeOwnership = patch.takeOwnership;
308
+ }
309
+ await saveTeamAutoStore(s);
310
+ scheduleRepo(repo);
311
+ return repo;
312
+ }
313
+ async function runSweepNow(repoId, force = true) {
314
+ const s = await ensureStore();
315
+ const repo = s.repos.find((r) => r.id === repoId);
316
+ if (!repo) {
317
+ throw new Error(`${repoId} not bound`);
318
+ }
319
+ return runSweep(repo, force);
320
+ }
321
+ // ---------- sweep engine ----------
322
+ async function runSweep(repo, force) {
323
+ // Sweeps stay gated until bind-time provisioning (clone + norms) settles.
324
+ if (repo.provision?.status === "provisioning") {
325
+ const summary = `skipped: still provisioning (${repo.provision.message})`;
326
+ logger.debug?.(`TeamAuto: ${repo.id} ${summary}`);
327
+ return summary;
328
+ }
329
+ if (repo.provision?.status === "failed") {
330
+ const summary = `skipped: provisioning failed (${repo.provision.message})`;
331
+ logger.warn(`TeamAuto: ${repo.id} ${summary}`);
332
+ return summary;
333
+ }
334
+ const s = await ensureStore();
335
+ if (sweeping.has(repo.id)) {
336
+ return "sweep already in progress";
337
+ }
338
+ sweeping.add(repo.id);
339
+ try {
340
+ const { candidates, issues, pulls } = await sweepRepo(repo, client);
341
+ const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
342
+ if (dryRun) {
343
+ // One observing pass, then act. Flip unconditionally - flipping only
344
+ // when candidates existed deadlocked empty first sweeps in dry-run
345
+ // mode forever (dry-run never advanced cursors -> still "first sweep"
346
+ // -> still zero candidates -> dryRunDone never set).
347
+ repo.dryRunDone = true;
348
+ }
349
+ if (!dryRun) {
350
+ // Advance only for acting sweeps: a dry-run must leave the cursors
351
+ // untouched so the reported actions are actually performed next time
352
+ // instead of being marked as already-seen.
353
+ advanceCursors(repo, issues, pulls);
354
+ }
355
+ // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
356
+ // pull candidates, so a busy repo would otherwise starve them forever
357
+ // (cap filled every sweep, lastFullReviewAt never advancing). They are
358
+ // at most one cycle (3 sections) per interval, so this stays bounded.
359
+ const fullReviews = candidates.filter((c) => c.kind === "fullReview");
360
+ const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
361
+ const capped = [...fullReviews, ...regular];
362
+ let created = 0;
363
+ const summary = [`found ${candidates.length} candidate(s)`];
364
+ if (capped.length && dryRun) {
365
+ summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
366
+ repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
367
+ }
368
+ else if (capped.length) {
369
+ if (!consumeDailyBudget(s, capped.length)) {
370
+ summary.push("skipped: daily task budget exhausted");
371
+ }
372
+ else {
373
+ for (const candidate of capped) {
374
+ const taskId = enqueueCandidate(repo, candidate);
375
+ if (taskId === "dead-lettered") {
376
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
377
+ }
378
+ else if (taskId) {
379
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
380
+ const action = candidate.kind === "prReview"
381
+ ? "prComment"
382
+ : candidate.kind === "fullReview"
383
+ ? "createIssue"
384
+ : "issueComment";
385
+ registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
386
+ created++;
387
+ }
388
+ }
389
+ repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
390
+ if (capped.some((c) => c.kind === "fullReview")) {
391
+ repo.cursors.lastFullReviewAt = Date.now();
392
+ }
393
+ }
394
+ }
395
+ else {
396
+ repo.lastSweepSummary = "no new work";
397
+ }
398
+ repo.lastSweepAt = Date.now();
399
+ if (isAutoPause(repo.pausedReason)) {
400
+ repo.pausedReason = null;
401
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
402
+ }
403
+ repo.sweepFailures = 0;
404
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
405
+ await saveTeamAutoStore(s);
406
+ if (created > 0) {
407
+ await deps.onTasksCreated().catch((err) => {
408
+ logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
409
+ });
410
+ }
411
+ logger.info(`TeamAuto: sweep ${repo.id} -> ${repo.lastSweepSummary}`);
412
+ return repo.lastSweepSummary ?? "sweep complete";
413
+ }
414
+ catch (err) {
415
+ const message = err instanceof Error ? err.message : String(err);
416
+ // Transient failures (network blips, restart-interrupted sweeps) used to
417
+ // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
418
+ // failed". Auto-pauses are cooldowns now: the timer retries after the
419
+ // backoff below, and a success clears the state in the block above.
420
+ repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
421
+ repo.lastSweepErrorAt = Date.now();
422
+ repo.pausedReason = `sweep failed: ${message}`;
423
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
424
+ await saveTeamAutoStore(s).catch(() => { });
425
+ logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
426
+ return `error: ${message}`;
427
+ }
428
+ finally {
429
+ sweeping.delete(repo.id);
430
+ }
431
+ }
432
+ function enqueueCandidate(repo, candidate) {
433
+ let createdId;
434
+ let deadLettered = false;
435
+ deps.updateTeamState((state) => {
436
+ // Idempotency: an active task for the same object AND kind wins. The
437
+ // key rides in the description (TaskInfo has no dedicated field) and
438
+ // must be a distinct marked line - titles contain human text that never
439
+ // matches the raw key (that was the pre-fix bug). Kind-scoping matters:
440
+ // object-level keys starved takeOwnership (review always enqueued first).
441
+ const dedupMarker = idempotencyMarker(candidate);
442
+ const duplicate = Object.values(state.tasks).find((t) => t.description.includes(dedupMarker) && t.status !== "completed" && t.status !== "failed");
443
+ if (duplicate) {
444
+ return;
445
+ }
446
+ // Dead-letter: task history doubles as the attempt log. The dedup above
447
+ // only blocks ACTIVE tasks, so a failed candidate would be re-enqueued
448
+ // every sweep forever (observed: issue #12 re-candidated 4 sweeps in a
449
+ // row, burning daily budget on churn). Cap the retries instead - hard
450
+ // failures fast (3), environmental/transient failures get a wider
451
+ // allowance (6 total) so rate limits or workspace races do not kill
452
+ // work that would succeed on a quieter sweep.
453
+ if (hardAttemptCount(state, candidate) >= TEAMAUTO_DEAD_LETTER_ATTEMPTS
454
+ || failedAttemptCount(state, candidate) >= TEAMAUTO_DEAD_LETTER_TRANSIENT_ATTEMPTS) {
455
+ deadLettered = true;
456
+ return;
457
+ }
458
+ const task = {
459
+ id: newId("teamauto"),
460
+ title: `[${candidate.kind}] ${candidate.title}`,
461
+ description: [
462
+ `TeamAuto autonomous work for ${candidate.repoId}.`,
463
+ dedupMarker,
464
+ `Local checkout: projects/${teamAutoProjectDir(candidate.repoId)} in the team workspace.`,
465
+ ...(candidate.writeMode === "read-only" || (!candidate.writeMode && candidate.kind !== "takeOwnership")
466
+ ? [
467
+ "READ-ONLY TASK (collaboration contract): You must NOT modify, create, or delete any files - your reply IS the deliverable.",
468
+ "Base your review on the committed HEAD state (use git show/git log); uncommitted working-tree changes belong to a concurrent write task and must be ignored.",
469
+ ]
470
+ : [
471
+ "WRITE TASK (collaboration contract): you are executing in a dedicated git worktree; deliver your changes via commits there - the controller turns your branch into a PR.",
472
+ ]),
473
+ renderNormsBlock(repo.norms, repo.id),
474
+ "---",
475
+ candidate.context,
476
+ "---",
477
+ `When finished, your reply becomes the GitHub ${candidate.kind === "prReview" || candidate.kind === "issueReview" ? "review comment" : "deliverable"}. ` +
478
+ `If the material is ambiguous or blocked on a human decision, request clarification instead of guessing.`,
479
+ MARKER_FOOTER(candidate.role),
480
+ ].join("\n"),
481
+ status: "pending",
482
+ priority: candidate.kind === "takeOwnership" ? "high" : "medium",
483
+ // Candidate.role is RoleId since Phase 2.3 debt item 4 (scanner role
484
+ // set derives from the active team profile) - no cast needed.
485
+ assignedRole: candidate.role,
486
+ writeMode: candidate.writeMode === "write" ? "write" : "read-only",
487
+ createdBy: "teamauto",
488
+ projectDir: teamAutoProjectDir(candidate.repoId),
489
+ createdAt: Date.now(),
490
+ updatedAt: Date.now(),
491
+ };
492
+ state.tasks[task.id] = task;
493
+ createdId = task.id;
494
+ });
495
+ return deadLettered ? "dead-lettered" : createdId;
496
+ }
497
+ /**
498
+ * Agent-facing manual proposal: inject a candidate directly (bypassing the
499
+ * GitHub-object sweep) while reusing the full pipeline - idempotency dedup,
500
+ * dead-letter caps, budget accounting, norms blocks, worktree checkout.
501
+ * No writeback is registered (there is no GitHub object to write back to);
502
+ * the result stays in the task system, visible via teamclaw_list_tasks.
503
+ */
504
+ async function proposeManual(repoId, input) {
505
+ const s = await ensureStore();
506
+ const repo = s.repos.find((r) => r.id === repoId);
507
+ if (!repo) {
508
+ throw new Error(`${repoId} not bound`);
509
+ }
510
+ const kind = input.kind === "takeOwnership" || input.kind === "issueReview" || input.kind === "prReview" || input.kind === "fullReview" ? input.kind : "issueReview";
511
+ // Cross-review adopted suggestion: the caller-supplied role is untrusted
512
+ // input - validate it against the ACTIVE profile (drops unknown and
513
+ // not-in-this-profile ids) and fall back to the profile defaultRole
514
+ // instead of the old hardcoded "developer"/"architect" software literals.
515
+ const role = validateActiveRoleId(input.role) ?? getActiveDefaultRole();
516
+ const candidate = {
517
+ repoId,
518
+ key: `${repoId}#manual-${Date.now()}`,
519
+ kind,
520
+ number: 0,
521
+ role,
522
+ writeMode: input.writeMode ?? (kind === "takeOwnership" ? "write" : "read-only"),
523
+ title: input.title.slice(0, 120),
524
+ reason: "manual proposal from agent tool",
525
+ context: input.context,
526
+ };
527
+ const taskId = enqueueCandidate(repo, candidate);
528
+ if (taskId === "dead-lettered") {
529
+ throw new Error(`proposal dead-lettered (${kind} exceeded failure caps for this repo)`);
530
+ }
531
+ if (taskId) {
532
+ recordActivity(s, { at: Date.now(), repoId, kind: "task", text: `manual ${kind}: ${candidate.title}` });
533
+ await saveTeamAutoStore(s);
534
+ return taskId;
535
+ }
536
+ return "duplicate-active-skipped";
537
+ }
538
+ // ---------- write-back reconciler ----------
539
+ async function reconcileWritebacks() {
540
+ const s = await ensureStore();
541
+ const state0 = deps.getTeamState();
542
+ // Dead letters: entries whose task is gone or failed without a result can
543
+ // never deliver - drop them instead of accumulating forever.
544
+ if (state0) {
545
+ const before = s.writebacks.length;
546
+ const deadOnes = [];
547
+ s.writebacks = s.writebacks.filter((w) => {
548
+ if (w.doneAt) {
549
+ return true;
550
+ }
551
+ const t = state0.tasks[w.taskId];
552
+ const dead = !t || (t.status === "failed" && !t.result);
553
+ if (dead) {
554
+ logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
555
+ deadOnes.push(w);
556
+ }
557
+ return !dead;
558
+ });
559
+ if (s.writebacks.length !== before) {
560
+ await saveTeamAutoStore(s);
561
+ }
562
+ // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
563
+ // failed-without-result tasks BEFORE the pending loop below, so the
564
+ // terminal worktree cleanup there never ran for them - the single
565
+ // largest leak source. Safety-clean here too (same contract). The
566
+ // filter callback cannot await, hence the post-filter pass.
567
+ for (const w of deadOnes) {
568
+ const t = state0.tasks[w.taskId];
569
+ if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
570
+ const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
571
+ if (r.removed) {
572
+ // #173 follow-up 4: positive removal line - without it a successful
573
+ // terminal cleanup is invisible in logs (only kept/failed logged).
574
+ logger.warn(`TeamAuto: terminal task ${w.taskId} worktree removed (${r.reason})`);
575
+ }
576
+ else if (!r.reason.includes("already gone")) {
577
+ logger.warn(`TeamAuto: terminal task ${w.taskId} worktree kept: ${r.reason}`);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ // Self-heal: an entry whose task later COMPLETED with a result (e.g. the
583
+ // completion gate rejected an early submission, then a retry succeeded)
584
+ // must be retried - a sticky error here would silently drop delivery.
585
+ // Issue #24: the retry now respects the per-entry backoff (nextAttemptAt)
586
+ // so a failing write-back no longer hammers GitHub on every 20s pass;
587
+ // legacy entries without a nextAttemptAt (pre-#24 stores) retry once
588
+ // immediately and then enter the normal backoff ladder. Terminally
589
+ // failed entries (failedAt) are never retried again.
590
+ for (const w of s.writebacks) {
591
+ if (w.error && !w.doneAt && !w.failedAt && state0) {
592
+ const t = state0.tasks[w.taskId];
593
+ if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
594
+ w.error = null;
595
+ }
596
+ }
597
+ }
598
+ const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
599
+ if (!pending.length) {
600
+ return;
601
+ }
602
+ const state = deps.getTeamState();
603
+ if (!state) {
604
+ return;
605
+ }
606
+ for (const entry of pending) {
607
+ const task = state.tasks[entry.taskId];
608
+ if (!task || (task.status !== "completed" && task.status !== "failed")) {
609
+ continue;
610
+ }
611
+ const repo = s.repos.find((r) => r.id === entry.repoId);
612
+ const [owner, name] = entry.repoId.split("/");
613
+ try {
614
+ if (task.status === "failed" || !task.result) {
615
+ // Undeliverable in every future pass: a failed task never gains a
616
+ // result, and "completed without result" cannot recover either.
617
+ // Mark terminal (issue #24) so the entry is counted, surfaced via
618
+ // activity/stats, and never pointlessly retried. Failed-without-
619
+ // result entries are additionally dropped by the dead-letter pass
620
+ // on the next reconcile.
621
+ markWritebackFailure(s, entry, task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result", { terminal: true });
622
+ // Terminal write task: its dispatch-time worktree has no delivery
623
+ // path left - remove it when the worker never produced deliverable
624
+ // commits (safety-checked, undelivered work is retained + logged).
625
+ if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
626
+ const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
627
+ if (r.removed) {
628
+ // #173 follow-up 4: positive removal line - symmetric with the
629
+ // boot-GC path which logs both directions.
630
+ logger.warn(`TeamAuto: terminal task ${task.id} worktree removed (${r.reason})`);
631
+ }
632
+ else if (!r.reason.includes("already gone")) {
633
+ logger.warn(`TeamAuto: terminal task ${task.id} worktree kept: ${r.reason}`);
634
+ }
635
+ }
636
+ }
637
+ else {
638
+ const role = (task.assignedRole ?? "qa");
639
+ let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
640
+ let writebackDone = false;
641
+ // WRITE TASKS (collaboration contract): commit the task worktree,
642
+ // push its branch, open a PR, and attach the link to the reply.
643
+ const repoId = entry.repoId;
644
+ const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
645
+ if (isTeamAutoWrite) {
646
+ try {
647
+ const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
648
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
649
+ const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
650
+ const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
651
+ // Workers often commit themselves inside the worktree - deliver
652
+ // whenever the branch carries commits beyond base, not only when
653
+ // commitAll just added new ones.
654
+ const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
655
+ if (deliverable) {
656
+ await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
657
+ const pr = await client.createPullRequest(repoId.split("/")[0], repoId.split("/")[1], branch, info.defaultBranch, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 120), `${task.result.trim()}\n${MARKER_FOOTER(role)}`);
658
+ entry.prUrl = pr.url;
659
+ body = `${body}\n\nDelivered as PR: ${pr.url}`;
660
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
661
+ }
662
+ await sync.removeTaskWorktree(repoId, task.id);
663
+ }
664
+ catch (prErr) {
665
+ markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
666
+ }
667
+ }
668
+ if (entry.action === "issueComment" && entry.targetId) {
669
+ await client.postIssueComment(owner, name, entry.targetId, body);
670
+ entry.doneAt = Date.now();
671
+ writebackDone = true;
672
+ // Our own comment bumps the issue's updatedAt, which the scanner
673
+ // treats as new activity - advance the seen cursor so we do not
674
+ // re-trigger a review of an object we just replied to. External
675
+ // edits (updatedAt > now) still re-arm the candidate.
676
+ const issueRepo = s.repos.find((r) => r.id === entry.repoId);
677
+ if (issueRepo) {
678
+ issueRepo.cursors.seen[`${entry.repoId}#issue-${entry.targetId}`] = Date.now();
679
+ }
680
+ }
681
+ else if (entry.action === "prComment" && entry.targetId) {
682
+ await client.postPullReviewComment(owner, name, entry.targetId, body);
683
+ entry.doneAt = Date.now();
684
+ writebackDone = true;
685
+ const prRepo = s.repos.find((r) => r.id === entry.repoId);
686
+ if (prRepo) {
687
+ prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
688
+ }
689
+ }
690
+ else if (entry.action === "createIssue") {
691
+ // Joint full review: same-cycle sections land in ONE umbrella issue
692
+ // (first completed section creates it, the rest post as comments).
693
+ const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
694
+ if (entry.cycleKey) {
695
+ const peers = s.writebacks.filter((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
696
+ const umbrella = peers[0];
697
+ if (umbrella && umbrella.targetId != null) {
698
+ await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
699
+ entry.targetId = umbrella.targetId;
700
+ entry.doneAt = Date.now();
701
+ writebackDone = true;
702
+ }
703
+ else if (entry.targetId == null) {
704
+ const number = await client.createIssue(owner, name, `[teamclaw:fullreview] Joint full review - ${entry.repoId}`, `Joint multi-role full review (cycle ${entry.cycleKey}). Each role appends its section as a comment below.\n\n${sectionBody}`, ["teamclaw", "teamclaw:fullreview"]);
705
+ entry.targetId = number;
706
+ entry.doneAt = Date.now();
707
+ writebackDone = true;
708
+ }
709
+ }
710
+ else {
711
+ const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
712
+ entry.targetId = number;
713
+ entry.doneAt = Date.now();
714
+ writebackDone = true;
715
+ }
716
+ }
717
+ else {
718
+ markWritebackFailure(s, entry, `unsupported action ${entry.action}`, { terminal: true });
719
+ }
720
+ if (writebackDone) {
721
+ // Delivery succeeded: clear any transient failure state so a
722
+ // partially-failed entry (e.g. PR opened on an earlier retry)
723
+ // does not linger in the errored/failed stats (issue #24).
724
+ entry.error = null;
725
+ entry.failedAt = null;
726
+ 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)` : ""})` });
727
+ }
728
+ }
729
+ }
730
+ catch (err) {
731
+ markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
732
+ }
733
+ void repo;
734
+ }
735
+ s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
736
+ await saveTeamAutoStore(s);
737
+ }
738
+ // Register the write-back intent when a task lands in the task store.
739
+ function registerWriteback(taskId, action, repoId, targetId, cycleKey) {
740
+ void ensureStore().then((s) => {
741
+ if (s.writebacks.some((w) => w.taskId === taskId)) {
742
+ return;
743
+ }
744
+ s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
745
+ void saveTeamAutoStore(s);
746
+ }).catch(() => { });
747
+ }
748
+ // ---------- scheduling loop ----------
749
+ function scheduleRepo(repo) {
750
+ const previous = timers.get(repo.id);
751
+ if (previous) {
752
+ clearTimeout(previous);
753
+ timers.delete(repo.id);
754
+ }
755
+ if (!repo.enabled) {
756
+ return;
757
+ }
758
+ let delay;
759
+ try {
760
+ delay = nextFireMs(repo.schedule);
761
+ }
762
+ catch (err) {
763
+ logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
764
+ return;
765
+ }
766
+ const timer = setTimeout(() => {
767
+ void (async () => {
768
+ try {
769
+ const s = await ensureStore();
770
+ const fresh = s.repos.find((r) => r.id === repo.id);
771
+ const retryDue = fresh
772
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
773
+ : false;
774
+ if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
775
+ await runSweep(fresh, false);
776
+ }
777
+ if (fresh?.enabled) {
778
+ scheduleRepo(fresh);
779
+ }
780
+ }
781
+ catch (err) {
782
+ // The timer chain must survive any single tick failure. Before this
783
+ // guard, a rejected ensureStore() (corrupt store file, IO error)
784
+ // unhandled-rejected through `void`, scheduleRepo(fresh) never ran,
785
+ // and the repo's scheduling chain died silently until a gateway
786
+ // restart. Re-arm from the last known config; updateRepo re-arms on
787
+ // config change anyway, so a stale schedule here is bounded.
788
+ logger.warn(`TeamAuto: sweep tick failed for ${repo.id}, re-arming timer: ${err instanceof Error ? err.message : String(err)}`);
789
+ try {
790
+ scheduleRepo(repo);
791
+ }
792
+ catch {
793
+ // scheduleRepo only throws on programmer error; a dead chain here
794
+ // is still recoverable by restart (start() rebuilds all timers).
795
+ }
796
+ }
797
+ })();
798
+ }, delay);
799
+ timer.unref?.();
800
+ timers.set(repo.id, timer);
801
+ }
802
+ async function start() {
803
+ if (running) {
804
+ return;
805
+ }
806
+ running = true;
807
+ const s = await ensureStore();
808
+ for (const repo of s.repos) {
809
+ scheduleRepo(repo);
810
+ }
811
+ if (s.repos.length) {
812
+ logger.info(`TeamAuto: scheduler started for ${s.repos.length} repo(s)`);
813
+ }
814
+ writebackTimer = setInterval(() => {
815
+ void reconcileWritebacks();
816
+ }, 20_000);
817
+ writebackTimer.unref?.();
818
+ // Boot reconciliation: heal leftover task worktrees whose task is
819
+ // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
820
+ // on its own. Safety-checked: undelivered work is kept and logged.
821
+ void (async () => {
822
+ try {
823
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
824
+ // predicate below classifies EVERY task as terminal - boot GC must
825
+ // not run blind over an unloaded team state (fails toward skip).
826
+ if (!deps.getTeamState()) {
827
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
828
+ return;
829
+ }
830
+ let removed = 0;
831
+ let retained = 0;
832
+ let stale = 0;
833
+ const retainedDetails = [];
834
+ for (const repo of s.repos) {
835
+ if (!repo.enabled)
836
+ continue;
837
+ const isTerminal = (taskId) => {
838
+ const t = deps.getTeamState()?.tasks[taskId];
839
+ if (t && t.status !== "completed" && t.status !== "failed")
840
+ return false;
841
+ // Review F1: a terminal task with a pending write-back (push
842
+ // ok / PR failed, 20s-retry window) still needs its worktree -
843
+ // the retry delivers the PR from the surviving branch. Do not
844
+ // GC until the write-back settles (doneAt or dropped). Issue
845
+ // #24: terminally failed write-backs (failedAt) count as settled
846
+ // too - safeRemoveTaskWorktree still retains unpushed work.
847
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
848
+ };
849
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
850
+ removed += r.removed.length;
851
+ retained += r.retained.length;
852
+ stale += r.stale;
853
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
854
+ }
855
+ if (removed || retained || stale) {
856
+ // #173 follow-up 4: per-task retain reasons recorded as activity
857
+ // (PR #167 promised "outcome logged + recorded as activity"); the
858
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
859
+ const detail = retainedDetails.length
860
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
861
+ : "";
862
+ const stalePart = stale ? `, stale ${stale}` : "";
863
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
864
+ await saveTeamAutoStore(s);
865
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
866
+ }
867
+ }
868
+ catch (err) {
869
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
870
+ }
871
+ })();
872
+ }
873
+ async function stop() {
874
+ running = false;
875
+ for (const timer of timers.values()) {
876
+ clearTimeout(timer);
877
+ }
878
+ timers.clear();
879
+ if (writebackTimer) {
880
+ clearInterval(writebackTimer);
881
+ writebackTimer = null;
882
+ }
883
+ }
884
+ async function getStatus() {
885
+ const s = await ensureStore();
886
+ // Issue #24: failed/stuck write-back deliveries are part of the status
887
+ // payload (repos endpoint + teamclaw_teamauto_status tool) instead of
888
+ // being invisible outside warn logs.
889
+ return { repos: s.repos, budget: s.budget, activity: s.activity ?? [], writebacks: summarizeWritebacks(s) };
890
+ }
891
+ async function getActivity() {
892
+ const s = await ensureStore();
893
+ return (s.activity ?? []).slice().reverse();
894
+ }
895
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
896
+ /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
897
+ async function ensureWriteWorktree(repoId, taskId) {
898
+ const wtAbs = await sync.ensureTaskWorktree(repoId, taskId);
899
+ void wtAbs;
900
+ // Rel dir INCLUDING the teamauto/ level (basename dropped it and pointed
901
+ // workers outside the git worktree).
902
+ return sync.taskWorktreeRelDir(repoId, taskId);
903
+ }
904
+ async function removeWriteWorktree(repoId, taskId) {
905
+ await sync.removeTaskWorktree(repoId, taskId);
906
+ }
907
+ }