@teamclaws/teamclaw 2026.11.2 → 2026.11.4

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 (38) hide show
  1. package/dist/src/controller/http-server.js +18 -0
  2. package/dist/src/controller/journal.js +68 -0
  3. package/dist/src/controller/provisioning/process-supervisor.js +58 -2
  4. package/dist/src/controller/provisioning-config.js +53 -0
  5. package/dist/src/controller/route-table.js +5 -0
  6. package/dist/src/controller/security.js +39 -0
  7. package/dist/src/controller/teamauto-routes.js +12 -0
  8. package/dist/src/controller/tunnel-manager.js +33 -1
  9. package/dist/src/controller/tunnel-routes.js +17 -1
  10. package/dist/src/controller/websocket.js +4 -0
  11. package/dist/src/controller/worker-provisioning.js +36 -0
  12. package/dist/src/state.js +77 -1
  13. package/dist/src/teamauto/github-client.js +39 -0
  14. package/dist/src/teamauto/scanner.js +9 -1
  15. package/dist/src/teamauto/scheduler.js +368 -17
  16. package/dist/src/teamauto/store.js +13 -0
  17. package/dist/src/ui/app.js +44 -0
  18. package/dist/src/ui/index.html +15 -0
  19. package/openclaw.plugin.json +1 -1
  20. package/package.json +1 -1
  21. package/src/controller/http-server.ts +18 -0
  22. package/src/controller/journal.ts +89 -0
  23. package/src/controller/provisioning/process-supervisor.ts +56 -2
  24. package/src/controller/provisioning-config.ts +54 -0
  25. package/src/controller/route-table.ts +5 -0
  26. package/src/controller/security.ts +40 -0
  27. package/src/controller/teamauto-routes.ts +12 -0
  28. package/src/controller/tunnel-manager.ts +34 -1
  29. package/src/controller/tunnel-routes.ts +18 -1
  30. package/src/controller/websocket.ts +5 -0
  31. package/src/controller/worker-provisioning.ts +34 -0
  32. package/src/state.ts +73 -2
  33. package/src/teamauto/github-client.ts +43 -0
  34. package/src/teamauto/scanner.ts +9 -1
  35. package/src/teamauto/scheduler.ts +372 -17
  36. package/src/teamauto/store.ts +40 -1
  37. package/src/ui/app.js +44 -0
  38. package/src/ui/index.html +15 -0
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import fs from "node:fs/promises";
2
3
 
3
4
  import type { PluginLogger } from "../../api.js";
4
5
  // Issue #226 W5: cross-subsystem contract lives in the shared layer now.
@@ -12,6 +13,7 @@ import { createGithubClient } from "./github-client.js";
12
13
  import { learnNorms, renderNormsBlock } from "./norms.js";
13
14
  import { createRepoSync, teamAutoProjectDir, type TaskDeliveryOracle } from "./repo-sync.js";
14
15
  import { nextFireMs } from "./schedule.js";
16
+ import { resolveTeamAutoPaths } from "./store.js";
15
17
  import { advanceCursors, sweepRepo, type Candidate } from "./scanner.js";
