@teamclaws/teamclaw 2026.11.2 → 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 (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 +33 -0
  14. package/dist/src/teamauto/scanner.js +9 -1
  15. package/dist/src/teamauto/scheduler.js +292 -17
  16. package/dist/src/teamauto/store.js +9 -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 +36 -0
  34. package/src/teamauto/scanner.ts +9 -1
  35. package/src/teamauto/scheduler.ts +295 -17
  36. package/src/teamauto/store.ts +31 -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,
@@ -93,16 +96,54 @@ export function hardAttemptCount(
93
96
  ).length;
94
97
  }
95
98
 
96
- /** Auto-pause retry backoff: 30m after the 1st failure, doubling, capped at 4h. */
99
+ /** Auto-pause retry backoff for classes where a fast retry is useless or
100
+ * harmful: 30m after the 1st failure, doubling, capped at 4h. auth needs a
101
+ * human re-login; ratelimited retried early just re-triggers the limit. */
97
102
  export const SWEEP_RETRY_BASE_MINUTES = 30;
98
103
  export const SWEEP_RETRY_MAX_MINUTES = 240;
99
104
  export function sweepBackoffMinutes(failures: number): number {
100
105
  return Math.min(SWEEP_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_RETRY_MAX_MINUTES);
101
106
  }
102
107
 
108
+ /** Sweep-timeout report: a transient "fetch failed" sat a full 30m before
109
+ * its first retry - a seconds-long network blip cost half an hour of repo
110
+ * idle time. Network-class failures get a fast ladder: 1m, 2m, 4m... capped
111
+ * at 15m. The cap means a genuinely-down network converges to one attempt
112
+ * per 15m (slower than the old ladder's first step, so we never hammer),
113
+ * but a single blip costs one minute instead of thirty. */
114
+ export const SWEEP_NETWORK_RETRY_BASE_MINUTES = 1;
115
+ export const SWEEP_NETWORK_RETRY_MAX_MINUTES = 15;
116
+ export function sweepNetworkBackoffMinutes(failures: number): number {
117
+ return Math.min(SWEEP_NETWORK_RETRY_BASE_MINUTES * 2 ** Math.max(0, failures - 1), SWEEP_NETWORK_RETRY_MAX_MINUTES);
118
+ }
119
+
120
+ /** Class-aware dispatch: the retry ladder a failure class deserves. */
121
+ export function sweepBackoffMinutesFor(failClass: SweepFailClass, failures: number): number {
122
+ return failClass === "network" ? sweepNetworkBackoffMinutes(failures) : sweepBackoffMinutes(failures);
123
+ }
124
+
125
+ /** Timer floor when arming the retry ladder: a just-missed due time must not
126
+ * fire at 0ms (tight failure/retry loop protection). */
127
+ export const SWEEP_RETRY_FLOOR_MS = 5_000;
128
+
103
129
  /** 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;
130
+ export function sweepRetryDueAt(failures: number, lastErrorAt: number, failClass: SweepFailClass = "network"): number {
131
+ return lastErrorAt + sweepBackoffMinutesFor(failClass, failures) * 60_000;
132
+ }
133
+
134
+ /** In-place network retries: a transient "fetch failed"/"terminated" is
135
+ * retried immediately INSIDE the sweep invocation (user report 2026-11-14:
136
+ * "sweep failed[network] (auto-retry in ~30min): fetch failed" - the repo
137
+ * idled half an hour on a blip that a 5s retry would have survived). 10
138
+ * attempts with a 3s..30s delay ladder (~2.5min worst case) before the
139
+ * failure is recorded and the pause/backoff path takes over. Non-network
140
+ * classes (auth, ratelimited) never retry in place - retrying is useless
141
+ * or harmful. */
142
+ export const SWEEP_INPLACE_RETRIES = 10;
143
+ export const SWEEP_INPLACE_DELAY_BASE_MS = 3_000;
144
+ export const SWEEP_INPLACE_DELAY_MAX_MS = 30_000;
145
+ export function sweepInplaceDelayMs(attempt: number): number {
146
+ return Math.min(SWEEP_INPLACE_DELAY_BASE_MS * 2 ** Math.max(0, attempt - 1), SWEEP_INPLACE_DELAY_MAX_MS);
106
147
  }
107
148
 
