@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
  // Phase 2.3/2.5 (cross-review adopted suggestion): manual-proposal roles
3
4
  // validate against the ACTIVE profile and default to its defaultRole instead
4
5
  // of hardcoded software role literals.
@@ -7,8 +8,9 @@ import { createGithubClient } from "./github-client.js";
7
8
  import { learnNorms, renderNormsBlock } from "./norms.js";
8
9
  import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
9
10
  import { nextFireMs } from "./schedule.js";
11
+ import { resolveTeamAutoPaths } from "./store.js";
10
12
  import { advanceCursors, sweepRepo } from "./scanner.js";
11
- import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, } from "./store.js";
13
+ import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, pushSweepRecord, } from "./store.js";
12
14
  /**
13
15
  * TeamAuto scheduler: per-repo cron sweeps -> TeamClaw tasks -> GitHub
14
16
  * write-backs. Fully autonomous per the user's decisions (TEAMAUTO_DESIGN.md):
@@ -37,6 +39,20 @@ export const TRANSIENT_FAILURE_RE = /workspace filesystem changed|ai service nee
37
39
  export function idempotencyMarker(candidate) {
38
40
  return `Idempotency-Key: ${candidate.key}:${candidate.kind}`;
39
41
  }
42
+ /** #claim-recovery: parse the marker back out of a (failed) task's
43
+ * description - `{ repoId, number, kind, key }` or null. Issue candidates
44
+ * only (PR keys `#pr-` are not claim-bearing). */
45
+ export function parseClaimMarker(description) {
46
+ const m = /Idempotency-Key: ([^:\s]+)#issue-(\d+):(\w+)/.exec(description);
47
+ if (!m) {
48
+ return null;
49
+ }
50
+ const number = Number(m[2]);
51
+ if (!m[1] || !Number.isFinite(number)) {
52
+ return null;
53
+ }
54
+ return { repoId: m[1], number, kind: m[3], key: `${m[1]}#issue-${number}` };
55
+ }
40
56
  /** Failed task attempts for a candidate (task history is the attempt log). */