16
18
  import {
17
19
  consumeDailyBudget,
@@ -20,6 +22,7 @@ import {
20
22
  loadTeamAutoStore,
21
23
  pushTeamAutoActivity,
22
24
  saveTeamAutoStore,
25
+ pushSweepRecord,
23
26
  type TeamAutoActivityEntry,
24
27
  type TeamAutoRepo,
25
28
  type TeamAutoRepoNorms,
@@ -73,6 +76,21 @@ export function idempotencyMarker(candidate: { key: string; kind: string }): str
73
76
  return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
74
77
  }
75
78
 
79
+ /** #claim-recovery: parse the marker back out of a (failed) task's
80
+ * description - `{ repoId, number, kind, key }` or null. Issue candidates
81
+ * only (PR keys `#pr-` are not claim-bearing). */
82
+ export function parseClaimMarker(description: string): { repoId: string; number: number; kind: string; key: string } | null {
83
+ const m = /Idempotency-Key: ([^:\s]+)#issue-(\d+):(\w+)/.exec(description);
84
+ if (!m) {
85
+ return null;
86
+ }
87
+ const number = Number(m[2]);
88
+ if (!m[1] || !Number.isFinite(number)) {
89
+ return null;
90
+ }
91
+ return { repoId: m[1], number, kind: m[3], key: `${m[1]}#issue-${number}` };
92
+ }
93
+
76
94
  /** Failed task attempts for a candidate (task history is the attempt log). */
77
95
  export function failedAttemptCount(
78
96
  state: { tasks: Record<string, { description: string; status: string; error?: string }> },
@@ -93,16 +111,54 @@ export function hardAttemptCount(
93
111
  ).length;
94
112
  }
95
113
 
96
- /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
114
+ /** Auto-pause retry backoff for classes where a fast retry is useless or
115
+ * harmful: 30m after the 1st failure, doubling, capped at 4h. auth needs a
116
+ * human re-login; ratelimited retried early just re-triggers the limit. */
97
117
  export const SWEEP_RETRY_BASE_MINUTES = 30;
98
118
  export const SWEEP_RETRY_MAX_MINUTES = 240;
99
119
  export function sweepBackoffMinutes(failures: number): number {
100
120
  return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
101
121
  }
102
122
 
123
+ /** Sweep-timeout report: a transient "fetch failed" sat a full 30m before
124
+ * its first retry - a seconds-long network blip cost half an hour of repo
125
+ * idle time. Network-class failures get a fast ladder: 1m, 2m, 4m... capped
126
+ * at 15m. The cap means a genuinely-down network converges to one attempt
127
+ * per 15m (slower than the old ladder's first step, so we never hammer),
128
+ * but a single blip costs one minute instead of thirty. */
129
+ export const SWEEP_NETWORK_RETRY_BASE_MINUTES = 1;
130
+ export const SWEEP_NETWORK_RETRY_MAX_MINUTES = 15;
131
+ export function sweepNetworkBackoffMinutes(failures: number): number {
132
+ return Math.min(SWEEP_NETWORK_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_NETWORK_RETRY_MAX_MINUTES);
133
+ }
134
+
135
+ /** Class-aware dispatch: the retry ladder a failure class deserves. */
136
+ export function sweepBackoffMinutesFor(failClass: SweepFailClass, failures: number): number {
137
+ return failClass === "network" ? sweepNetworkBackoffMinutes(failures) : sweepBackoffMinutes(failures);
138
+ }
139
+
140
+ /** Timer floor when arming the retry ladder: a just-missed due time must not
141
+ * fire at 0ms (tight failure/retry loop protection). */
142
+ export const SWEEP_RETRY_FLOOR_MS = 5_000;
143
+
103
144
  /** Epoch ms when an auto-paused repo becomes due for its next retry attempt. */
104
- export function sweepRetryDueAt(failures: number, lastErrorAt: number): number {
105
- return lastErrorAt + sweepBackoffMinutes(failures) * 60_000;
145
+ export function sweepRetryDueAt(failures: number, lastErrorAt: number, failClass: SweepFailClass = "network"): number {
146
+ return lastErrorAt + sweepBackoffMinutesFor(failClass, failures) * 60_000;
147
+ }
148
+
149
+ /** In-place network retries: a transient "fetch failed"/"terminated" is
150
+ * retried immediately INSIDE the sweep invocation (user report 2026-11-14:
151
+ * "sweep failed[network] (auto-retry in ~30min): fetch failed" - the repo
152
+ * idled half an hour on a blip that a 5s retry would have survived). 10
153
+ * attempts with a 3s..30s delay ladder (~2.5min worst case) before the
154
+ * failure is recorded and the pause/backoff path takes over. Non-network
155
+ * classes (auth, ratelimited) never retry in place - retrying is useless
156
+ * or harmful. */
157
+ export const SWEEP_INPLACE_RETRIES = 10;
158
+ export const SWEEP_INPLACE_DELAY_BASE_MS = 3_000;
159
+ export const SWEEP_INPLACE_DELAY_MAX_MS = 30_000;
160
+ export function sweepInplaceDelayMs(attempt: number): number {
161
+ return Math.min(SWEEP_INPLACE_DELAY_BASE_MS * 2 ** Math.max(0, attempt - 1), SWEEP_INPLACE_DELAY_MAX_MS);
106
162
  }
107
163
 
108
164
  /**
@@ -130,9 +186,38 @@ export function writebackRetryDueAt(attempts: number, lastErrorAt: number): numb
130
186
  return lastErrorAt + writebackBackoffMs(attempts);
131
187
  }
132
188
 
133
- /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
189
+ /** #267-1: sweep failures are classified so operators can act on the RIGHT
190
+ * root cause: 401 -> re-login, 403/429 -> back off harder, network -> the
191
+ * existing retry ladder. undici wraps HTTP errors; the status rides on
192
+ * err.cause (fetch failed). Unknown causes stay "network" - the ladder's
193
+ * existing semantics. */
194
+ export type SweepFailClass = "auth" | "ratelimited" | "network";
195
+ export function classifySweepError(err: unknown): SweepFailClass {
196
+ const cause = (err as { cause?: { status?: number }; status?: number })?.cause ?? (err as { status?: number });
197
+ const status = Number(cause?.status ?? 0);
198
+ if (status === 401) return "auth";
199
+ if (status === 403 || status === 429) return "ratelimited";
200
+ return "network";
201
+ }
202
+
203
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not.
204
+ * Accept BOTH the legacy prefix ("sweep failed: ...") and the #267 classified
205
+ * format ("sweep failed[network]: ...") - the classified format broke the old
206
+ * startsWith("sweep failed:") check, so successful sweeps could never clear
207
+ * the pause and the retry timer never re-armed (all four repos stuck paused
208
+ * after the 12:30 restart-window failures; found 2026-11-12). */
134
209
  export function isAutoPause(reason: string | null | undefined): boolean {
135
- return !!reason && reason.startsWith("sweep failed:");
210
+ if (!reason) return false;
211
+ return /^sweep failed(\[[^\]]*\])?:/.test(reason);
212
+ }
213
+
214
+ /** Recover the fail class from a persisted auto-pause reason
215
+ * ("sweep failed[network]: ..."). Legacy/unparsable reasons default to the
216
+ * fast network ladder - a wrong guess only retries sooner, and the ladder
217
+ * itself still caps the attempt rate, so the default is safe. */
218
+ export function failClassFromPauseReason(reason: string | null | undefined): SweepFailClass {
219
+ const m = reason?.match(/^sweep failed\[([^\]]*)\]/);
220
+ return m && (m[1] === "auth" || m[1] === "ratelimited" || m[1] === "network") ? m[1] : "network";
136
221
  }
