@teamclaws/teamclaw 2026.11.1 → 2026.11.3

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 (45) hide show
  1. package/cli.mjs +96 -11
  2. package/dist/index.js +7 -0
  3. package/dist/src/controller/config-routes.js +138 -0
  4. package/dist/src/controller/http-server.js +18 -0
  5. package/dist/src/controller/journal.js +68 -0
  6. package/dist/src/controller/provisioning/process-supervisor.js +58 -2
  7. package/dist/src/controller/provisioning-config.js +53 -0
  8. package/dist/src/controller/route-table.js +11 -0
  9. package/dist/src/controller/security.js +39 -0
  10. package/dist/src/controller/teamauto-routes.js +12 -0
  11. package/dist/src/controller/tunnel-manager.js +33 -1
  12. package/dist/src/controller/tunnel-routes.js +17 -1
  13. package/dist/src/controller/websocket.js +4 -0
  14. package/dist/src/controller/worker-provisioning.js +36 -0
  15. package/dist/src/openclaw-workspace.js +36 -0
  16. package/dist/src/state.js +77 -1
  17. package/dist/src/teamauto/github-client.js +33 -0
  18. package/dist/src/teamauto/scanner.js +30 -3
  19. package/dist/src/teamauto/scheduler.js +300 -18
  20. package/dist/src/teamauto/store.js +9 -0
  21. package/dist/src/ui/app.js +188 -11
  22. package/dist/src/ui/index.html +38 -0
  23. package/index.ts +8 -0
  24. package/openclaw.plugin.json +1 -1
  25. package/package.json +1 -1
  26. package/src/controller/config-routes.ts +152 -0
  27. package/src/controller/http-server.ts +18 -0
  28. package/src/controller/journal.ts +89 -0
  29. package/src/controller/provisioning/process-supervisor.ts +56 -2
  30. package/src/controller/provisioning-config.ts +54 -0
  31. package/src/controller/route-table.ts +11 -0
  32. package/src/controller/security.ts +40 -0
  33. package/src/controller/teamauto-routes.ts +12 -0
  34. package/src/controller/tunnel-manager.ts +34 -1
  35. package/src/controller/tunnel-routes.ts +18 -1
  36. package/src/controller/websocket.ts +6 -0
  37. package/src/controller/worker-provisioning.ts +34 -0
  38. package/src/openclaw-workspace.ts +47 -0
  39. package/src/state.ts +73 -2
  40. package/src/teamauto/github-client.ts +36 -0
  41. package/src/teamauto/scanner.ts +31 -4
  42. package/src/teamauto/scheduler.ts +303 -18
  43. package/src/teamauto/store.ts +36 -1
  44. package/src/ui/app.js +188 -11
  45. package/src/ui/index.html +38 -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):
@@ -47,15 +49,49 @@ export function hardAttemptCount(state, candidate) {
47
49
  const marker = idempotencyMarker(candidate);
48
50
  return Object.values(state.tasks).filter((t) => t.description.includes(marker) && t.status === "failed" && !(t.error && TRANSIENT_FAILURE_RE.test(t.error))).length;
49
51
  }
50
- /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
52
+ /** Auto-pause retry backoff for classes where a fast retry is useless or
53
+ * harmful: 30m after the 1st failure, doubling, capped at 4h. auth needs a
54
+ * human re-login; ratelimited retried early just re-triggers the limit. */
51
55
  export const SWEEP_RETRY_BASE_MINUTES = 30;
52
56
  export const SWEEP_RETRY_MAX_MINUTES = 240;
53
57
  export function sweepBackoffMinutes(failures) {
54
58
  return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
55
59
  }
