@teamclaws/teamclaw 2026.4.3-2 → 2026.5.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.
@@ -0,0 +1,585 @@
1
+ import { randomBytes } from "node:crypto";
2
+
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";
6
+ import { createGithubClient } from "./github-client.js";
7
+ import { learnNorms, renderNormsBlock } from "./norms.js";
8
+ import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
9
+ import { advanceCursors, sweepRepo, type Candidate } from "./scanner.js";
10
+ import {
11
+ consumeDailyBudget,
12
+ defaultCursors,
13
+ defaultPolicy,
14
+ loadTeamAutoStore,
15
+ pushTeamAutoActivity,
16
+ saveTeamAutoStore,
17
+ type TeamAutoRepo,
18
+ type TeamAutoRepoNorms,
19
+ type TeamAutoRepoProvision,
20
+ type TeamAutoStore,
21
+ } from "./store.js";
22
+
23
+ /**
24
+ * TeamAuto scheduler: per-repo cron sweeps -> TeamClaw tasks -> GitHub
25
+ * write-backs. Fully autonomous per the user's decisions (TEAMAUTO_DESIGN.md):
26
+ * comments/PRs/issues are posted directly; ambiguous work goes through the
27
+ * normal clarification blocking flow.
28
+ */
29
+
30
+ const MARKER_FOOTER = (role: string) => `\n---\n[teamclaw:${role}] autonomous via TeamClaw`;
31
+
32
+ function newId(prefix: string): string {
33
+ return `${prefix}-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`;
34
+ }
35
+
36
+ /** Minimal cron: supports minute-step schedules like "star-slash-n" (every n minutes), "@hourly", "@daily", plain-number fallback to minutes. */
37
+ export function nextFireMs(schedule: string): number {
38
+ const trimmed = schedule.trim();
39
+ if (trimmed === "@hourly") {
40
+ return 3600_000;
41
+ }
42
+ if (trimmed === "@daily") {
43
+ return 24 * 3600_000;
44
+ }
45
+ const match = trimmed.match(/^\*\/(\d+)\s+\*\s+\*\s+\*\s+\*$/);
46
+ if (match) {
47
+ return Math.max(1, Number(match[1])) * 60_000;
48
+ }
49
+ const digits = trimmed.match(/\d+/);
50
+ return digits ? Math.max(1, Number(digits[0])) * 60_000 : 30 * 60_000;
51
+ }
52
+ export type TeamAutoSchedulerDeps = {
53
+ logger: PluginLogger;
54
+ auth: GithubAuthManager;
55
+ getTeamState: () => TeamState | null;
56
+ updateTeamState: (updater: (state: TeamState) => void) => TeamState;
57
+ onTasksCreated: () => Promise<void>;
58
+ };
59
+
60
+ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
61
+ const { logger, auth } = deps;
62
+ const client = createGithubClient(auth);
63
+ const sync = createRepoSync(auth, logger);
64
+ const timers = new Map<string, NodeJS.Timeout>();
65
+ const sweeping = new Set<string>();
66
+ let running = false;
67
+ let store: TeamAutoStore | null = null;
68
+ let writebackTimer: NodeJS.Timeout | null = null;
69
+
70
+ async function ensureStore(): Promise<TeamAutoStore> {
71
+ if (!store) {
72
+ store = await loadTeamAutoStore();
73
+ }
74
+ return store;
75
+ }
76
+
77
+ // ---------- public repo management ----------
78
+
79
+ async function addRepo(repoId: string, options: { schedule?: string; keywordInclude?: string[]; keywordExclude?: string[] } = {}): Promise<TeamAutoRepo> {
80
+ const s = await ensureStore();
81
+ const normalized = repoId.trim().replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, "");
82
+ if (!/^[\w.-]+\/[\w.-]+$/.test(normalized)) {
83
+ throw new Error(`invalid repo id: ${repoId} (expected owner/repo)`);
84
+ }
85
+ if (s.repos.some((r) => r.id === normalized)) {
86
+ throw new Error(`${normalized} is already bound`);
87
+ }
88
+ const [owner, name] = normalized.split("/");
89
+ const info = await client.getRepoInfo(owner, name);
90
+ if (!info.permissions.pull) {
91
+ throw new Error(`no read access to ${normalized}`);
92
+ }
93
+ const repo: TeamAutoRepo = {
94
+ id: normalized,
95
+ enabled: true,
96
+ schedule: options.schedule?.trim() || "*/30 * * * *",
97
+ addedAt: Date.now(),
98
+ lastSweepAt: 0,
99
+ lastSweepSummary: null,
100
+ pausedReason: null,
101
+ dryRunDone: !s.budget.firstSweepDryRun,
102
+ policy: defaultPolicy(),
103
+ cursors: defaultCursors(),
104
+ norms: null,
105
+ };
106
+ if (options.keywordInclude?.length) {
107
+ repo.policy.keywordFilter.include = options.keywordInclude;
108
+ }
109
+ if (options.keywordExclude?.length) {
110
+ repo.policy.keywordFilter.exclude = options.keywordExclude;
111
+ }
112
+ // Provision (clone + norms learning) runs in the background so bind
113
+ // returns immediately; sweeps stay gated until provision completes.
114
+ repo.provision = { status: "provisioning", message: "cloning repo", startedAt: Date.now(), updatedAt: Date.now() };
115
+ s.repos.push(repo);
116
+ pushTeamAutoActivity(s, { at: Date.now(), repoId: normalized, kind: "bind", text: `bound (schedule ${repo.schedule})` });
117
+ await saveTeamAutoStore(s);
118
+ scheduleRepo(repo);
119
+ void provisionRepoInBackground(normalized, info.cloneUrl, info.defaultBranch);
120
+ logger.info(`TeamAuto: bound ${normalized} (schedule ${repo.schedule}${repo.dryRunDone ? "" : ", first sweep dry-run"}; provisioning in background)`);
121
+ return repo;
122
+ }
123
+
124
+ async function provisionRepoInBackground(repoId: string, cloneUrl: string, defaultBranch: string): Promise<void> {
125
+ try {
126
+ const s0 = await ensureStore();
127
+ const repoRef = s0.repos.find((r) => r.id === repoId);
128
+ if (!repoRef) { return; }
129
+ await updateRepoProvision(repoId, { status: "provisioning", message: "learning repo norms" });
130
+ const norms = await learnNorms(repoRef, client, sync, cloneUrl, defaultBranch);
131
+ await updateRepoProvision(repoId, { status: "ready", message: "ready", norms });
132
+ const sReady = await ensureStore();
133
+ pushTeamAutoActivity(sReady, { at: Date.now(), repoId, kind: "provision", text: "ready (clone + norms done)" });
134
+ logger.info(`TeamAuto: provisioned ${repoId} (clone + norms done)`);
135
+ } catch (err) {
136
+ const message = err instanceof Error ? err.message : String(err);
137
+ logger.warn(`TeamAuto: provisioning failed for ${repoId}: ${message}`);
138
+ await updateRepoProvision(repoId, { status: "failed", message });
139
+ }
140
+ }
141
+
142
+ async function updateRepoProvision(repoId: string, patch: Partial<TeamAutoRepoProvision> & { norms?: TeamAutoRepoNorms }): Promise<void> {
143
+ const s = await ensureStore();
144
+ const repo = s.repos.find((r) => r.id === repoId);
145
+ if (!repo) { return; }
146
+ repo.provision = { status: patch.status ?? repo.provision?.status ?? "provisioning", message: patch.message ?? repo.provision?.message ?? "", startedAt: repo.provision?.startedAt ?? Date.now(), updatedAt: Date.now() };
147
+ if (patch.norms) { repo.norms = patch.norms; }
148
+ await saveTeamAutoStore(s);
149
+ }
150
+
151
+ async function removeRepo(repoId: string): Promise<void> {
152
+ const s = await ensureStore();
153
+ s.repos = s.repos.filter((r) => r.id !== repoId);
154
+ await saveTeamAutoStore(s);
155
+ const timer = timers.get(repoId);
156
+ if (timer) {
157
+ clearTimeout(timer);
158
+ timers.delete(repoId);
159
+ }
160
+ }
161
+
162
+ async function setRepoEnabled(repoId: string, enabled: boolean): Promise<void> {
163
+ const s = await ensureStore();
164
+ const repo = s.repos.find((r) => r.id === repoId);
165
+ if (!repo) {
166
+ throw new Error(`${repoId} not bound`);
167
+ }
168
+ repo.enabled = enabled;
169
+ repo.pausedReason = enabled ? null : (repo.pausedReason ?? "disabled by user");
170
+ await saveTeamAutoStore(s);
171
+ if (enabled) {
172
+ scheduleRepo(repo);
173
+ }
174
+ }
175
+
176
+ async function updateRepo(repoId: string, patch: { schedule?: string; maxTasksPerSweep?: number; fullReview?: "off" | "weekly" | "daily"; takeOwnership?: boolean } = {}): Promise<TeamAutoRepo> {
177
+ const s = await ensureStore();
178
+ const repo = s.repos.find((r) => r.id === repoId);
179
+ if (!repo) {
180
+ throw new Error(`${repoId} not bound`);
181
+ }
182
+ if (patch.schedule?.trim()) {
183
+ repo.schedule = patch.schedule.trim();
184
+ }
185
+ if (typeof patch.maxTasksPerSweep === "number" && patch.maxTasksPerSweep > 0) {
186
+ repo.policy.maxTasksPerSweep = Math.min(20, Math.floor(patch.maxTasksPerSweep));
187
+ }
188
+ if (patch.fullReview) {
189
+ repo.policy.actions.fullReview = patch.fullReview;
190
+ }
191
+ if (typeof patch.takeOwnership === "boolean") {
192
+ repo.policy.actions.takeOwnership = patch.takeOwnership;
193
+ }
194
+ await saveTeamAutoStore(s);
195
+ scheduleRepo(repo);
196
+ return repo;
197
+ }
198
+
199
+ async function runSweepNow(repoId: string, force = true): Promise<string> {
200
+ const s = await ensureStore();
201
+ const repo = s.repos.find((r) => r.id === repoId);
202
+ if (!repo) {
203
+ throw new Error(`${repoId} not bound`);
204
+ }
205
+ return runSweep(repo, force);
206
+ }
207
+
208
+ // ---------- sweep engine ----------
209
+
210
+ async function runSweep(repo: TeamAutoRepo, force: boolean): Promise<string> {
211
+ // Sweeps stay gated until bind-time provisioning (clone + norms) settles.
212
+ if (repo.provision?.status === "provisioning") {
213
+ const summary = `skipped: still provisioning (${repo.provision.message})`;
214
+ logger.debug?.(`TeamAuto: ${repo.id} ${summary}`);
215
+ return summary;
216
+ }
217
+ if (repo.provision?.status === "failed") {
218
+ const summary = `skipped: provisioning failed (${repo.provision.message})`;
219
+ logger.warn(`TeamAuto: ${repo.id} ${summary}`);
220
+ return summary;
221
+ }
222
+ const s = await ensureStore();
223
+ if (sweeping.has(repo.id)) {
224
+ return "sweep already in progress";
225
+ }
226
+ sweeping.add(repo.id);
227
+ try {
228
+ const { candidates, issues, pulls } = await sweepRepo(repo, client);
229
+ const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
230
+ if (dryRun) {
231
+ // One observing pass, then act. Flip unconditionally - flipping only
232
+ // when candidates existed deadlocked empty first sweeps in dry-run
233
+ // mode forever (dry-run never advanced cursors -> still "first sweep"
234
+ // -> still zero candidates -> dryRunDone never set).
235
+ repo.dryRunDone = true;
236
+ }
237
+ if (!dryRun) {
238
+ // Advance only for acting sweeps: a dry-run must leave the cursors
239
+ // untouched so the reported actions are actually performed next time
240
+ // instead of being marked as already-seen.
241
+ advanceCursors(repo, issues, pulls);
242
+ }
243
+ // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
244
+ // pull candidates, so a busy repo would otherwise starve them forever
245
+ // (cap filled every sweep, lastFullReviewAt never advancing). They are
246
+ // at most one cycle (3 sections) per interval, so this stays bounded.
247
+ const fullReviews = candidates.filter((c) => c.kind === "fullReview");
248
+ const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
249
+ const capped = [...fullReviews, ...regular];
250
+ let created = 0;
251
+ const summary: string[] = [`found ${candidates.length} candidate(s)`];
252
+
253
+ if (capped.length && dryRun) {
254
+ summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
255
+ repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
256
+ } else if (capped.length) {
257
+ if (!consumeDailyBudget(s, capped.length)) {
258
+ summary.push("skipped: daily task budget exhausted");
259
+ } else {
260
+ for (const candidate of capped) {
261
+ const taskId = enqueueCandidate(repo, candidate);
262
+ if (taskId) {
263
+ pushTeamAutoActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
264
+ const action = candidate.kind === "prReview"
265
+ ? ("prComment" as const)
266
+ : candidate.kind === "fullReview"
267
+ ? ("createIssue" as const)
268
+ : ("issueComment" as const);
269
+ registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
270
+ created++;
271
+ }
272
+ }
273
+ repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
274
+ if (capped.some((c) => c.kind === "fullReview")) {
275
+ repo.cursors.lastFullReviewAt = Date.now();
276
+ }
277
+ }
278
+ } else {
279
+ repo.lastSweepSummary = "no new work";
280
+ }
281
+ repo.lastSweepAt = Date.now();
282
+ pushTeamAutoActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
283
+ await saveTeamAutoStore(s);
284
+ if (created > 0) {
285
+ await deps.onTasksCreated().catch((err) => {
286
+ logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
287
+ });
288
+ }
289
+ logger.info(`TeamAuto: sweep ${repo.id} -> ${repo.lastSweepSummary}`);
290
+ return repo.lastSweepSummary ?? "sweep complete";
291
+ } catch (err) {
292
+ const message = err instanceof Error ? err.message : String(err);
293
+ repo.pausedReason = `sweep failed: ${message}`;
294
+ await saveTeamAutoStore(s).catch(() => {});
295
+ logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
296
+ return `error: ${message}`;
297
+ } finally {
298
+ sweeping.delete(repo.id);
299
+ }
300
+ }
301
+
302
+ function enqueueCandidate(repo: TeamAutoRepo, candidate: Candidate): string | undefined {
303
+ let createdId: string | undefined;
304
+ deps.updateTeamState((state) => {
305
+ // Idempotency: an active task for the same object AND kind wins. The
306
+ // key rides in the description (TaskInfo has no dedicated field) and
307
+ // must be a distinct marked line - titles contain human text that never
308
+ // matches the raw key (that was the pre-fix bug). Kind-scoping matters:
309
+ // object-level keys starved takeOwnership (review always enqueued first).
310
+ const dedupMarker = `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
311
+ const duplicate = Object.values(state.tasks).find(
312
+ (t) => t.description.includes(dedupMarker) && t.status !== "completed" && t.status !== "failed",
313
+ );
314
+ if (duplicate) {
315
+ return;
316
+ }
317
+ const task: TaskInfo = {
318
+ id: newId("teamauto"),
319
+ title: `[${candidate.kind}] ${candidate.title}`,
320
+ description: [
321
+ `TeamAuto autonomous work for ${candidate.repoId}.`,
322
+ dedupMarker,
323
+ `Local checkout: projects/${teamAutoProjectDir(candidate.repoId)} in the team workspace.`,
324
+ ...(candidate.writeMode === "read-only" || (!candidate.writeMode && candidate.kind !== "takeOwnership")
325
+ ? [
326
+ "READ-ONLY TASK (collaboration contract): You must NOT modify, create, or delete any files - your reply IS the deliverable.",
327
+ "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.",
328
+ ]
329
+ : [
330
+ "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.",
331
+ ]),
332
+ renderNormsBlock(repo.norms, repo.id),
333
+ "---",
334
+ candidate.context,
335
+ "---",
336
+ `When finished, your reply becomes the GitHub ${candidate.kind === "prReview" || candidate.kind === "issueReview" ? "review comment" : "deliverable"}. ` +
337
+ `If the material is ambiguous or blocked on a human decision, request clarification instead of guessing.`,
338
+ MARKER_FOOTER(candidate.role),
339
+ ].join("\n"),
340
+ status: "pending",
341
+ priority: candidate.kind === "takeOwnership" ? "high" : "medium",
342
+ assignedRole: candidate.role as RoleId,
343
+ writeMode: candidate.writeMode === "write" ? "write" : "read-only",
344
+ createdBy: "teamauto",
345
+ projectDir: teamAutoProjectDir(candidate.repoId),
346
+ createdAt: Date.now(),
347
+ updatedAt: Date.now(),
348
+ };
349
+ state.tasks[task.id] = task;
350
+ createdId = task.id;
351
+ });
352
+ return createdId;
353
+ }
354
+
355
+ // ---------- write-back reconciler ----------
356
+
357
+ async function reconcileWritebacks(): Promise<void> {
358
+ const s = await ensureStore();
359
+ const state0 = deps.getTeamState();
360
+ // Dead letters: entries whose task is gone or failed without a result can
361
+ // never deliver - drop them instead of accumulating forever.
362
+ if (state0) {
363
+ const before = s.writebacks.length;
364
+ s.writebacks = s.writebacks.filter((w) => {
365
+ if (w.doneAt) { return true; }
366
+ const t = state0.tasks[w.taskId];
367
+ const dead = !t || (t.status === "failed" && !t.result);
368
+ if (dead) {
369
+ logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
370
+ }
371
+ return !dead;
372
+ });
373
+ if (s.writebacks.length !== before) { await saveTeamAutoStore(s); }
374
+ }
375
+ // Self-heal: an entry whose task later COMPLETED with a result (e.g. the
376
+ // completion gate rejected an early submission, then a retry succeeded)
377
+ // must be retried - a sticky error here would silently drop delivery.
378
+ for (const w of s.writebacks) {
379
+ if (w.error && !w.doneAt && state0) {
380
+ const t = state0.tasks[w.taskId];
381
+ if (t && t.status === "completed" && t.result) {
382
+ w.error = null;
383
+ }
384
+ }
385
+ }
386
+ const pending = s.writebacks.filter((w) => !w.doneAt && !w.error);
387
+ if (!pending.length) {
388
+ return;
389
+ }
390
+ const state = deps.getTeamState();
391
+ if (!state) {
392
+ return;
393
+ }
394
+ for (const entry of pending) {
395
+ const task = state.tasks[entry.taskId];
396
+ if (!task || (task.status !== "completed" && task.status !== "failed")) {
397
+ continue;
398
+ }
399
+ const repo = s.repos.find((r) => r.id === entry.repoId);
400
+ const [owner, name] = entry.repoId.split("/");
401
+ try {
402
+ if (task.status === "failed" || !task.result) {
403
+ entry.error = task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result";
404
+ } else {
405
+ const role = (task.assignedRole ?? "qa") as string;
406
+ let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
407
+ let writebackDone = false;
408
+ // WRITE TASKS (collaboration contract): commit the task worktree,
409
+ // push its branch, open a PR, and attach the link to the reply.
410
+ const repoId = entry.repoId;
411
+ const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
412
+ if (isTeamAutoWrite) {
413
+ try {
414
+ const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
415
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
416
+ const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
417
+ const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
418
+ // Workers often commit themselves inside the worktree - deliver
419
+ // whenever the branch carries commits beyond base, not only when
420
+ // commitAll just added new ones.
421
+ const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
422
+ if (deliverable) {
423
+ await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
424
+ 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)}`);
425
+ entry.prUrl = pr.url;
426
+ body = `${body}\n\nDelivered as PR: ${pr.url}`;
427
+ pushTeamAutoActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
428
+ }
429
+ await sync.removeTaskWorktree(repoId, task.id);
430
+ } catch (prErr) {
431
+ entry.error = `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`;
432
+ logger.warn(`TeamAuto: ${entry.error} (${task.id})`);
433
+ }
434
+ }
435
+ if (entry.action === "issueComment" && entry.targetId) {
436
+ await client.postIssueComment(owner, name, entry.targetId, body);
437
+ entry.doneAt = Date.now();
438
+ writebackDone = true;
439
+ } else if (entry.action === "prComment" && entry.targetId) {
440
+ await client.postPullReviewComment(owner, name, entry.targetId, body);
441
+ entry.doneAt = Date.now();
442
+ writebackDone = true;
443
+ } else if (entry.action === "createIssue") {
444
+ // Joint full review: same-cycle sections land in ONE umbrella issue
445
+ // (first completed section creates it, the rest post as comments).
446
+ const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
447
+ if (entry.cycleKey) {
448
+ const peers = s.writebacks.filter((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
449
+ const umbrella = peers[0];
450
+ if (umbrella && umbrella.targetId != null) {
451
+ await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
452
+ entry.targetId = umbrella.targetId;
453
+ entry.doneAt = Date.now();
454
+ writebackDone = true;
455
+ } else if (entry.targetId == null) {
456
+ const number = await client.createIssue(
457
+ owner,
458
+ name,
459
+ `[teamclaw:fullreview] Joint full review - ${entry.repoId}`,
460
+ `Joint multi-role full review (cycle ${entry.cycleKey}). Each role appends its section as a comment below.\n\n${sectionBody}`,
461
+ ["teamclaw", "teamclaw:fullreview"],
462
+ );
463
+ entry.targetId = number;
464
+ entry.doneAt = Date.now();
465
+ writebackDone = true;
466
+ }
467
+ } else {
468
+ const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
469
+ entry.targetId = number;
470
+ entry.doneAt = Date.now();
471
+ writebackDone = true;
472
+ }
473
+ } else {
474
+ entry.error = `unsupported action ${entry.action}`;
475
+ }
476
+ if (writebackDone) {
477
+ pushTeamAutoActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id})` });
478
+ }
479
+ }
480
+ } catch (err) {
481
+ entry.error = err instanceof Error ? err.message : String(err);
482
+ logger.warn(`TeamAuto: writeback failed (${entry.repoId} ${entry.action} #${entry.targetId ?? "-"}): ${entry.error}`);
483
+ }
484
+ void repo;
485
+ }
486
+ s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
487
+ await saveTeamAutoStore(s);
488
+ }
489
+
490
+ // Register the write-back intent when a task lands in the task store.
491
+ function registerWriteback(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): void {
492
+ void ensureStore().then((s) => {
493
+ if (s.writebacks.some((w) => w.taskId === taskId)) {
494
+ return;
495
+ }
496
+ s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
497
+ void saveTeamAutoStore(s);
498
+ }).catch(() => {});
499
+ }
500
+
501
+ // ---------- scheduling loop ----------
502
+
503
+ function scheduleRepo(repo: TeamAutoRepo): void {
504
+ const previous = timers.get(repo.id);
505
+ if (previous) {
506
+ clearTimeout(previous);
507
+ timers.delete(repo.id);
508
+ }
509
+ if (!repo.enabled) {
510
+ return;
511
+ }
512
+ const delay = nextFireMs(repo.schedule);
513
+ const timer = setTimeout(() => {
514
+ void (async () => {
515
+ const s = await ensureStore();
516
+ const fresh = s.repos.find((r) => r.id === repo.id);
517
+ if (fresh?.enabled && fresh.pausedReason === null) {
518
+ await runSweep(fresh, false);
519
+ }
520
+ if (fresh?.enabled) {
521
+ scheduleRepo(fresh);
522
+ }
523
+ })();
524
+ }, delay);
525
+ timer.unref?.();
526
+ timers.set(repo.id, timer);
527
+ }
528
+
529
+ async function start(): Promise<void> {
530
+ if (running) {
531
+ return;
532
+ }
533
+ running = true;
534
+ const s = await ensureStore();
535
+ for (const repo of s.repos) {
536
+ scheduleRepo(repo);
537
+ }
538
+ if (s.repos.length) {
539
+ logger.info(`TeamAuto: scheduler started for ${s.repos.length} repo(s)`);
540
+ }
541
+ writebackTimer = setInterval(() => {
542
+ void reconcileWritebacks();
543
+ }, 20_000);
544
+ writebackTimer.unref?.();
545
+ }
546
+
547
+ async function stop(): Promise<void> {
548
+ running = false;
549
+ for (const timer of timers.values()) {
550
+ clearTimeout(timer);
551
+ }
552
+ timers.clear();
553
+ if (writebackTimer) {
554
+ clearInterval(writebackTimer);
555
+ writebackTimer = null;
556
+ }
557
+ }
558
+
559
+ async function getStatus(): Promise<{ repos: TeamAutoRepo[]; budget: TeamAutoStore["budget"]; activity: NonNullable<TeamAutoStore["activity"]> }> {
560
+ const s = await ensureStore();
561
+ return { repos: s.repos, budget: s.budget, activity: s.activity ?? [] };
562
+ }
563
+
564
+ async function getActivity(): Promise<NonNullable<TeamAutoStore["activity"]>> {
565
+ const s = await ensureStore();
566
+ return (s.activity ?? []).slice().reverse();
567
+ }
568
+
569
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree };
570
+
571
+ /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
572
+ async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {
573
+ const wtAbs = await sync.ensureTaskWorktree(repoId, taskId);
574
+ void wtAbs;
575
+ // Rel dir INCLUDING the teamauto/ level (basename dropped it and pointed
576
+ // workers outside the git worktree).
577
+ return sync.taskWorktreeRelDir(repoId, taskId);
578
+ }
579
+
580
+ async function removeWriteWorktree(repoId: string, taskId: string): Promise<void> {
581
+ await sync.removeTaskWorktree(repoId, taskId);
582
+ }
583
+ }
584
+
585
+ export type TeamAutoScheduler = ReturnType<typeof createTeamAutoScheduler>;