137
222
 
138
223
  export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
@@ -153,6 +238,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
153
238
  */
154
239
  function markWritebackFailure(store: TeamAutoStore, entry: TeamAutoWriteBack, message: string, options: { terminal?: boolean } = {}): void {
155
240
  entry.error = message;
241
+ entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
156
242
  entry.attempts = (entry.attempts ?? 0) + 1;
157
243
  entry.lastErrorAt = Date.now();
158
244
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
@@ -244,6 +330,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
244
330
  let running = false;
245
331
  let store: TeamAutoStore | null = null;
246
332
  let writebackTimer: NodeJS.Timeout | null = null;
333
+ let claimRecoveryTimer: NodeJS.Timeout | null = null;
247
334
 
248
335
  async function ensureStore(): Promise<TeamAutoStore> {
249
336
  if (!store) {
@@ -408,8 +495,34 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
408
495
  return "sweep already in progress";
409
496
  }
410
497
  sweeping.add(repo.id);
498
+ const sweepStartedAt = Date.now();
499
+ const etagBefore = client.etagStats();
411
500
  try {
412
- const { candidates, issues, pulls, newCommits, commits } = await sweepRepo(repo, client);
501
+ // #sweep-inplace: transient network failures retry IN PLACE (see
502
+ // SWEEP_INPLACE_RETRIES) - only a network blip that survives ~2.5min of
503
+ // retrying reaches the failure-recording path below.
504
+ let swept: Awaited<ReturnType<typeof sweepRepo>> | undefined;
505
+ let lastNetworkErr: unknown;
506
+ for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
507
+ try {
508
+ swept = await sweepRepo(repo, client);
509
+ break;
510
+ } catch (err) {
511
+ if (classifySweepError(err) !== "network") {
512
+ throw err;
513
+ }
514
+ lastNetworkErr = err;
515
+ const message0 = err instanceof Error ? err.message : String(err);
516
+ logger.warn(`TeamAuto: sweep ${repo.id} network error (attempt ${attempt}/${SWEEP_INPLACE_RETRIES}): ${message0}`);
517
+ if (attempt < SWEEP_INPLACE_RETRIES) {
518
+ await new Promise((resolve) => setTimeout(resolve, sweepInplaceDelayMs(attempt)));
519
+ }
520
+ }
521
+ }
522
+ if (!swept) {
523
+ throw lastNetworkErr;
524
+ }
525
+ const { candidates, issues, pulls, newCommits, commits } = swept;
413
526
  const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
414
527
  if (dryRun) {
415
528
  // One observing pass, then act. Flip unconditionally - flipping only
@@ -452,6 +565,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
452
565
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
453
566
  } else if (taskId) {
454
567
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
568
+ claimIssue(repo, candidate); // #268: visible claim at enqueue time
455
569
  const action = candidate.kind === "prReview"
456
570
  ? ("prComment" as const)
457
571
  : candidate.kind === "fullReview"
@@ -476,6 +590,8 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
476
590
  }
477
591
  repo.sweepFailures = 0;
478
592
  repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
593
+ const etagAfter = client.etagStats();
594
+ pushSweepRecord(repo, { at: Date.now(), ok: true, summary: repo.lastSweepSummary ?? "sweep complete", durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
479
595
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
480
596
  await saveTeamAutoStore(s);
481
597
  if (created > 0) {
@@ -494,8 +610,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
494
610
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
495
611
  repo.lastSweepErrorAt = Date.now();
496
612
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
497
- repo.pausedReason = `sweep failed: ${message}`;
498
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
613
+ const failClass = classifySweepError(err);
614
+ repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
615
+ const etagAfter = client.etagStats();
616
+ pushSweepRecord(repo, { at: Date.now(), ok: false, summary: `sweep failed[${failClass}]: ${message}`, failClass, durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
617
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
499
618
  await saveTeamAutoStore(s).catch(() => {});
500
619
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
501
620
  return `error: ${message}`;
@@ -620,9 +739,65 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
620
739
  }
621
740
 
622
741
  // ---------- write-back reconciler ----------
623
-
742
+ // #269: the 20s interval fires `void reconcileWritebacks()` fire-and-forget,
743
+ // and a slow delivery (worktree ensure + commit + PR > 20s) let the next
744
+ // tick re-read the same pending entries before doneAt landed - same
745
+ // comment delivered twice (ggcode#5480, byte-identical pair). Two-layer
746
+ // fix: serialize the whole pass (guard below) + intent-first inFlightAt
747
+ // persisted BEFORE dispatch so even a concurrent caller cannot re-send.
748
+ let reconcileInFlight = false;
624
749
  async function reconcileWritebacks(): Promise<void> {
625
- const s = await ensureStore();
750
+ if (reconcileInFlight) {
751
+ return; // a pass is still delivering - never overlap (#269)
752
+ }
753
+ // #269 recurrence (23:40 CST): MULTIPLE gateway processes share one
754
+ // ~/.openclaw store (launchctl service + spawned gateways). In-process
755
+ // guards cannot see another process's deliveries - each kept its
756
+ // startup-cached store and delivered the same pending row (3s apart,
757
+ // two "issueComment ok" for one task). Cross-process mutex: an atomic
758
+ // mkdir lock dir next to the store file; stale (>5min) locks are
759
+ // taken over (crashed holder).
760
+ const { storeFile } = resolveTeamAutoPaths();
761
+ const lockDir = `${storeFile}.reconcile-lock`;
762
+ let locked = false;
763
+ try {
764
+ try {
765
+ await fs.mkdir(lockDir);
766
+ locked = true;
767
+ } catch {
768
+ // Held - unless stale (holder crashed mid-pass).
769
+ try {
770
+ const st = await fs.stat(lockDir);
771
+ if (Date.now() - st.mtimeMs > 300_000) {
772
+ await fs.rm(lockDir, { recursive: true, force: true });
773
+ await fs.mkdir(lockDir);
774
+ locked = true;
775
+ }
776
+ } catch { /* racing takeover - someone else won; skip this pass */ }
777
+ }
778
+ if (!locked) {
779
+ return; // another PROCESS is mid-reconcile; our next tick re-tries
780
+ }
781
+ reconcileInFlight = true;
782
+ try {
783
+ await doReconcileWritebacks();
784
+ } finally {
785
+ reconcileInFlight = false;
786
+ }
787
+ } finally {
788
+ if (locked) {
789
+ await fs.rm(lockDir, { recursive: true, force: true }).catch(() => {});
790
+ }
791
+ }
792
+ }
793
+
794
+ async function doReconcileWritebacks(): Promise<void> {
795
+ // #269 recurrence: re-read the store from disk EVERY pass - the
796
+ // closure cache is a startup snapshot that never sees another
797
+ // process's persisted inFlightAt/doneAt, which is exactly how the
798
+ // 23:40 double delivery happened.
799
+ store = await loadTeamAutoStore();
800
+ const s = store;
626
801
  const state0 = deps.getTeamState();
627
802
  // Dead letters: entries whose task is gone or failed without a result can
628
803
  // never deliver - drop them instead of accumulating forever.
@@ -675,7 +850,30 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
675
850
  }
676
851
  }
677
852
  }
678
- const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
853
+ // #269: reset stale in-flight intents (crashed mid-dispatch) so they
854
+ // re-enter the pending set instead of wedging forever.
855
+ for (const w of s.writebacks) {
856
+ if (w.inFlightAt && !w.doneAt && Date.now() - w.inFlightAt > 600_000) {
857
+ w.inFlightAt = undefined;
858
+ }
859
+ }
860
+ const pendingAll = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt && !w.inFlightAt);
861
+ // #269 per-target dedupe (delivery side): cap at ONE entry per target
862
+ // key per pass, so N pending rows aimed at the same issue/PR cannot
863
+ // burst N same-second comments even if they somehow slipped the enqueue
864
+ // check (e.g. pre-fix stores). Deferred rows simply ride the next 20s
865
+ // pass. Null-target create* rows key on taskId: each is a distinct
866
+ // create intent and must never be merged.
867
+ const seenTarget = new Set<string>();
868
+ const pending = [];
869
+ for (const w of pendingAll) {
870
+ const key = w.targetId != null ? `${w.action}|${w.repoId}|${w.targetId}` : `${w.action}|${w.taskId}`;
871
+ if (seenTarget.has(key)) {
872
+ continue;
873
+ }
874
+ seenTarget.add(key);
875
+ pending.push(w);
876
+ }
679
877
  if (!pending.length) {
680
878
  return;
681
879
  }
@@ -684,6 +882,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
684
882
  return;
685
883
  }
686
884
  for (const entry of pending) {
885
+ // #269 intent-first: persist the dispatch intent BEFORE any await so
886
+ // an overlapping pass (or a future guard-less caller) filters this
887
+ // entry out instead of re-delivering it.
888
+ entry.inFlightAt = Date.now();
889
+ await saveTeamAutoStore(s);
687
890
  const task = state.tasks[entry.taskId];
688
891
  if (!task || (task.status !== "completed" && task.status !== "failed")) {
689
892
  continue;
@@ -725,6 +928,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
725
928
  // push its branch, open a PR, and attach the link to the reply.
726
929
  const repoId = entry.repoId;
727
930
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
931
+ let prDeliveryFailed = false;
728
932
  if (isTeamAutoWrite) {
729
933
  try {
730
934
  const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
@@ -745,11 +949,24 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
745
949
  await sync.removeTaskWorktree(repoId, task.id);
746
950
  } catch (prErr) {
747
951
  markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
952
+ // #269 4th recurrence (ggcode#5524): a failed PR step must abort
953
+ // the WHOLE entry this pass. The old fall-through posted the
954
+ // link-less comment anyway, set doneAt, and the #24 cleanup
955
+ // cleared the error - a partial delivery masked as success.
956
+ // The retry pass then delivered the WITH-link comment too:
957
+ // two comments 2s apart. Fail atomically instead: the entry
958
+ // keeps its failed state + backoff and replays BOTH steps
959
+ // (PR first, then comment) on the next attempt.
960
+ prDeliveryFailed = true;
748
961
  }
749
962
  }
963
+ if (prDeliveryFailed) {
964
+ continue;
965
+ }
750
966
  if (entry.action === "issueComment" && entry.targetId) {
751
967
  await client.postIssueComment(owner, name, entry.targetId, body);
752
968
  entry.doneAt = Date.now();
969
+ entry.inFlightAt = undefined;
753
970
  writebackDone = true;
754
971
  // Our own comment bumps the issue's updatedAt, which the scanner
755
972
  // treats as new activity - advance the seen cursor so we do not
@@ -762,6 +979,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
762
979
  } else if (entry.action === "prComment" && entry.targetId) {
763
980
  await client.postPullReviewComment(owner, name, entry.targetId, body);
764
981
  entry.doneAt = Date.now();
982
+ entry.inFlightAt = undefined;
765
983
  writebackDone = true;
766
984
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
767
985
  if (prRepo) {
@@ -778,6 +996,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
778
996
  await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
779
997
  entry.targetId = umbrella.targetId;
780
998
  entry.doneAt = Date.now();
999
+ entry.inFlightAt = undefined;
781
1000
  writebackDone = true;
782
1001
  } else if (entry.targetId == null) {
783
1002
  const number = await client.createIssue(
@@ -789,12 +1008,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
789
1008
  );
790
1009
  entry.targetId = number;
791
1010
  entry.doneAt = Date.now();
1011
+ entry.inFlightAt = undefined;
792
1012
  writebackDone = true;
793
1013
  }
794
1014
  } else {
795
1015
  const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
796
1016
  entry.targetId = number;
797
1017
  entry.doneAt = Date.now();
1018
+ entry.inFlightAt = undefined;
798
1019
  writebackDone = true;
799
1020
  }
800
1021
  } else {
@@ -824,11 +1045,129 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
824
1045
  if (s.writebacks.some((w) => w.taskId === taskId)) {
825
1046
  return;
826
1047
  }
1048
+ // #269 per-target dedupe (enqueue side): a second registration for
1049
+ // the SAME target + action with no doneAt yet is a duplicate in the
1050
+ // making - the delivery pass would fan out two comments onto one
1051
+ // target. Skip it; the pending original still delivers the content.
1052
+ // targetId null (create* actions) cannot be target-deduped pre-delivery
1053
+ // and is excluded by the taskId check above.
1054
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1055
+ return;
1056
+ }
827
1057
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
828
1058
  void saveTeamAutoStore(s);
829
1059
  }).catch(() => {});
830
1060
  }