60
+ /** Sweep-timeout report: a transient "fetch failed" sat a full 30m before
61
+ * its first retry - a seconds-long network blip cost half an hour of repo
62
+ * idle time. Network-class failures get a fast ladder: 1m, 2m, 4m... capped
63
+ * at 15m. The cap means a genuinely-down network converges to one attempt
64
+ * per 15m (slower than the old ladder's first step, so we never hammer),
65
+ * but a single blip costs one minute instead of thirty. */
66
+ export const SWEEP_NETWORK_RETRY_BASE_MINUTES = 1;
67
+ export const SWEEP_NETWORK_RETRY_MAX_MINUTES = 15;
68
+ export function sweepNetworkBackoffMinutes(failures) {
69
+ return Math.min(SWEEP_NETWORK_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_NETWORK_RETRY_MAX_MINUTES);
70
+ }
71
+ /** Class-aware dispatch: the retry ladder a failure class deserves. */
72
+ export function sweepBackoffMinutesFor(failClass, failures) {
73
+ return failClass === "network" ? sweepNetworkBackoffMinutes(failures) : sweepBackoffMinutes(failures);
74
+ }
75
+ /** Timer floor when arming the retry ladder: a just-missed due time must not
76
+ * fire at 0ms (tight failure/retry loop protection). */
77
+ export const SWEEP_RETRY_FLOOR_MS = 5_000;
56
78
  /** 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;
79
+ export function sweepRetryDueAt(failures, lastErrorAt, failClass = "network") {
80
+ return lastErrorAt + sweepBackoffMinutesFor(failClass, failures) * 60_000;
81
+ }
82
+ /** In-place network retries: a transient "fetch failed"/"terminated" is
83
+ * retried immediately INSIDE the sweep invocation (user report 2026-11-14:
84
+ * "sweep failed[network] (auto-retry in ~30min): fetch failed" - the repo
85
+ * idled half an hour on a blip that a 5s retry would have survived). 10
86
+ * attempts with a 3s..30s delay ladder (~2.5min worst case) before the
87
+ * failure is recorded and the pause/backoff path takes over. Non-network
88
+ * classes (auth, ratelimited) never retry in place - retrying is useless
89
+ * or harmful. */
90
+ export const SWEEP_INPLACE_RETRIES = 10;
91
+ export const SWEEP_INPLACE_DELAY_BASE_MS = 3_000;
92
+ export const SWEEP_INPLACE_DELAY_MAX_MS = 30_000;
93
+ export function sweepInplaceDelayMs(attempt) {
94
+ return Math.min(SWEEP_INPLACE_DELAY_BASE_MS * 2 ** Math.max(0, attempt - 1), SWEEP_INPLACE_DELAY_MAX_MS);
59
95
  }
60
96
  /**
61
97
  * Issue #24: max write-back delivery attempts before the entry is marked
@@ -79,9 +115,33 @@ export function writebackBackoffMs(attempts) {
79
115
  export function writebackRetryDueAt(attempts, lastErrorAt) {
80
116
  return lastErrorAt + writebackBackoffMs(attempts);
81
117
  }
82
- /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
118
+ export function classifySweepError(err) {
119
+ const cause = err?.cause ?? err;
120
+ const status = Number(cause?.status ?? 0);
121
+ if (status === 401)
122
+ return "auth";
123
+ if (status === 403 || status === 429)
124
+ return "ratelimited";
125
+ return "network";
126
+ }
127
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not.
128
+ * Accept BOTH the legacy prefix ("sweep failed: ...") and the #267 classified
129
+ * format ("sweep failed[network]: ...") - the classified format broke the old
130
+ * startsWith("sweep failed:") check, so successful sweeps could never clear
131
+ * the pause and the retry timer never re-armed (all four repos stuck paused
132
+ * after the 12:30 restart-window failures; found 2026-11-12). */
83
133
  export function isAutoPause(reason) {
84
- return !!reason && reason.startsWith("sweep failed:");
134
+ if (!reason)
135
+ return false;
136
+ return /^sweep failed(\[[^\]]*\])?:/.test(reason);
137
+ }
138
+ /** Recover the fail class from a persisted auto-pause reason
139
+ * ("sweep failed[network]: ..."). Legacy/unparsable reasons default to the
140
+ * fast network ladder - a wrong guess only retries sooner, and the ladder
141
+ * itself still caps the attempt rate, so the default is safe. */
142
+ export function failClassFromPauseReason(reason) {
143
+ const m = reason?.match(/^sweep failed\[([^\]]*)\]/);
144
+ return m && (m[1] === "auth" || m[1] === "ratelimited" || m[1] === "network") ? m[1] : "network";
85
145
  }