108
149
  /**
@@ -130,9 +171,38 @@ export function writebackRetryDueAt(attempts: number, lastErrorAt: number): numb
130
171
  return lastErrorAt + writebackBackoffMs(attempts);
131
172
  }
132
173
 
133
- /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not. */
174
+ /** #267-1: sweep failures are classified so operators can act on the RIGHT
175
+ * root cause: 401 -> re-login, 403/429 -> back off harder, network -> the
176
+ * existing retry ladder. undici wraps HTTP errors; the status rides on
177
+ * err.cause (fetch failed). Unknown causes stay "network" - the ladder's
178
+ * existing semantics. */
179
+ export type SweepFailClass = "auth" | "ratelimited" | "network";
180
+ export function classifySweepError(err: unknown): SweepFailClass {
181
+ const cause = (err as { cause?: { status?: number }; status?: number })?.cause ?? (err as { status?: number });
182
+ const status = Number(cause?.status ?? 0);
183
+ if (status === 401) return "auth";
184
+ if (status === 403 || status === 429) return "ratelimited";
185
+ return "network";
186
+ }
187
+
188
+ /** Auto-pauses (set by the sweep catch block) are cooldowns; user pauses are not.
189
+ * Accept BOTH the legacy prefix ("sweep failed: ...") and the #267 classified
190
+ * format ("sweep failed[network]: ...") - the classified format broke the old
191
+ * startsWith("sweep failed:") check, so successful sweeps could never clear
192
+ * the pause and the retry timer never re-armed (all four repos stuck paused
193
+ * after the 12:30 restart-window failures; found 2026-11-12). */
134
194
  export function isAutoPause(reason: string | null | undefined): boolean {
135
- return !!reason && reason.startsWith("sweep failed:");
195
+ if (!reason) return false;
196
+ return /^sweep failed(\[[^\]]*\])?:/.test(reason);
197
+ }
198
+
199
+ /** Recover the fail class from a persisted auto-pause reason
200
+ * ("sweep failed[network]: ..."). Legacy/unparsable reasons default to the
201
+ * fast network ladder - a wrong guess only retries sooner, and the ladder
202
+ * itself still caps the attempt rate, so the default is safe. */
203
+ export function failClassFromPauseReason(reason: string | null | undefined): SweepFailClass {
204
+ const m = reason?.match(/^sweep failed\[([^\]]*)\]/);
205
+ return m && (m[1] === "auth" || m[1] === "ratelimited" || m[1] === "network") ? m[1] : "network";
136
206
  }
137
207
 
138
208
  export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
@@ -153,6 +223,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
153
223
  */
154
224
  function markWritebackFailure(store: TeamAutoStore, entry: TeamAutoWriteBack, message: string, options: { terminal?: boolean } = {}): void {
155
225
  entry.error = message;
226
+ entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
156
227
  entry.attempts = (entry.attempts ?? 0) + 1;
157
228
  entry.lastErrorAt = Date.now();
158
229
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
@@ -408,8 +479,34 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
408
479
  return "sweep already in progress";
409
480
  }
410
481
  sweeping.add(repo.id);
482
+ const sweepStartedAt = Date.now();
483
+ const etagBefore = client.etagStats();
411
484
  try {
412
- const { candidates, issues, pulls, newCommits, commits } = await sweepRepo(repo, client);
485
+ // #sweep-inplace: transient network failures retry IN PLACE (see
486
+ // SWEEP_INPLACE_RETRIES) - only a network blip that survives ~2.5min of
487
+ // retrying reaches the failure-recording path below.
488
+ let swept: Awaited<ReturnType<typeof sweepRepo>> | undefined;
489
+ let lastNetworkErr: unknown;
490
+ for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
491
+ try {
492
+ swept = await sweepRepo(repo, client);
493
+ break;
494
+ } catch (err) {
495
+ if (classifySweepError(err) !== "network") {
496
+ throw err;
497
+ }
498
+ lastNetworkErr = err;
499
+ const message0 = err instanceof Error ? err.message : String(err);
500
+ logger.warn(`TeamAuto: sweep ${repo.id} network error (attempt ${attempt}/${SWEEP_INPLACE_RETRIES}): ${message0}`);
501
+ if (attempt < SWEEP_INPLACE_RETRIES) {
502
+ await new Promise((resolve) => setTimeout(resolve, sweepInplaceDelayMs(attempt)));
503
+ }
504
+ }
505
+ }
506
+ if (!swept) {
507
+ throw lastNetworkErr;
508
+ }
509
+ const { candidates, issues, pulls, newCommits, commits } = swept;
413
510
  const dryRun = !repo.dryRunDone && s.budget.firstSweepDryRun;