831
1061
 
1062
+ /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
1063
+ * assignIssue was dead code and registerWriteback had no assign action, so
1064
+ * claims existed only in internal state - humans could not see the bot had
1065
+ * picked an issue up (collision risk), contradicting the design decision
1066
+ * that identity presents as the logged-in account's activity.
1067
+ * Fired at ENQUEUE time: a claim is a placeholder declaration; posting it
1068
+ * at completion would leave the whole execution window claim-invisible.
1069
+ * Best-effort, never blocks the task. Review notes (#268):
1070
+ * (a) re-check assignees at claim time (the scan snapshot is seconds
1071
+ * stale - a human may have self-assigned in between);
1072
+ * (b) stamp cursors.seen with NOW + 60s on BOTH success paths (assign
1073
+ * AND fallback comment) because our own write bumps the issue's
1074
+ * updated_at - a bare-assign stamp would lose the scanner's
1075
+ * `seen >= updatedAt` comparison next sweep and re-candidate the
1076
+ * issue we just claimed (self-triggering loop). */
1077
+ function claimIssue(repo: TeamAutoRepo, candidate: { key: string; number: number; kind: string; title: string }): void {
1078
+ if (candidate.kind !== "takeOwnership" || !candidate.number) {
1079
+ return;
1080
+ }
1081
+ void (async () => {
1082
+ const [owner, name] = repo.id.split("/");
1083
+ const client = createGithubClient(auth);
1084
+ try {
1085
+ const fresh = await client.getIssue(owner, name, candidate.number);
1086
+ if (fresh.state !== "open") {
1087
+ return;
1088
+ }
1089
+ if (repo.policy.skipAssignedToHumans && fresh.assignees.length > 0) {
1090
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claim skipped: issue #${candidate.number} gained an assignee since scan` });
1091
+ return;
1092
+ }
1093
+ const { login } = await client.getAuthenticatedUser();
1094
+ try {
1095
+ await client.assignIssue(owner, name, candidate.number, login);
1096
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
1097
+ } catch {
1098
+ // Fallback: a visible claim comment carries the same placeholder
1099
+ // semantics when the App lacks the assignees write surface.
1100
+ await client.postIssueComment(owner, name, candidate.number, `TeamClaw (teamclaw/developer, @${login}) has taken ownership of this issue and is implementing it autonomously - a PR will follow.`);
1101
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1102
+ }
1103
+ const s = await ensureStore();
1104
+ const freshRepo = s.repos.find((r) => r.id === repo.id);
1105
+ if (freshRepo) {
1106
+ // +60s guard: our own write (assign or comment) bumps updated_at;
1107
+ // see helper doc.
1108
+ freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1109
+ await saveTeamAutoStore(s);
1110
+ }
1111
+ } catch (err) {
1112
+ logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1113
+ }
1114
+ })();
1115
+ }
1116
+
1117
+ /** #claim-recovery: a task that CLAIMED an issue (takeOwnership stamps the
1118
+ * seen cursor AND self-assigns the bot at enqueue time; issueReview stamps
1119
+ * the cursor) locks the issue twice against re-candidacy. When the task
1120
+ * fails, the issue must not be orphaned - nobody (human or bot) would ever
1121
+ * pick it up again. Once per failed taskId: clear the seen stamp so the
1122
+ * next sweep re-candidates naturally, and for takeOwnership remove the
1123
+ * bot's own assignment (human assignees untouched). The existing
1124
+ * dead-letter caps (3 hard / 6 transient) bound how often this can loop. */
1125
+ async function recoverFailedClaims(): Promise<void> {
1126
+ const teamState = deps.getTeamState();
1127
+ if (!teamState) {
1128
+ return;
1129
+ }
1130
+ const s = await ensureStore();
1131
+ s.failedClaimRecovery ??= {};
1132
+ let changed = false;
1133
+ for (const [taskId, task] of Object.entries(teamState.tasks ?? {})) {
1134
+ if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1135
+ continue;
1136
+ }
1137
+ if (s.failedClaimRecovery[taskId]) {
1138
+ continue;
1139
+ }
1140
+ const parsed = parseClaimMarker(task.description);
1141
+ const repo = parsed ? s.repos.find((r) => r.id === parsed.repoId) : undefined;
1142
+ if (!parsed || !repo) {
1143
+ continue;
1144
+ }
1145
+ delete repo.cursors.seen[parsed.key];
1146
+ s.failedClaimRecovery[taskId] = Date.now();
1147
+ changed = true;
1148
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `recovered failed task ${taskId}: issue #${parsed.number} re-opened for the next sweep` });
1149
+ if (parsed.kind === "takeOwnership") {
1150
+ void (async () => {
1151
+ try {
1152
+ const client = createGithubClient(auth);
1153
+ const { login } = await client.getAuthenticatedUser();
1154
+ const [owner, name] = repo.id.split("/");
1155
+ await client.removeIssueAssignees(owner, name, parsed.number, [login]);
1156
+ } catch (err) {
1157
+ logger.warn(`TeamAuto: unassign for failed claim ${repo.id}#${parsed.number} failed (scanner may skip it until a human clears the assignee): ${err instanceof Error ? err.message : String(err)}`);
1158
+ }
1159
+ })();
1160
+ }
1161
+ }
1162
+ if (changed) {
1163
+ const entries = Object.entries(s.failedClaimRecovery).sort((a, b) => a[1] - b[1]);
1164
+ if (entries.length > 200) {
1165
+ s.failedClaimRecovery = Object.fromEntries(entries.slice(entries.length - 200));
1166
+ }
1167
+ await saveTeamAutoStore(s);
1168
+ }
1169
+ }
1170
+
832
1171
  // ---------- scheduling loop ----------