41
57
  export function failedAttemptCount(state, candidate) {
42
58
  const marker = idempotencyMarker(candidate);
@@ -47,15 +63,49 @@ export function hardAttemptCount(state, candidate) {
47
63
  const marker = idempotencyMarker(candidate);
48
64
  return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed" && !(t.error && TRANSIENT_FAILURE_RE.test(t.error))).length;
49
65
  }
50
- /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
66
+ /** Auto-pause retry backoff for classes where a fast retry is useless or
67
+ * harmful: 30m after the 1st failure, doubling, capped at 4h. auth needs a
68
+ * human re-login; ratelimited retried early just re-triggers the limit. */
51
69
  export const SWEEP_RETRY_BASE_MINUTES = 30;
52
70
  export const SWEEP_RETRY_MAX_MINUTES = 240;
53
71
  export function sweepBackoffMinutes(failures) {
54
72
  return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
55
73
  }
74
+ /** Sweep-timeout report: a transient "fetch failed" sat a full 30m before
75
+ * its first retry - a seconds-long network blip cost half an hour of repo
76
+ * idle time. Network-class failures get a fast ladder: 1m, 2m, 4m... capped
77
+ * at 15m. The cap means a genuinely-down network converges to one attempt
78
+ * per 15m (slower than the old ladder's first step, so we never hammer),
79
+ * but a single blip costs one minute instead of thirty. */
80
+ export const SWEEP_NETWORK_RETRY_BASE_MINUTES = 1;
81
+ export const SWEEP_NETWORK_RETRY_MAX_MINUTES = 15;
82
+ export function sweepNetworkBackoffMinutes(failures) {
83
+ return Math.min(SWEEP_NETWORK_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_NETWORK_RETRY_MAX_MINUTES);
84
+ }
85
+ /** Class-aware dispatch: the retry ladder a failure class deserves. */
86
+ export function sweepBackoffMinutesFor(failClass, failures) {
87
+ return failClass === "network" ? sweepNetworkBackoffMinutes(failures) : sweepBackoffMinutes(failures);
88
+ }
89
+ /** Timer floor when arming the retry ladder: a just-missed due time must not
90
+ * fire at 0ms (tight failure/retry loop protection). */
91
+ export const SWEEP_RETRY_FLOOR_MS = 5_000;
56
92
  /** 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;
93
+ export function sweepRetryDueAt(failures, lastErrorAt, failClass = "network") {
94
+ return lastErrorAt + sweepBackoffMinutesFor(failClass, failures) * 60_000;
95
+ }
96
+ /** In-place network retries: a transient "fetch failed"/"terminated" is
97
+ * retried immediately INSIDE the sweep invocation (user report 2026-11-14:
98
+ * "sweep failed[network] (auto-retry in ~30min): fetch failed" - the repo
99
+ * idled half an hour on a blip that a 5s retry would have survived). 10
100
+ * attempts with a 3s..30s delay ladder (~2.5min worst case) before the
101
+ * failure is recorded and the pause/backoff path takes over. Non-network
102
+ * classes (auth, ratelimited) never retry in place - retrying is useless
103
+ * or harmful. */
104
+ export const SWEEP_INPLACE_RETRIES = 10;
105
+ export const SWEEP_INPLACE_DELAY_BASE_MS = 3_000;
106
+ export const SWEEP_INPLACE_DELAY_MAX_MS = 30_000;
107
+ export function sweepInplaceDelayMs(attempt) {
108
+ return Math.min(SWEEP_INPLACE_DELAY_BASE_MS * 2 ** Math.max(0, attempt - 1), SWEEP_INPLACE_DELAY_MAX_MS);
59
109
  }
60
110
  /**
61
111
  * Issue #24: max write-back delivery attempts before the entry is marked
@@ -79,9 +129,33 @@ export function writebackBackoffMs(attempts) {
79
129
  export function writebackRetryDueAt(attempts, lastErrorAt) {
80
130
  return lastErrorAt + writebackBackoffMs(attempts);
81
131
  }
82
- /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
132
+ export function classifySweepError(err) {
133
+ const cause = err?.cause ?? err;
134
+ const status = Number(cause?.status ?? 0);
135
+ if (status === 401)
136
+ return "auth";
137
+ if (status === 403 || status === 429)
138
+ return "ratelimited";
139
+ return "network";
140
+ }
141
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not.
142
+ * Accept BOTH the legacy prefix ("sweep failed: ...") and the #267 classified
143
+ * format ("sweep failed[network]: ...") - the classified format broke the old
144
+ * startsWith("sweep failed:") check, so successful sweeps could never clear
145
+ * the pause and the retry timer never re-armed (all four repos stuck paused
146
+ * after the 12:30 restart-window failures; found 2026-11-12). */
83
147
  export function isAutoPause(reason) {
84
- return !!reason && reason.startsWith("sweep failed:");
148
+ if (!reason)
149
+ return false;
150
+ return /^sweep failed(\[[^\]]*\])?:/.test(reason);
151
+ }
152
+ /** Recover the fail class from a persisted auto-pause reason
153
+ * ("sweep failed[network]: ..."). Legacy/unparsable reasons default to the
154
+ * fast network ladder - a wrong guess only retries sooner, and the ladder
155
+ * itself still caps the attempt rate, so the default is safe. */
156
+ export function failClassFromPauseReason(reason) {
157
+ const m = reason?.match(/^sweep failed\[([^\]]*)\]/);
158
+ return m && (m[1] === "auth" || m[1] === "ratelimited" || m[1] === "network") ? m[1] : "network";
85
159
  }