414
511
  if (dryRun) {
415
512
  // One observing pass, then act. Flip unconditionally - flipping only
@@ -452,6 +549,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
452
549
  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
550
  } else if (taskId) {
454
551
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
552
+ claimIssue(repo, candidate); // #268: visible claim at enqueue time
455
553
  const action = candidate.kind === "prReview"
456
554
  ? ("prComment" as const)
457
555
  : candidate.kind === "fullReview"
@@ -476,6 +574,8 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
476
574
  }
477
575
  repo.sweepFailures = 0;
478
576
  repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
577
+ const etagAfter = client.etagStats();
578
+ 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
579
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
480
580
  await saveTeamAutoStore(s);
481
581
  if (created > 0) {
@@ -494,8 +594,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
494
594
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
495
595
  repo.lastSweepErrorAt = Date.now();
496
596
  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}` });
597
+ const failClass = classifySweepError(err);
598
+ repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
599
+ const etagAfter = client.etagStats();
600
+ 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) });
601
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
499
602
  await saveTeamAutoStore(s).catch(() => {});
500
603
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
501
604
  return `error: ${message}`;
@@ -620,9 +723,65 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
620
723
  }
621
724
 
622
725
  // ---------- write-back reconciler ----------
623
-
726
+ // #269: the 20s interval fires `void reconcileWritebacks()` fire-and-forget,
727
+ // and a slow delivery (worktree ensure + commit + PR > 20s) let the next
728
+ // tick re-read the same pending entries before doneAt landed - same
729
+ // comment delivered twice (ggcode#5480, byte-identical pair). Two-layer
730
+ // fix: serialize the whole pass (guard below) + intent-first inFlightAt
731
+ // persisted BEFORE dispatch so even a concurrent caller cannot re-send.
732
+ let reconcileInFlight = false;
624
733
  async function reconcileWritebacks(): Promise<void> {
625
- const s = await ensureStore();
734
+ if (reconcileInFlight) {
735
+ return; // a pass is still delivering - never overlap (#269)
736
+ }
737
+ // #269 recurrence (23:40 CST): MULTIPLE gateway processes share one
738
+ // ~/.openclaw store (launchctl service + spawned gateways). In-process
739
+ // guards cannot see another process's deliveries - each kept its
740
+ // startup-cached store and delivered the same pending row (3s apart,
741
+ // two "issueComment ok" for one task). Cross-process mutex: an atomic
742
+ // mkdir lock dir next to the store file; stale (>5min) locks are
743
+ // taken over (crashed holder).
744
+ const { storeFile } = resolveTeamAutoPaths();
745
+ const lockDir = `${storeFile}.reconcile-lock`;
746
+ let locked = false;
747
+ try {
748
+ try {
749
+ await fs.mkdir(lockDir);
750
+ locked = true;
751
+ } catch {
752
+ // Held - unless stale (holder crashed mid-pass).
753
+ try {
754
+ const st = await fs.stat(lockDir);
755
+ if (Date.now() - st.mtimeMs > 300_000) {
756
+ await fs.rm(lockDir, { recursive: true, force: true });
757
+ await fs.mkdir(lockDir);
758
+ locked = true;
759
+ }
760
+ } catch { /* racing takeover - someone else won; skip this pass */ }
761
+ }
762
+ if (!locked) {
763
+ return; // another PROCESS is mid-reconcile; our next tick re-tries
764
+ }
765
+ reconcileInFlight = true;
766
+ try {
767
+ await doReconcileWritebacks();
768
+ } finally {
769
+ reconcileInFlight = false;
770
+ }
771
+ } finally {
772
+ if (locked) {
773
+ await fs.rm(lockDir, { recursive: true, force: true }).catch(() => {});
774
+ }
775
+ }
776
+ }
777
+
778
+ async function doReconcileWritebacks(): Promise<void> {
779
+ // #269 recurrence: re-read the store from disk EVERY pass - the
780
+ // closure cache is a startup snapshot that never sees another
781
+ // process's persisted inFlightAt/doneAt, which is exactly how the
782
+ // 23:40 double delivery happened.
783
+ store = await loadTeamAutoStore();
784
+ const s = store;
626
785
  const state0 = deps.getTeamState();
627
786
  // Dead letters: entries whose task is gone or failed without a result can
628
787
  // never deliver - drop them instead of accumulating forever.
@@ -675,7 +834,30 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
675
834
  }
676
835
  }
677
836
  }
678
- const pending = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt);
837
+ // #269: reset stale in-flight intents (crashed mid-dispatch) so they
838
+ // re-enter the pending set instead of wedging forever.
839
+ for (const w of s.writebacks) {
840
+ if (w.inFlightAt && !w.doneAt && Date.now() - w.inFlightAt > 600_000) {
841
+ w.inFlightAt = undefined;
842
+ }
843
+ }
844
+ const pendingAll = s.writebacks.filter((w) => !w.doneAt && !w.error && !w.failedAt && !w.inFlightAt);
845
+ // #269 per-target dedupe (delivery side): cap at ONE entry per target
846
+ // key per pass, so N pending rows aimed at the same issue/PR cannot
847
+ // burst N same-second comments even if they somehow slipped the enqueue
848
+ // check (e.g. pre-fix stores). Deferred rows simply ride the next 20s
849
+ // pass. Null-target create* rows key on taskId: each is a distinct
850
+ // create intent and must never be merged.
851
+ const seenTarget = new Set<string>();
852
+ const pending = [];
853
+ for (const w of pendingAll) {
854
+ const key = w.targetId != null ? `${w.action}|${w.repoId}|${w.targetId}` : `${w.action}|${w.taskId}`;
855
+ if (seenTarget.has(key)) {
856
+ continue;
857
+ }
858
+ seenTarget.add(key);
859
+ pending.push(w);
860
+ }
679
861
  if (!pending.length) {
680
862
  return;
681
863
  }
@@ -684,6 +866,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
684
866
  return;
685
867
  }
686
868
  for (const entry of pending) {
869
+ // #269 intent-first: persist the dispatch intent BEFORE any await so
870
+ // an overlapping pass (or a future guard-less caller) filters this
871
+ // entry out instead of re-delivering it.
872
+ entry.inFlightAt = Date.now();
873
+ await saveTeamAutoStore(s);
687
874
  const task = state.tasks[entry.taskId];
688
875
  if (!task || (task.status !== "completed" && task.status !== "failed")) {
689
876
  continue;
@@ -725,6 +912,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
725
912
  // push its branch, open a PR, and attach the link to the reply.
726
913
  const repoId = entry.repoId;
727
914
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
915
+ let prDeliveryFailed = false;
728
916
  if (isTeamAutoWrite) {
729
917
  try {
730
918
  const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
@@ -745,11 +933,24 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
745
933
  await sync.removeTaskWorktree(repoId, task.id);
746
934
  } catch (prErr) {
747
935
  markWritebackFailure(s, entry, `worktree PR delivery failed: ${prErr instanceof Error ? prErr.message : String(prErr)}`);
936
+ // #269 4th recurrence (ggcode#5524): a failed PR step must abort
937
+ // the WHOLE entry this pass. The old fall-through posted the
938
+ // link-less comment anyway, set doneAt, and the #24 cleanup
939
+ // cleared the error - a partial delivery masked as success.
940
+ // The retry pass then delivered the WITH-link comment too:
941
+ // two comments 2s apart. Fail atomically instead: the entry
942
+ // keeps its failed state + backoff and replays BOTH steps
943
+ // (PR first, then comment) on the next attempt.
944
+ prDeliveryFailed = true;
748
945
  }
749
946
  }
947
+ if (prDeliveryFailed) {
948
+ continue;
949
+ }
750
950
  if (entry.action === "issueComment" && entry.targetId) {
751
951
  await client.postIssueComment(owner, name, entry.targetId, body);
752
952
  entry.doneAt = Date.now();
953
+ entry.inFlightAt = undefined;
753
954
  writebackDone = true;
754
955
  // Our own comment bumps the issue's updatedAt, which the scanner
755
956
  // treats as new activity - advance the seen cursor so we do not
@@ -762,6 +963,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
762
963
  } else if (entry.action === "prComment" && entry.targetId) {
763
964
  await client.postPullReviewComment(owner, name, entry.targetId, body);
764
965
  entry.doneAt = Date.now();
966
+ entry.inFlightAt = undefined;
765
967
  writebackDone = true;
766
968
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
767
969
  if (prRepo) {
@@ -778,6 +980,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
778
980
  await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
779
981
  entry.targetId = umbrella.targetId;
780
982
  entry.doneAt = Date.now();
983
+ entry.inFlightAt = undefined;
781
984
  writebackDone = true;
782
985
  } else if (entry.targetId == null) {
783
986
  const number = await client.createIssue(
@@ -789,12 +992,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
789
992
  );
790
993
  entry.targetId = number;
791
994
  entry.doneAt = Date.now();
995
+ entry.inFlightAt = undefined;
792
996
  writebackDone = true;
793
997
  }
794
998
  } else {
795
999
  const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
796
1000
  entry.targetId = number;
797
1001
  entry.doneAt = Date.now();
1002
+ entry.inFlightAt = undefined;
798
1003
  writebackDone = true;
799
1004
  }
800
1005
  } else {
@@ -824,11 +1029,75 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
824
1029
  if (s.writebacks.some((w) => w.taskId === taskId)) {
825
1030
  return;
826
1031
  }
1032
+ // #269 per-target dedupe (enqueue side): a second registration for
1033
+ // the SAME target + action with no doneAt yet is a duplicate in the
1034
+ // making - the delivery pass would fan out two comments onto one
1035
+ // target. Skip it; the pending original still delivers the content.
1036
+ // targetId null (create* actions) cannot be target-deduped pre-delivery
1037
+ // and is excluded by the taskId check above.
1038
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1039
+ return;
1040
+ }
827
1041
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
828
1042
  void saveTeamAutoStore(s);
829
1043
  }).catch(() => {});
830
1044
  }
831
1045
 
1046
+ /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
1047
+ * assignIssue was dead code and registerWriteback had no assign action, so
1048
+ * claims existed only in internal state - humans could not see the bot had
1049
+ * picked an issue up (collision risk), contradicting the design decision
1050
+ * that identity presents as the logged-in account's activity.
1051
+ * Fired at ENQUEUE time: a claim is a placeholder declaration; posting it
1052
+ * at completion would leave the whole execution window claim-invisible.
1053
+ * Best-effort, never blocks the task. Review notes (#268):
1054
+ * (a) re-check assignees at claim time (the scan snapshot is seconds
1055
+ * stale - a human may have self-assigned in between);
1056
+ * (b) stamp cursors.seen with NOW + 60s on BOTH success paths (assign
1057
+ * AND fallback comment) because our own write bumps the issue's
1058
+ * updated_at - a bare-assign stamp would lose the scanner's
1059
+ * `seen >= updatedAt` comparison next sweep and re-candidate the
1060
+ * issue we just claimed (self-triggering loop). */
1061
+ function claimIssue(repo: TeamAutoRepo, candidate: { key: string; number: number; kind: string; title: string }): void {
1062
+ if (candidate.kind !== "takeOwnership" || !candidate.number) {
1063
+ return;
1064
+ }
1065
+ void (async () => {
1066
+ const [owner, name] = repo.id.split("/");
1067
+ const client = createGithubClient(auth);
1068
+ try {
1069
+ const fresh = await client.getIssue(owner, name, candidate.number);
1070
+ if (fresh.state !== "open") {
1071
+ return;
1072
+ }
1073
+ if (repo.policy.skipAssignedToHumans && fresh.assignees.length > 0) {
1074
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claim skipped: issue #${candidate.number} gained an assignee since scan` });
1075
+ return;
1076
+ }
1077
+ const { login } = await client.getAuthenticatedUser();
1078
+ try {
1079
+ await client.assignIssue(owner, name, candidate.number, login);
1080
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
1081
+ } catch {
1082
+ // Fallback: a visible claim comment carries the same placeholder
1083
+ // semantics when the App lacks the assignees write surface.
1084
+ 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.`);
1085
+ recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1086
+ }
1087
+ const s = await ensureStore();
1088
+ const freshRepo = s.repos.find((r) => r.id === repo.id);
1089
+ if (freshRepo) {
1090
+ // +60s guard: our own write (assign or comment) bumps updated_at;
1091
+ // see helper doc.
1092
+ freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1093
+ await saveTeamAutoStore(s);
1094
+ }
1095
+ } catch (err) {
1096
+ logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1097
+ }
1098
+ })();
1099
+ }
1100
+
832
1101
  // ---------- scheduling loop ----------
833
1102
 
834
1103
  function scheduleRepo(repo: TeamAutoRepo): void {
@@ -841,11 +1110,20 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
841
1110
  return;
842
1111
  }
843
1112
  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;
1113
+ // Auto-paused repos arm the RETRY ladder, not the regular schedule: the
1114
+ // retry-due check used to ride the next regular tick, so "auto-retry in
1115
+ // ~1min" for a network blip really meant "at the next hourly tick".
1116
+ // While paused, retry at the class-aware backoff; a successful sweep
1117
+ // clears pausedReason and restores the regular schedule below.
1118
+ if (isAutoPause(repo.pausedReason) && repo.lastSweepErrorAt) {
1119
+ delay = Math.max(SWEEP_RETRY_FLOOR_MS, sweepRetryDueAt(repo.sweepFailures ?? 1, repo.lastSweepErrorAt, failClassFromPauseReason(repo.pausedReason)) - Date.now());
1120
+ } else {
1121
+ try {
1122
+ delay = nextFireMs(repo.schedule);
1123
+ } catch (err) {
1124
+ logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
1125
+ return;
1126
+ }
849
1127
  }
850
1128
  const timer = setTimeout(() => {
851
1129
  void (async () => {
@@ -853,7 +1131,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
853
1131
  const s = await ensureStore();
854
1132
  const fresh = s.repos.find((r) => r.id === repo.id);
855
1133
  const retryDue = fresh
856
- ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0)
1134
+ ? isAutoPause(fresh.pausedReason) && Date.now() >= sweepRetryDueAt(fresh.sweepFailures ?? 1, fresh.lastSweepErrorAt ?? 0, failClassFromPauseReason(fresh.pausedReason))
857
1135
  : false;
858
1136
  if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
859
1137
  await runSweep(fresh, false);
@@ -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[];
package/src/ui/app.js CHANGED
@@ -78,6 +78,11 @@
78
78
  "tab.workspace": "Workspace",
79
79
  "common.showOlder": "Show older ({n})",
80
80
  "tab.settings": "Settings",
81
+ "tab.activity": "Activity",
82
+ "activity.events.title": "Controller activity",
83
+ "activity.events.hint": "Live provisioning, sweeps, task routing and team events (ring buffer, last 400).",
84
+ "activity.log.title": "TeamClaw log tail",
85
+ "activity.log.all": "unfiltered",
81
86
  "settings.models.title": "Model settings",
82
87
  "settings.models.hint": "Default model and per-role overrides.",
83
88
  "settings.workers.title": "Worker scaling (hot)",
@@ -373,6 +378,11 @@
373
378
  "tab.workspace": "工作区",
374
379
  "common.showOlder": "显示更早({n})",
375
380
  "tab.settings": "设置",
381
+ "tab.activity": "活动",
382
+ "activity.events.title": "控制器活动",
383
+ "activity.events.hint": "实时的 worker 供给、sweep、任务分派与团队事件(环形缓冲,最近 400 条)。",
384
+ "activity.log.title": "TeamClaw 日志尾随",
385
+ "activity.log.all": "不过滤",
376
386
  "settings.models.title": "模型设置",
377
387
  "settings.models.hint": "默认模型与按角色覆盖。",
378
388
  "settings.workers.title": "Worker 弹性伸缩(热)",
@@ -4131,6 +4141,9 @@
4131
4141
  if (activeTab === "settings") {
4132
4142
  renderWorkerSettingsPanel();
4133
4143
  }
4144
+ if (activeTab === "activity") {
4145
+ renderActivityTab();
4146
+ }
4134
4147
  if (activeTab === "teamauto") {
4135
4148
  refreshTeamAutoTab();
4136
4149
  }
@@ -5306,6 +5319,37 @@ function renderWorkerSettingsPanel() {
5306
5319
  });
5307
5320
  }
5308
5321
 
5322
+ // Controller Activity tab (#ui-blindness): journal event stream + gateway
5323
+ // log tail. Polls only while the tab is active (no background traffic).
5324
+ var activityTimer = null;
5325
+ function renderActivityTab() {
5326
+ var journalEl = document.getElementById("activity-journal");
5327
+ if (!journalEl) return;
5328
+ function fmtTime(at) {
5329
+ var d = new Date(at);
5330
+ return ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2) + ":" + ("0" + d.getSeconds()).slice(-2);
5331
+ }
5332
+ function load() {
5333
+ apiRequest("/controller/journal?limit=200").then(function (d) {
5334
+ var ev = d.events || [];
5335
+ journalEl.innerHTML = ev.length
5336
+ ? ev.map(function (e) { return escapeHtml(fmtTime(e.at) + " [" + e.type + "] " + e.summary); }).join("\n")
5337
+ : "(no events yet)";
5338
+ }).catch(function (err) { journalEl.textContent = (err && err.message) || "load failed"; });
5339
+ var all = document.getElementById("activity-log-all");
5340
+ apiRequest("/controller/log-tail?lines=200" + (all && all.checked ? "&all=1" : "")).then(function (d) {
5341
+ var logEl = document.getElementById("activity-log");
5342
+ if (logEl) {
5343
+ logEl.textContent = ((d.path || "") + "\n" + (d.lines || []).join("\n")) || "(no log lines matched)";
5344
+ logEl.scrollTop = logEl.scrollHeight;
5345
+ }
5346
+ }).catch(function () { /* transient */ });
5347
+ }
5348
+ if (activityTimer) clearInterval(activityTimer);
5349
+ load();
5350
+ activityTimer = setInterval(load, 5000);
5351
+ }
5352
+
5309
5353
  function openModelSettings() {
5310
5354
  var modal = document.querySelector("#model-settings-modal");
5311
5355
  if (!modal) return;
package/src/ui/index.html CHANGED
@@ -79,6 +79,7 @@
79
79
  </button>
80
80
  <button class="tab" data-tab="workspace"><span class="tab-label" data-i18n="tab.workspace">Workspace</span></button>
81
81
  <button class="tab" data-tab="settings"><span class="tab-label" data-i18n="tab.settings">Settings</span></button>
82
+ <button class="tab" data-tab="activity"><span class="tab-label" data-i18n="tab.activity">Activity</span></button>
82
83
  <button class="tab" data-tab="clarifications">
83
84
  <span class="tab-label" data-i18n="tab.clarifications">Clarifications</span>
84
85
  <span id="clarifications-tab-count" class="tab-badge">0</span>
@@ -151,6 +152,20 @@
151
152
  </div>
152
153
 
153
154
  <!-- Workspace Tab -->
155
+ <div id="tab-activity" class="tab-panel">
156
+ <div class="panel-note" style="padding:12px 14px">
157
+ <h3 data-i18n="activity.events.title" style="margin:0 0 6px">Controller activity</h3>
158
+ <p data-i18n="activity.events.hint" style="margin:0 0 8px;color:#666">Live provisioning, sweeps, task routing and team events (ring buffer, last 400).</p>
159
+ <div id="activity-journal" style="font:12px/1.6 ui-monospace,monospace;max-height:320px;overflow:auto;background:#f6f6f6;padding:8px;border-radius:6px;white-space:pre-wrap"></div>
160
+ </div>
161
+ <div class="panel-note" style="padding:12px 14px;margin-top:10px">
162
+ <h3 data-i18n="activity.log.title" style="margin:0 0 6px">TeamClaw log tail</h3>
163
+ <p style="margin:0 0 8px">
164
+ <label style="font-size:12px;color:#666"><input id="activity-log-all" type="checkbox" /> <span data-i18n="activity.log.all">unfiltered</span></label>
165
+ </p>
166
+ <div id="activity-log" style="font:12px/1.6 ui-monospace,monospace;max-height:420px;overflow:auto;background:#111;color:#9f9;padding:10px;border-radius:6px;white-space:pre-wrap"></div>
167
+ </div>
168
+ </div>
154
169
  <div id="tab-settings" class="tab-panel">
155
170
  <div class="panel-note" style="padding:12px 14px">
156
171
  <h3 data-i18n="settings.models.title" style="margin:0 0 6px">Model settings</h3>