833
1172
 
834
1173
  function scheduleRepo(repo: TeamAutoRepo): void {
@@ -841,11 +1180,20 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
841
1180
  return;
842
1181
  }
843
1182
  let delay: number;
844
- try {
845
- delay = nextFireMs(repo.schedule);
846
- } catch (err) {
847
- logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
848
- return;
1183
+ // Auto-paused repos arm the RETRY ladder, not the regular schedule: the
1184
+ // retry-due check used to ride the next regular tick, so "auto-retry in
1185
+ // ~1min" for a network blip really meant "at the next hourly tick".
1186
+ // While paused, retry at the class-aware backoff; a successful sweep
1187
+ // clears pausedReason and restores the regular schedule below.
1188
+ if (isAutoPause(repo.pausedReason) && repo.lastSweepErrorAt) {
1189
+ delay = Math.max(SWEEP_RETRY_FLOOR_MS, sweepRetryDueAt(repo.sweepFailures ?? 1, repo.lastSweepErrorAt, failClassFromPauseReason(repo.pausedReason)) - Date.now());
1190
+ } else {
1191
+ try {
1192
+ delay = nextFireMs(repo.schedule);
1193
+ } catch (err) {
1194
+ logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
1195
+ return;
1196
+ }
849
1197
  }
850
1198
  const timer = setTimeout(() => {
851
1199
  void (async () => {
@@ -853,7 +1201,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
853
1201
  const s = await ensureStore();
854
1202
  const fresh = s.repos.find((r) => r.id === repo.id);
855
1203
  const retryDue = fresh
856
- ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
1204
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0, failClassFromPauseReason(fresh.pausedReason))
857
1205
  : false;
858
1206
  if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
859
1207
  await runSweep(fresh, false);
@@ -898,6 +1246,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
898
1246
  void reconcileWritebacks();
899
1247
  }, 20_000);
900
1248
  writebackTimer.unref?.();
1249
+ claimRecoveryTimer = setInterval(() => {
1250
+ void recoverFailedClaims();
1251
+ }, 60_000);
1252
+ claimRecoveryTimer.unref?.();
901
1253
  // Boot reconciliation: heal leftover task worktrees whose task is
902
1254
  // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
903
1255
  // on its own. Safety-checked: undelivered work is kept and logged.
@@ -959,6 +1311,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
959
1311
  timers.clear();
960
1312
  if (writebackTimer) {
961
1313
  clearInterval(writebackTimer);
1314
+ if (claimRecoveryTimer) {
1315
+ clearInterval(claimRecoveryTimer);
1316
+ }
962
1317
  writebackTimer = null;
963
1318
  }
964
1319
  }
@@ -75,6 +75,8 @@ export type TeamAutoRepo = {
75
75
  * answers "did the scheduler try recently" without the two surfaces
76
76
  * contradicting each other when read side by side. */
77
77
  lastAttemptAt?: number;
78
+ /** #267-2: bounded per-repo sweep ring (newest last, cap 20). */
79
+ sweeps?: TeamAutoSweepRecord[];
78
80
  dryRunDone: boolean;
79
81
  /** Bind-time provisioning state; ready/undefined means sweepable. */
80
82
  provision?: TeamAutoRepoProvision;
@@ -103,11 +105,16 @@ export type TeamAutoWriteBack = {
103
105
  lastErrorAt?: number;
104
106
  /** Epoch ms when the next retry becomes due (exponential backoff gate). */
105
107
  nextAttemptAt?: number;
108
+ /** #269: set (and persisted) BEFORE dispatch starts so overlapping
109
+ * reconcile passes can see the in-flight intent; cleared on success
110
+ * (doneAt) or failure (error/nextAttemptAt). A crashed process can
111
+ * leave it stale - reconciles older than 10 minutes are reset. */
112
+ inFlightAt?: number;
106
113
  /** Terminal marker: set when retry attempts are exhausted; never retried again. */
107
114
  failedAt?: number | null;
108
115
  };
109
116
 
110
- export type TeamAutoActivityKind = "bind" | "provision" | "sweep" | "task" | "writeback";
117
+ export type TeamAutoActivityKind = "bind" | "provision" | "sweep" | "task" | "writeback" | "claim" | "hygiene";
111
118
 
112
119
  export type TeamAutoActivityEntry = {
113
120
  at: number;
@@ -126,6 +133,29 @@ export function pushTeamAutoActivity(store: TeamAutoStore, entry: TeamAutoActivi
126
133
  }
127
134
  }
128
135
 
136
+ /** #267-2: bounded per-repo sweep ring (newest last, cap 20) - same slice
137
+ * pattern as pushTeamAutoActivity. */
138
+ export function pushSweepRecord(repo: TeamAutoRepo, entry: TeamAutoSweepRecord): void {
139
+ repo.sweeps = repo.sweeps ?? [];
140
+ repo.sweeps.push(entry);
141
+ if (repo.sweeps.length > 20) {
142
+ repo.sweeps = repo.sweeps.slice(repo.sweeps.length - 20);
143
+ }
144
+ }
145
+
146
+ /** #267-2 record type: one bounded per-repo sweep history entry. */
147
+ export type TeamAutoSweepRecord = {
148
+ at: number;
149
+ ok: boolean;
150
+ summary: string;
151
+ /** #267-1 classification when ok=false: auth | ratelimited | network. */
152
+ failClass?: "auth" | "ratelimited" | "network";
153
+ durationMs: number;
154
+ /** #267-3 per-sweep deltas of the client's cumulative etag counters. */
155
+ etagCalls: number;
156
+ etag304Hits: number;
157
+ };
158
+
129
159
  export type TeamAutoStore = {
130
160
  version: number;
131
161
  repos: TeamAutoRepo[];
@@ -138,6 +168,11 @@ export type TeamAutoStore = {
138
168
  tasksToday: number;
139
169
  dayStamp: string;
140
170
  };
171
+ /** #claim-recovery: taskId -> recoveredAt. A failed task whose candidate
172
+ * claimed an issue must not orphan it - the recovery pass clears the seen
173
+ * stamp (and the bot's self-assignment) once per taskId so the next sweep
174
+ * re-candidates naturally, while the dead-letter caps bound retries. */
175
+ failedClaimRecovery?: Record<string, number>;
141
176
  };
142
177
 
143
178
  export function defaultPolicy(): TeamAutoRepoPolicy {
@@ -161,6 +196,7 @@ function emptyStore(): TeamAutoStore {
161
196
  repos: [],
162
197
  writebacks: [],
163
198
  activity: [],
199
+ failedClaimRecovery: {},
164
200
  budget: {
165
201
  maxTasksPerDay: 150,
166
202
  firstSweepDryRun: true,
@@ -219,6 +255,9 @@ export async function loadTeamAutoStore(): Promise<TeamAutoStore> {
219
255
  if (Array.isArray(parsed.activity)) {
220
256
  store.activity = parsed.activity.slice(-TEAMAUTO_ACTIVITY_LIMIT);
221
257
  }
258
+ if (parsed.failedClaimRecovery && typeof parsed.failedClaimRecovery === "object") {
259
+ store.failedClaimRecovery = parsed.failedClaimRecovery as Record<string, number>;
260
+ }
222
261
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
223
262
  return store;
224
263
  } catch {