86
160
  export function createTeamAutoScheduler(deps) {
87
161
  const { logger, auth } = deps;
@@ -99,6 +173,7 @@ export function createTeamAutoScheduler(deps) {
99
173
  */
100
174
  function markWritebackFailure(store, entry, message, options = {}) {
101
175
  entry.error = message;
176
+ entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
102
177
  entry.attempts = (entry.attempts ?? 0) + 1;
103
178
  entry.lastErrorAt = Date.now();
104
179
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
@@ -176,6 +251,7 @@ export function createTeamAutoScheduler(deps) {
176
251
  let running = false;
177
252
  let store = null;
178
253
  let writebackTimer = null;
254
+ let claimRecoveryTimer = null;
179
255
  async function ensureStore() {
180
256
  if (!store) {
181
257
  store = await loadTeamAutoStore();
@@ -336,8 +412,35 @@ export function createTeamAutoScheduler(deps) {
336
412
  return "sweep already in progress";
337
413
  }
338
414
  sweeping.add(repo.id);
415
+ const sweepStartedAt = Date.now();
416
+ const etagBefore = client.etagStats();
339
417
  try {
340
- const { candidates, issues, pulls, newCommits, commits } = await sweepRepo(repo, client);
418
+ // #sweep-inplace: transient network failures retry IN PLACE (see
419
+ // SWEEP_INPLACE_RETRIES) - only a network blip that survives ~2.5min of
420
+ // retrying reaches the failure-recording path below.
421
+ let swept;
422
+ let lastNetworkErr;
423
+ for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
424
+ try {
425
+ swept = await sweepRepo(repo, client);
426
+ break;
427
+ }
428
+ catch (err) {
429
+ if (classifySweepError(err) !== "network") {
430
+ throw err;
431
+ }
432
+ lastNetworkErr = err;
433
+ const message0 = err instanceof Error ? err.message : String(err);
434
+ logger.warn(`TeamAuto: sweep ${repo.id} network error (attempt ${attempt}/${SWEEP_INPLACE_RETRIES}): ${message0}`);
435
+ if (attempt < SWEEP_INPLACE_RETRIES) {
436
+ await new Promise((resolve) => setTimeout(resolve, sweepInplaceDelayMs(attempt)));
437
+ }
438
+ }
439
+ }
440
+ if (!swept) {
441
+ throw lastNetworkErr;
442
+ }
443
+ const { candidates, issues, pulls, newCommits, commits } = swept;
341
444
  const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
342
445
  if (dryRun) {
343
446
  // One observing pass, then act. Flip unconditionally - flipping only
@@ -382,6 +485,7 @@ export function createTeamAutoScheduler(deps) {
382
485
  }
383
486
  else if (taskId) {
384
487
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
488
+ claimIssue(repo, candidate); // #268: visible claim at enqueue time
385
489
  const action = candidate.kind === "prReview"
386
490
  ? "prComment"
387
491
  : candidate.kind === "fullReview"
@@ -407,6 +511,8 @@ export function createTeamAutoScheduler(deps) {
407
511
  }
408
512
  repo.sweepFailures = 0;
409
513
  repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
514
+ const etagAfter = client.etagStats();
515
+ 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) });
410
516
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
411
517
  await saveTeamAutoStore(s);
412
518
  if (created > 0) {
@@ -426,8 +532,11 @@ export function createTeamAutoScheduler(deps) {
426
532
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
427
533
  repo.lastSweepErrorAt = Date.now();
428
534
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
429
- repo.pausedReason = `sweep failed: ${message}`;
430
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
535
+ const failClass = classifySweepError(err);
536
+ repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
537
+ const etagAfter = client.etagStats();
538
+ 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) });
539
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
431
540
  await saveTeamAutoStore(s).catch(() => { });
432
541
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
433
542
  return `error: ${message}`;
@@ -543,8 +652,68 @@ export function createTeamAutoScheduler(deps) {
543
652
  return "duplicate-active-skipped";
544
653
  }
545
654
  // ---------- write-back reconciler ----------
655
+ // #269: the 20s interval fires `void reconcileWritebacks()` fire-and-forget,
656
+ // and a slow delivery (worktree ensure + commit + PR > 20s) let the next
657
+ // tick re-read the same pending entries before doneAt landed - same
658
+ // comment delivered twice (ggcode#5480, byte-identical pair). Two-layer
659
+ // fix: serialize the whole pass (guard below) + intent-first inFlightAt
660
+ // persisted BEFORE dispatch so even a concurrent caller cannot re-send.
661
+ let reconcileInFlight = false;
546
662
  async function reconcileWritebacks() {
547
- const s = await ensureStore();
663
+ if (reconcileInFlight) {
664
+ return; // a pass is still delivering - never overlap (#269)
665
+ }
666
+ // #269 recurrence (23:40 CST): MULTIPLE gateway processes share one
667
+ // ~/.openclaw store (launchctl service + spawned gateways). In-process
668
+ // guards cannot see another process's deliveries - each kept its
669
+ // startup-cached store and delivered the same pending row (3s apart,
670
+ // two "issueComment ok" for one task). Cross-process mutex: an atomic
671
+ // mkdir lock dir next to the store file; stale (>5min) locks are
672
+ // taken over (crashed holder).
673
+ const { storeFile } = resolveTeamAutoPaths();
674
+ const lockDir = `${storeFile}.reconcile-lock`;
675
+ let locked = false;
676
+ try {
677
+ try {
678
+ await fs.mkdir(lockDir);
679
+ locked = true;
680
+ }
681
+ catch {
682
+ // Held - unless stale (holder crashed mid-pass).
683
+ try {
684
+ const st = await fs.stat(lockDir);
685
+ if (Date.now() - st.mtimeMs > 300_000) {
686
+ await fs.rm(lockDir, { recursive: true, force: true });
687
+ await fs.mkdir(lockDir);
688
+ locked = true;
689
+ }
690
+ }
691
+ catch { /* racing takeover - someone else won; skip this pass */ }
692
+ }
693
+ if (!locked) {
694
+ return; // another PROCESS is mid-reconcile; our next tick re-tries
695
+ }
696
+ reconcileInFlight = true;
697
+ try {
698
+ await doReconcileWritebacks();
699
+ }
700
+ finally {
701
+ reconcileInFlight = false;
702
+ }
703
+ }
704
+ finally {
705
+ if (locked) {
706
+ await fs.rm(lockDir, { recursive: true, force: true }).catch(() => { });
707
+ }
708
+ }
709
+ }
710
+ async function doReconcileWritebacks() {
711
+ // #269 recurrence: re-read the store from disk EVERY pass - the
712
+ // closure cache is a startup snapshot that never sees another
713
+ // process's persisted inFlightAt/doneAt, which is exactly how the
714
+ // 23:40 double delivery happened.
715
+ store = await loadTeamAutoStore();
716
+ const s = store;
548
717
  const state0 = deps.getTeamState();
549
718
  // Dead letters: entries whose task is gone or failed without a result can
550
719
  // never deliver - drop them instead of accumulating forever.
@@ -602,7 +771,30 @@ export function createTeamAutoScheduler(deps) {
602
771
  }
603
772
  }
604
773
  }
605
- const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
774
+ // #269: reset stale in-flight intents (crashed mid-dispatch) so they
775
+ // re-enter the pending set instead of wedging forever.
776
+ for (const w of s.writebacks) {
777
+ if (w.inFlightAt && !w.doneAt && Date.now() - w.inFlightAt > 600_000) {
778
+ w.inFlightAt = undefined;
779
+ }
780
+ }
781
+ const pendingAll = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt && !w.inFlightAt);
782
+ // #269 per-target dedupe (delivery side): cap at ONE entry per target
783
+ // key per pass, so N pending rows aimed at the same issue/PR cannot
784
+ // burst N same-second comments even if they somehow slipped the enqueue
785
+ // check (e.g. pre-fix stores). Deferred rows simply ride the next 20s
786
+ // pass. Null-target create* rows key on taskId: each is a distinct
787
+ // create intent and must never be merged.
788
+ const seenTarget = new Set();
789
+ const pending = [];
790
+ for (const w of pendingAll) {
791
+ const key = w.targetId != null ? `${w.action}|${w.repoId}|${w.targetId}` : `${w.action}|${w.taskId}`;
792
+ if (seenTarget.has(key)) {
793
+ continue;
794
+ }
795
+ seenTarget.add(key);
796
+ pending.push(w);
797
+ }
606
798
  if (!pending.length) {
607
799
  return;
608
800
  }
@@ -611,6 +803,11 @@ export function createTeamAutoScheduler(deps) {
611
803
  return;
612
804
  }
613
805
  for (const entry of pending) {
806
+ // #269 intent-first: persist the dispatch intent BEFORE any await so
807
+ // an overlapping pass (or a future guard-less caller) filters this
808
+ // entry out instead of re-delivering it.
809
+ entry.inFlightAt = Date.now();
810
+ await saveTeamAutoStore(s);
614
811
  const task = state.tasks[entry.taskId];
615
812
  if (!task || (task.status !== "completed" && task.status !== "failed")) {
616
813
  continue;
@@ -649,6 +846,7 @@ export function createTeamAutoScheduler(deps) {
649
846
  // push its branch, open a PR, and attach the link to the reply.
650
847
  const repoId = entry.repoId;
651
848
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
849
+ let prDeliveryFailed = false;
652
850
  if (isTeamAutoWrite) {
653
851
  try {
654
852
  const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
@@ -670,11 +868,24 @@ export function createTeamAutoScheduler(deps) {
670
868
  }
671
869
  catch (prErr) {
672
870
  markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
871
+ // #269 4th recurrence (ggcode#5524): a failed PR step must abort
872
+ // the WHOLE entry this pass. The old fall-through posted the
873
+ // link-less comment anyway, set doneAt, and the #24 cleanup
874
+ // cleared the error - a partial delivery masked as success.
875
+ // The retry pass then delivered the WITH-link comment too:
876
+ // two comments 2s apart. Fail atomically instead: the entry
877
+ // keeps its failed state + backoff and replays BOTH steps
878
+ // (PR first, then comment) on the next attempt.
879
+ prDeliveryFailed = true;
673
880
  }
674
881
  }
882
+ if (prDeliveryFailed) {
883
+ continue;
884
+ }
675
885
  if (entry.action === "issueComment" && entry.targetId) {
676
886
  await client.postIssueComment(owner, name, entry.targetId, body);
677
887
  entry.doneAt = Date.now();
888
+ entry.inFlightAt = undefined;
678
889
  writebackDone = true;
679
890
  // Our own comment bumps the issue's updatedAt, which the scanner
680
891
  // treats as new activity - advance the seen cursor so we do not
@@ -688,6 +899,7 @@ export function createTeamAutoScheduler(deps) {
688
899
  else if (entry.action === "prComment" && entry.targetId) {
689
900
  await client.postPullReviewComment(owner, name, entry.targetId, body);
690
901
  entry.doneAt = Date.now();
902
+ entry.inFlightAt = undefined;
691
903
  writebackDone = true;
692
904
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
693
905
  if (prRepo) {
@@ -705,12 +917,14 @@ export function createTeamAutoScheduler(deps) {
705
917
  await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
706
918
  entry.targetId = umbrella.targetId;
707
919
  entry.doneAt = Date.now();
920
+ entry.inFlightAt = undefined;
708
921
  writebackDone = true;
709
922
  }
710
923
  else if (entry.targetId == null) {
711
924
  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"]);
712
925
  entry.targetId = number;
713
926
  entry.doneAt = Date.now();
927
+ entry.inFlightAt = undefined;
714
928
  writebackDone = true;
715
929
  }
716
930
  }
@@ -718,6 +932,7 @@ export function createTeamAutoScheduler(deps) {
718
932
  const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
719
933
  entry.targetId = number;
720
934
  entry.doneAt = Date.now();
935
+ entry.inFlightAt = undefined;
721
936
  writebackDone = true;
722
937
  }
723
938
  }
@@ -748,10 +963,129 @@ export function createTeamAutoScheduler(deps) {
748
963
  if (s.writebacks.some((w) => w.taskId === taskId)) {
749
964
  return;
750
965
  }
966
+ // #269 per-target dedupe (enqueue side): a second registration for
967
+ // the SAME target + action with no doneAt yet is a duplicate in the
968
+ // making - the delivery pass would fan out two comments onto one
969
+ // target. Skip it; the pending original still delivers the content.
970
+ // targetId null (create* actions) cannot be target-deduped pre-delivery
971
+ // and is excluded by the taskId check above.
972
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
973
+ return;
974
+ }
751
975
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
752
976
  void saveTeamAutoStore(s);
753
977
  }).catch(() => { });
754
978
  }
979
+ /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
980
+ * assignIssue was dead code and registerWriteback had no assign action, so
981
+ * claims existed only in internal state - humans could not see the bot had
982
+ * picked an issue up (collision risk), contradicting the design decision
983
+ * that identity presents as the logged-in account's activity.
984
+ * Fired at ENQUEUE time: a claim is a placeholder declaration; posting it
985
+ * at completion would leave the whole execution window claim-invisible.
986
+ * Best-effort, never blocks the task. Review notes (#268):
987
+ * (a) re-check assignees at claim time (the scan snapshot is seconds
988
+ * stale - a human may have self-assigned in between);
989
+ * (b) stamp cursors.seen with NOW + 60s on BOTH success paths (assign
990
+ * AND fallback comment) because our own write bumps the issue's
991
+ * updated_at - a bare-assign stamp would lose the scanner's
992
+ * `seen >= updatedAt` comparison next sweep and re-candidate the
993
+ * issue we just claimed (self-triggering loop). */
994
+ function claimIssue(repo, candidate) {
995
+ if (candidate.kind !== "takeOwnership" || !candidate.number) {
996
+ return;
997
+ }
998
+ void (async () => {
999
+ const [owner, name] = repo.id.split("/");
1000
+ const client = createGithubClient(auth);
1001
+ try {
1002
+ const fresh = await client.getIssue(owner, name, candidate.number);
1003
+ if (fresh.state !== "open") {
1004
+ return;
1005
+ }
1006
+ if (repo.policy.skipAssignedToHumans && fresh.assignees.length > 0) {
1007
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claim skipped: issue #${candidate.number} gained an assignee since scan` });
1008
+ return;
1009
+ }
1010
+ const { login } = await client.getAuthenticatedUser();
1011
+ try {
1012
+ await client.assignIssue(owner, name, candidate.number, login);
1013
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
1014
+ }
1015
+ catch {
1016
+ // Fallback: a visible claim comment carries the same placeholder
1017
+ // semantics when the App lacks the assignees write surface.
1018
+ 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.`);
1019
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1020
+ }
1021
+ const s = await ensureStore();
1022
+ const freshRepo = s.repos.find((r) => r.id === repo.id);
1023
+ if (freshRepo) {
1024
+ // +60s guard: our own write (assign or comment) bumps updated_at;
1025
+ // see helper doc.
1026
+ freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1027
+ await saveTeamAutoStore(s);
1028
+ }
1029
+ }
1030
+ catch (err) {
1031
+ logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1032
+ }
1033
+ })();
1034
+ }
1035
+ /** #claim-recovery: a task that CLAIMED an issue (takeOwnership stamps the
1036
+ * seen cursor AND self-assigns the bot at enqueue time; issueReview stamps
1037
+ * the cursor) locks the issue twice against re-candidacy. When the task
1038
+ * fails, the issue must not be orphaned - nobody (human or bot) would ever
1039
+ * pick it up again. Once per failed taskId: clear the seen stamp so the
1040
+ * next sweep re-candidates naturally, and for takeOwnership remove the
1041
+ * bot's own assignment (human assignees untouched). The existing
1042
+ * dead-letter caps (3 hard / 6 transient) bound how often this can loop. */
1043
+ async function recoverFailedClaims() {
1044
+ const teamState = deps.getTeamState();
1045
+ if (!teamState) {
1046
+ return;
1047
+ }
1048
+ const s = await ensureStore();
1049
+ s.failedClaimRecovery ??= {};
1050
+ let changed = false;
1051
+ for (const [taskId, task] of Object.entries(teamState.tasks ?? {})) {
1052
+ if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1053
+ continue;
1054
+ }
1055
+ if (s.failedClaimRecovery[taskId]) {
1056
+ continue;
1057
+ }
1058
+ const parsed = parseClaimMarker(task.description);
1059
+ const repo = parsed ? s.repos.find((r) => r.id === parsed.repoId) : undefined;
1060
+ if (!parsed || !repo) {
1061
+ continue;
1062
+ }
1063
+ delete repo.cursors.seen[parsed.key];
1064
+ s.failedClaimRecovery[taskId] = Date.now();
1065
+ changed = true;
1066
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `recovered failed task ${taskId}: issue #${parsed.number} re-opened for the next sweep` });
1067
+ if (parsed.kind === "takeOwnership") {
1068
+ void (async () => {
1069
+ try {
1070
+ const client = createGithubClient(auth);
1071
+ const { login } = await client.getAuthenticatedUser();
1072
+ const [owner, name] = repo.id.split("/");
1073
+ await client.removeIssueAssignees(owner, name, parsed.number, [login]);
1074
+ }
1075
+ catch (err) {
1076
+ 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)}`);
1077
+ }
1078
+ })();
1079
+ }
1080
+ }
1081
+ if (changed) {
1082
+ const entries = Object.entries(s.failedClaimRecovery).sort((a, b) => a[1] - b[1]);
1083
+ if (entries.length > 200) {
1084
+ s.failedClaimRecovery = Object.fromEntries(entries.slice(entries.length - 200));
1085
+ }
1086
+ await saveTeamAutoStore(s);
1087
+ }
1088
+ }
755
1089
  // ---------- scheduling loop ----------
756
1090
  function scheduleRepo(repo) {
757
1091
  const previous = timers.get(repo.id);
@@ -763,12 +1097,22 @@ export function createTeamAutoScheduler(deps) {
763
1097
  return;
764
1098
  }
765
1099
  let delay;
766
- try {
767
- delay = nextFireMs(repo.schedule);
1100
+ // Auto-paused repos arm the RETRY ladder, not the regular schedule: the
1101
+ // retry-due check used to ride the next regular tick, so "auto-retry in
1102
+ // ~1min" for a network blip really meant "at the next hourly tick".
1103
+ // While paused, retry at the class-aware backoff; a successful sweep
1104
+ // clears pausedReason and restores the regular schedule below.
1105
+ if (isAutoPause(repo.pausedReason) && repo.lastSweepErrorAt) {
1106
+ delay = Math.max(SWEEP_RETRY_FLOOR_MS, sweepRetryDueAt(repo.sweepFailures ?? 1, repo.lastSweepErrorAt, failClassFromPauseReason(repo.pausedReason)) - Date.now());
768
1107
  }
769
- catch (err) {
770
- logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
771
- return;
1108
+ else {
1109
+ try {
1110
+ delay = nextFireMs(repo.schedule);
1111
+ }
1112
+ catch (err) {
1113
+ logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
1114
+ return;
1115
+ }
772
1116
  }
773
1117
  const timer = setTimeout(() => {
774
1118
  void (async () => {
@@ -776,7 +1120,7 @@ export function createTeamAutoScheduler(deps) {
776
1120
  const s = await ensureStore();
777
1121
  const fresh = s.repos.find((r) => r.id === repo.id);
778
1122
  const retryDue = fresh
779
- ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
1123
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0, failClassFromPauseReason(fresh.pausedReason))
780
1124
  : false;
781
1125
  if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
782
1126
  await runSweep(fresh, false);
@@ -822,6 +1166,10 @@ export function createTeamAutoScheduler(deps) {
822
1166
  void reconcileWritebacks();
823
1167
  }, 20_000);
824
1168
  writebackTimer.unref?.();
1169
+ claimRecoveryTimer = setInterval(() => {
1170
+ void recoverFailedClaims();
1171
+ }, 60_000);
1172
+ claimRecoveryTimer.unref?.();
825
1173
  // Boot reconciliation: heal leftover task worktrees whose task is
826
1174
  // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
827
1175
  // on its own. Safety-checked: undelivered work is kept and logged.
@@ -885,6 +1233,9 @@ export function createTeamAutoScheduler(deps) {
885
1233
  timers.clear();
886
1234
  if (writebackTimer) {
887
1235
  clearInterval(writebackTimer);
1236
+ if (claimRecoveryTimer) {
1237
+ clearInterval(claimRecoveryTimer);
1238
+ }
888
1239
  writebackTimer = null;
889
1240
  }
890
1241
  }
@@ -16,6 +16,15 @@ export function pushTeamAutoActivity(store, entry) {
16
16
  store.activity = store.activity.slice(store.activity.length - TEAMAUTO_ACTIVITY_LIMIT);
17
17
  }
18
18
  }
19
+ /** #267-2: bounded per-repo sweep ring (newest last, cap 20) - same slice
20
+ * pattern as pushTeamAutoActivity. */
21
+ export function pushSweepRecord(repo, entry) {
22
+ repo.sweeps = repo.sweeps ?? [];
23
+ repo.sweeps.push(entry);
24
+ if (repo.sweeps.length > 20) {
25
+ repo.sweeps = repo.sweeps.slice(repo.sweeps.length - 20);
26
+ }
27
+ }
19
28
  export function defaultPolicy() {
20
29
  return {
21
30
  maxTasksPerSweep: 5,
@@ -35,6 +44,7 @@ function emptyStore() {
35
44
  repos: [],
36
45
  writebacks: [],
37
46
  activity: [],
47
+ failedClaimRecovery: {},
38
48
  budget: {
39
49
  maxTasksPerDay: 150,
40
50
  firstSweepDryRun: true,
@@ -92,6 +102,9 @@ export async function loadTeamAutoStore() {
92
102
  if (Array.isArray(parsed.activity)) {
93
103
  store.activity = parsed.activity.slice(-TEAMAUTO_ACTIVITY_LIMIT);
94
104
  }
105
+ if (parsed.failedClaimRecovery && typeof parsed.failedClaimRecovery === "object") {
106
+ store.failedClaimRecovery = parsed.failedClaimRecovery;
107
+ }
95
108
  store.budget = { ...store.budget, ...(parsed.budget ?? {}) };
96
109
  return store;
97
110
  }