86
146
  export function createTeamAutoScheduler(deps) {
87
147
  const { logger, auth } = deps;
@@ -99,6 +159,7 @@ export function createTeamAutoScheduler(deps) {
99
159
  */
100
160
  function markWritebackFailure(store, entry, message, options = {}) {
101
161
  entry.error = message;
162
+ entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
102
163
  entry.attempts = (entry.attempts ?? 0) + 1;
103
164
  entry.lastErrorAt = Date.now();
104
165
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
@@ -336,8 +397,35 @@ export function createTeamAutoScheduler(deps) {
336
397
  return "sweep already in progress";
337
398
  }
338
399
  sweeping.add(repo.id);
400
+ const sweepStartedAt = Date.now();
401
+ const etagBefore = client.etagStats();
339
402
  try {
340
- const { candidates, issues, pulls } = await sweepRepo(repo, client);
403
+ // #sweep-inplace: transient network failures retry IN PLACE (see
404
+ // SWEEP_INPLACE_RETRIES) - only a network blip that survives ~2.5min of
405
+ // retrying reaches the failure-recording path below.
406
+ let swept;
407
+ let lastNetworkErr;
408
+ for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
409
+ try {
410
+ swept = await sweepRepo(repo, client);
411
+ break;
412
+ }
413
+ catch (err) {
414
+ if (classifySweepError(err) !== "network") {
415
+ throw err;
416
+ }
417
+ lastNetworkErr = err;
418
+ const message0 = err instanceof Error ? err.message : String(err);
419
+ logger.warn(`TeamAuto: sweep ${repo.id} network error (attempt ${attempt}/${SWEEP_INPLACE_RETRIES}): ${message0}`);
420
+ if (attempt < SWEEP_INPLACE_RETRIES) {
421
+ await new Promise((resolve) => setTimeout(resolve, sweepInplaceDelayMs(attempt)));
422
+ }
423
+ }
424
+ }
425
+ if (!swept) {
426
+ throw lastNetworkErr;
427
+ }
428
+ const { candidates, issues, pulls, newCommits, commits } = swept;
341
429
  const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
342
430
  if (dryRun) {
343
431
  // One observing pass, then act. Flip unconditionally - flipping only
@@ -350,7 +438,7 @@ export function createTeamAutoScheduler(deps) {
350
438
  // Advance only for acting sweeps: a dry-run must leave the cursors
351
439
  // untouched so the reported actions are actually performed next time
352
440
  // instead of being marked as already-seen.
353
- advanceCursors(repo, issues, pulls);
441
+ advanceCursors(repo, issues, pulls, Date.now(), commits);
354
442
  }
355
443
  // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
356
444
  // pull candidates, so a busy repo would otherwise starve them forever
@@ -361,6 +449,11 @@ export function createTeamAutoScheduler(deps) {
361
449
  const capped = [...fullReviews, ...regular];
362
450
  let created = 0;
363
451
  const summary = [`found ${candidates.length} candidate(s)`];
452
+ // #265: surface the commits delta so the third signal source is
453
+ // observable in sweep summaries (was silently dead before).
454
+ if (newCommits.length > 0) {
455
+ summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
456
+ }
364
457
  if (capped.length && dryRun) {
365
458
  summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
366
459
  repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
@@ -377,6 +470,7 @@ export function createTeamAutoScheduler(deps) {
377
470
  }
378
471
  else if (taskId) {
379
472
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
473
+ claimIssue(repo, candidate); // #268: visible claim at enqueue time
380
474
  const action = candidate.kind === "prReview"
381
475
  ? "prComment"
382
476
  : candidate.kind === "fullReview"
@@ -401,6 +495,9 @@ export function createTeamAutoScheduler(deps) {
401
495
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
402
496
  }
403
497
  repo.sweepFailures = 0;
498
+ repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
499
+ const etagAfter = client.etagStats();
500
+ 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) });
404
501
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
405
502
  await saveTeamAutoStore(s);
406
503
  if (created > 0) {
@@ -419,8 +516,12 @@ export function createTeamAutoScheduler(deps) {
419
516
  // backoff below, and a success clears the state in the block above.
420
517
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
421
518
  repo.lastSweepErrorAt = Date.now();
422
- repo.pausedReason = `sweep failed: ${message}`;
423
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
519
+ repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
520
+ const failClass = classifySweepError(err);
521
+ repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
522
+ const etagAfter = client.etagStats();
523
+ 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) });
524
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
424
525
  await saveTeamAutoStore(s).catch(() => { });
425
526
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
426
527
  return `error: ${message}`;
@@ -536,8 +637,68 @@ export function createTeamAutoScheduler(deps) {
536
637
  return "duplicate-active-skipped";
537
638
  }
538
639
  // ---------- write-back reconciler ----------
640
+ // #269: the 20s interval fires `void reconcileWritebacks()` fire-and-forget,
641
+ // and a slow delivery (worktree ensure + commit + PR > 20s) let the next
642
+ // tick re-read the same pending entries before doneAt landed - same
643
+ // comment delivered twice (ggcode#5480, byte-identical pair). Two-layer
644
+ // fix: serialize the whole pass (guard below) + intent-first inFlightAt
645
+ // persisted BEFORE dispatch so even a concurrent caller cannot re-send.
646
+ let reconcileInFlight = false;
539
647
  async function reconcileWritebacks() {
540
- const s = await ensureStore();
648
+ if (reconcileInFlight) {
649
+ return; // a pass is still delivering - never overlap (#269)
650
+ }
651
+ // #269 recurrence (23:40 CST): MULTIPLE gateway processes share one
652
+ // ~/.openclaw store (launchctl service + spawned gateways). In-process
653
+ // guards cannot see another process's deliveries - each kept its
654
+ // startup-cached store and delivered the same pending row (3s apart,
655
+ // two "issueComment ok" for one task). Cross-process mutex: an atomic
656
+ // mkdir lock dir next to the store file; stale (>5min) locks are
657
+ // taken over (crashed holder).
658
+ const { storeFile } = resolveTeamAutoPaths();
659
+ const lockDir = `${storeFile}.reconcile-lock`;
660
+ let locked = false;
661
+ try {
662
+ try {
663
+ await fs.mkdir(lockDir);
664
+ locked = true;
665
+ }
666
+ catch {
667
+ // Held - unless stale (holder crashed mid-pass).
668
+ try {
669
+ const st = await fs.stat(lockDir);
670
+ if (Date.now() - st.mtimeMs > 300_000) {
671
+ await fs.rm(lockDir, { recursive: true, force: true });
672
+ await fs.mkdir(lockDir);
673
+ locked = true;
674
+ }
675
+ }
676
+ catch { /* racing takeover - someone else won; skip this pass */ }
677
+ }
678
+ if (!locked) {
679
+ return; // another PROCESS is mid-reconcile; our next tick re-tries
680
+ }
681
+ reconcileInFlight = true;
682
+ try {
683
+ await doReconcileWritebacks();
684
+ }
685
+ finally {
686
+ reconcileInFlight = false;
687
+ }
688
+ }
689
+ finally {
690
+ if (locked) {
691
+ await fs.rm(lockDir, { recursive: true, force: true }).catch(() => { });
692
+ }
693
+ }
694
+ }
695
+ async function doReconcileWritebacks() {
696
+ // #269 recurrence: re-read the store from disk EVERY pass - the
697
+ // closure cache is a startup snapshot that never sees another
698
+ // process's persisted inFlightAt/doneAt, which is exactly how the
699
+ // 23:40 double delivery happened.
700
+ store = await loadTeamAutoStore();
701
+ const s = store;
541
702
  const state0 = deps.getTeamState();
542
703
  // Dead letters: entries whose task is gone or failed without a result can
543
704
  // never deliver - drop them instead of accumulating forever.
@@ -595,7 +756,30 @@ export function createTeamAutoScheduler(deps) {
595
756
  }
596
757
  }
597
758
  }
598
- const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
759
+ // #269: reset stale in-flight intents (crashed mid-dispatch) so they
760
+ // re-enter the pending set instead of wedging forever.
761
+ for (const w of s.writebacks) {
762
+ if (w.inFlightAt && !w.doneAt && Date.now() - w.inFlightAt > 600_000) {
763
+ w.inFlightAt = undefined;
764
+ }
765
+ }
766
+ const pendingAll = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt && !w.inFlightAt);
767
+ // #269 per-target dedupe (delivery side): cap at ONE entry per target
768
+ // key per pass, so N pending rows aimed at the same issue/PR cannot
769
+ // burst N same-second comments even if they somehow slipped the enqueue
770
+ // check (e.g. pre-fix stores). Deferred rows simply ride the next 20s
771
+ // pass. Null-target create* rows key on taskId: each is a distinct
772
+ // create intent and must never be merged.
773
+ const seenTarget = new Set();
774
+ const pending = [];
775
+ for (const w of pendingAll) {
776
+ const key = w.targetId != null ? `${w.action}|${w.repoId}|${w.targetId}` : `${w.action}|${w.taskId}`;
777
+ if (seenTarget.has(key)) {
778
+ continue;
779
+ }
780
+ seenTarget.add(key);
781
+ pending.push(w);
782
+ }
599
783
  if (!pending.length) {
600
784
  return;
601
785
  }
@@ -604,6 +788,11 @@ export function createTeamAutoScheduler(deps) {
604
788
  return;
605
789
  }
606
790
  for (const entry of pending) {
791
+ // #269 intent-first: persist the dispatch intent BEFORE any await so
792
+ // an overlapping pass (or a future guard-less caller) filters this
793
+ // entry out instead of re-delivering it.
794
+ entry.inFlightAt = Date.now();
795
+ await saveTeamAutoStore(s);
607
796
  const task = state.tasks[entry.taskId];
608
797
  if (!task || (task.status !== "completed" && task.status !== "failed")) {
609
798
  continue;
@@ -642,6 +831,7 @@ export function createTeamAutoScheduler(deps) {
642
831
  // push its branch, open a PR, and attach the link to the reply.
643
832
  const repoId = entry.repoId;
644
833
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
834
+ let prDeliveryFailed = false;
645
835
  if (isTeamAutoWrite) {
646
836
  try {
647
837
  const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
@@ -663,11 +853,24 @@ export function createTeamAutoScheduler(deps) {
663
853
  }
664
854
  catch (prErr) {
665
855
  markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
856
+ // #269 4th recurrence (ggcode#5524): a failed PR step must abort
857
+ // the WHOLE entry this pass. The old fall-through posted the
858
+ // link-less comment anyway, set doneAt, and the #24 cleanup
859
+ // cleared the error - a partial delivery masked as success.
860
+ // The retry pass then delivered the WITH-link comment too:
861
+ // two comments 2s apart. Fail atomically instead: the entry
862
+ // keeps its failed state + backoff and replays BOTH steps
863
+ // (PR first, then comment) on the next attempt.
864
+ prDeliveryFailed = true;
666
865
  }
667
866
  }
867
+ if (prDeliveryFailed) {
868
+ continue;
869
+ }
668
870
  if (entry.action === "issueComment" && entry.targetId) {
669
871
  await client.postIssueComment(owner, name, entry.targetId, body);
670
872
  entry.doneAt = Date.now();
873
+ entry.inFlightAt = undefined;
671
874
  writebackDone = true;
672
875
  // Our own comment bumps the issue's updatedAt, which the scanner
673
876
  // treats as new activity - advance the seen cursor so we do not
@@ -681,6 +884,7 @@ export function createTeamAutoScheduler(deps) {
681
884
  else if (entry.action === "prComment" && entry.targetId) {
682
885
  await client.postPullReviewComment(owner, name, entry.targetId, body);
683
886
  entry.doneAt = Date.now();
887
+ entry.inFlightAt = undefined;
684
888
  writebackDone = true;
685
889
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
686
890
  if (prRepo) {
@@ -698,12 +902,14 @@ export function createTeamAutoScheduler(deps) {
698
902
  await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
699
903
  entry.targetId = umbrella.targetId;
700
904
  entry.doneAt = Date.now();
905
+ entry.inFlightAt = undefined;
701
906
  writebackDone = true;
702
907
  }
703
908
  else if (entry.targetId == null) {
704
909
  const number = await client.createIssue(owner, name, `[teamclaw:fullreview] Joint full review - ${entry.repoId}`, `Joint multi-role full review (cycle ${entry.cycleKey}). Each role appends its section as a comment below.\n\n${sectionBody}`, ["teamclaw", "teamclaw:fullreview"]);
705
910
  entry.targetId = number;
706
911
  entry.doneAt = Date.now();
912
+ entry.inFlightAt = undefined;
707
913
  writebackDone = true;
708
914
  }
709
915
  }
@@ -711,6 +917,7 @@ export function createTeamAutoScheduler(deps) {
711
917
  const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
712
918
  entry.targetId = number;
713
919
  entry.doneAt = Date.now();
920
+ entry.inFlightAt = undefined;
714
921
  writebackDone = true;
715
922
  }
716
923
  }
@@ -741,10 +948,75 @@ export function createTeamAutoScheduler(deps) {
741
948
  if (s.writebacks.some((w) => w.taskId === taskId)) {
742
949
  return;
743
950
  }
951
+ // #269 per-target dedupe (enqueue side): a second registration for
952
+ // the SAME target + action with no doneAt yet is a duplicate in the
953
+ // making - the delivery pass would fan out two comments onto one
954
+ // target. Skip it; the pending original still delivers the content.
955
+ // targetId null (create* actions) cannot be target-deduped pre-delivery
956
+ // and is excluded by the taskId check above.
957
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
958
+ return;
959
+ }
744
960
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
745
961
  void saveTeamAutoStore(s);
746
962
  }).catch(() => { });
747
963
  }
964
+ /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
965
+ * assignIssue was dead code and registerWriteback had no assign action, so
966
+ * claims existed only in internal state - humans could not see the bot had
967
+ * picked an issue up (collision risk), contradicting the design decision
968
+ * that identity presents as the logged-in account's activity.
969
+ * Fired at ENQUEUE time: a claim is a placeholder declaration; posting it
970
+ * at completion would leave the whole execution window claim-invisible.
971
+ * Best-effort, never blocks the task. Review notes (#268):
972
+ * (a) re-check assignees at claim time (the scan snapshot is seconds
973
+ * stale - a human may have self-assigned in between);
974
+ * (b) stamp cursors.seen with NOW + 60s on BOTH success paths (assign
975
+ * AND fallback comment) because our own write bumps the issue's
976
+ * updated_at - a bare-assign stamp would lose the scanner's
977
+ * `seen >= updatedAt` comparison next sweep and re-candidate the
978
+ * issue we just claimed (self-triggering loop). */
979
+ function claimIssue(repo, candidate) {
980
+ if (candidate.kind !== "takeOwnership" || !candidate.number) {
981
+ return;
982
+ }
983
+ void (async () => {
984
+ const [owner, name] = repo.id.split("/");
985
+ const client = createGithubClient(auth);
986
+ try {
987
+ const fresh = await client.getIssue(owner, name, candidate.number);
988
+ if (fresh.state !== "open") {
989
+ return;
990
+ }
991
+ if (repo.policy.skipAssignedToHumans && fresh.assignees.length > 0) {
992
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claim skipped: issue #${candidate.number} gained an assignee since scan` });
993
+ return;
994
+ }
995
+ const { login } = await client.getAuthenticatedUser();
996
+ try {
997
+ await client.assignIssue(owner, name, candidate.number, login);
998
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
999
+ }
1000
+ catch {
1001
+ // Fallback: a visible claim comment carries the same placeholder
1002
+ // semantics when the App lacks the assignees write surface.
1003
+ 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.`);
1004
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1005
+ }
1006
+ const s = await ensureStore();
1007
+ const freshRepo = s.repos.find((r) => r.id === repo.id);
1008
+ if (freshRepo) {
1009
+ // +60s guard: our own write (assign or comment) bumps updated_at;
1010
+ // see helper doc.
1011
+ freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1012
+ await saveTeamAutoStore(s);
1013
+ }
1014
+ }
1015
+ catch (err) {
1016
+ logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1017
+ }
1018
+ })();
1019
+ }
748
1020
  // ---------- scheduling loop ----------
749
1021
  function scheduleRepo(repo) {
750
1022
  const previous = timers.get(repo.id);
@@ -756,12 +1028,22 @@ export function createTeamAutoScheduler(deps) {
756
1028
  return;
757
1029
  }
758
1030
  let delay;
759
- try {
760
- delay = nextFireMs(repo.schedule);
1031
+ // Auto-paused repos arm the RETRY ladder, not the regular schedule: the
1032
+ // retry-due check used to ride the next regular tick, so "auto-retry in
1033
+ // ~1min" for a network blip really meant "at the next hourly tick".
1034
+ // While paused, retry at the class-aware backoff; a successful sweep
1035
+ // clears pausedReason and restores the regular schedule below.
1036
+ if (isAutoPause(repo.pausedReason) && repo.lastSweepErrorAt) {
1037
+ delay = Math.max(SWEEP_RETRY_FLOOR_MS, sweepRetryDueAt(repo.sweepFailures ?? 1, repo.lastSweepErrorAt, failClassFromPauseReason(repo.pausedReason)) - Date.now());
761
1038
  }
762
- catch (err) {
763
- logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
764
- return;
1039
+ else {
1040
+ try {
1041
+ delay = nextFireMs(repo.schedule);
1042
+ }
1043
+ catch (err) {
1044
+ logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
1045
+ return;
1046
+ }
765
1047
  }
766
1048
  const timer = setTimeout(() => {
767
1049
  void (async () => {
@@ -769,7 +1051,7 @@ export function createTeamAutoScheduler(deps) {
769
1051
  const s = await ensureStore();
770
1052
  const fresh = s.repos.find((r) => r.id === repo.id);
771
1053
  const retryDue = fresh
772
- ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
1054
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0, failClassFromPauseReason(fresh.pausedReason))
773
1055
  : false;
774
1056
  if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
775
1057
  await runSweep(fresh, false);
@@ -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,