@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
@@ -54,11 +54,17 @@ export type GithubRepoInfo = {
54
54
  };
55
55
 
56
56
  export function createGithubClient(auth: GithubAuthManager) {
57
+ // #267-3: cumulative API-call counters; runSweep reads etagStats() before/
58
+ // after each sweep and stores the DELTA on the repo's sweep record, so the
59
+ // shared client still yields correct per-repo attribution (sweeps are
60
+ // serialized by the sweeping set).
61
+ const etagCounters = { calls: 0, hits: 0 };
57
62
  async function request(
58
63
  method: string,
59
64
  urlPath: string,
60
65
  options: { body?: unknown; etagKey?: string; etags?: EtagCache } = {},
61
66
  ): Promise<{ status: number; data: unknown; notModified: boolean }> {
67
+ etagCounters.calls += 1;
62
68
  const headers: Record<string, string> = {
63
69
  ...(await auth.getAuthHeaders()),
64
70
  "User-Agent": USER_AGENT,
@@ -99,6 +105,9 @@ export function createGithubClient(auth: GithubAuthManager) {
99
105
  const message = (data as { message?: string } | null)?.message ?? `HTTP ${response.status}`;
100
106
  throw new GithubClientError(message, response.status);
101
107
  }
108
+ if (response.status >= 200 && response.status < 300) {
109
+ etagCounters.hits += 1; // #267-3: "hits" = calls that returned fresh data (non-304 successes)
110
+ }
102
111
  return { status: response.status, data, notModified: false };
103
112
  }
104
113
 
@@ -110,6 +119,11 @@ export function createGithubClient(auth: GithubAuthManager) {
110
119
  return {
111
120
  request,
112
121
 
122
+ /** #267-3: cumulative etag/API counters (see etagCounters above). */
123
+ etagStats(): { calls: number; hits: number } {
124
+ return { ...etagCounters };
125
+ },
126
+
113
127
  async getRepoInfo(owner: string, repo: string): Promise<GithubRepoInfo> {
114
128
  const data = await getJson<Record<string, unknown>>(`/repos/${owner}/${repo}`);
115
129
  if (!data) {
@@ -224,6 +238,28 @@ export function createGithubClient(auth: GithubAuthManager) {
224
238
  await request("POST", `/repos/${owner}/${repo}/issues/${issueNumber}/assignees`, { body: { assignees: [assignee] } });
225
239
  },
226
240
 
241
+ /** Fresh issue state for claim-time re-checks (#268): the scan-time
242
+ * assignee snapshot is seconds stale by enqueue time - a human may have
243
+ * self-assigned in between, and claiming over a human is worse than not
244
+ * claiming. */
245
+ async getIssue(owner: string, repo: string, issueNumber: number): Promise<{ assignees: string[]; state: string; updatedAt: string }> {
246
+ const { data } = await request("GET", `/repos/${owner}/${repo}/issues/${issueNumber}`);
247
+ const raw = data as Record<string, unknown>;
248
+ return {
249
+ assignees: Array.isArray(raw.assignees) ? raw.assignees.map((a) => String((a as { login?: string }).login ?? "")).filter(Boolean) : [],
250
+ state: String(raw.state ?? "open"),
251
+ updatedAt: String(raw.updated_at ?? ""),
252
+ };
253
+ },
254
+
255
+ /** Login of the authenticated account (#268): the assignee string for
256
+ * self-claiming. Kept here (not on the auth manager) so the claim path
257
+ * stays client-only. */
258
+ async getAuthenticatedUser(): Promise<{ login: string }> {
259
+ const { data } = await request("GET", "/user");
260
+ return { login: String((data as { login?: string }).login ?? "") };
261
+ },
262
+
227
263
  /** Open a PR from a task worktree branch (collaboration contract delivery). */
228
264
  async createPullRequest(owner: string, repo: string, head: string, base: string, title: string, body: string): Promise<{ number: number; url: string }> {
229
265
  const { data } = await request("POST", `/repos/${owner}/${repo}/pulls`, {
@@ -102,12 +102,25 @@ export async function sweepRepo(
102
102
  repo: TeamAutoRepo,
103
103
  client: TeamAutoGithubClient,
104
104
  now = Date.now(),
105
- ): Promise<{ candidates: Candidate[]; issues: SweepableIssue[]; pulls: SweepablePull[] }> {
105
+ ): Promise<{ candidates: Candidate[]; issues: SweepableIssue[]; pulls: SweepablePull[]; newCommits: { sha: string; message: string }[]; commits: { sha: string; message: string }[] }> {
106
106
  const [owner, name] = repo.id.split("/");
107
107
  const issues = await client.listIssues(owner, name, repo.cursors.lastIssueSince, repo.cursors.etags);
108
108
  const pulls = repo.policy.actions.prReview
109
109
  ? await client.listPulls(owner, name, repo.cursors.etags)
110
110
  : [];
111
+ // #265: the commits leg was dead code (listCommits had zero callers,
112
+ // lastCommitSha never advanced) - the designed third signal source never
113
+ // ran. Wire it as an observation-only feed: fetch, filter past the cursor,
114
+ // and surface the delta. Cursor advance happens in advanceCursors (with
115
+ // the other legs, so dry-run semantics stay intact); it produces no task
116
+ // candidates (issue/pull policies stay the sole candidate sources).
117
+ const commits = await client.listCommits(owner, name, repo.cursors.lastCommitSha);
118
+ // Newest-first feed: when the cursor is set, stop the delta at the first
119
+ // entry whose sha equals it (that commit and everything after is already
120
+ // known). An unset cursor means first sweep: observe only, report nothing.
121
+ const newCommits = repo.cursors.lastCommitSha
122
+ ? commits.slice(0, (() => { const i = commits.findIndex((c) => c.sha === repo.cursors.lastCommitSha); return i === -1 ? commits.length : i; })())
123
+ : [];
111
124
  const candidates: Candidate[] = [];
112
125
 
113
126
  for (const issue of issues) {
@@ -138,7 +151,15 @@ export async function sweepRepo(
138
151
  role: "qa" as const,
139
152
  writeMode: "read-only" as const,
140
153
  };
141
- if (repo.policy.actions.issueReview) {
154
+ // #269 6th case (ggcode#4785): an issue eligible for BOTH actions got
155
+ // two tasks in the same sweep, each delivering its own comment - the
156
+ // delivery layer correctly treats them as independent entries. Collapse
157
+ // at the source: when ownership applies (open + enabled) it wins and
158
+ // subsumes the triage read; issueReview fires only when ownership is
159
+ // disabled for this repo (or the issue is closed and un-reviewable via
160
+ // ownership, e.g. follow-up triage on a closed issue).
161
+ const ownershipApplies = repo.policy.actions.takeOwnership && issue.state === "open";
162
+ if (repo.policy.actions.issueReview && !ownershipApplies) {
142
163
  candidates.push({
143
164
  ...base,
144
165
  kind: "issueReview",
@@ -220,17 +241,23 @@ export async function sweepRepo(
220
241
  }
221
242
  }
222
243
 
223
- return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls };
244
+ return { candidates: candidates.slice(0, repo.policy.maxTasksPerSweep * 2), issues, pulls, newCommits, commits };
224
245
  }
225
246
 
226
247
  /** Advance cursors after tasks were enqueued (or observed on first sweep). */
227
- export function advanceCursors(repo: TeamAutoRepo, issues: SweepableIssue[], pulls: SweepablePull[], now = Date.now()): void {
248
+ export function advanceCursors(repo: TeamAutoRepo, issues: SweepableIssue[], pulls: SweepablePull[], now = Date.now(), commits: { sha: string; message: string }[] = []): void {
228
249
  for (const issue of issues) {
229
250
  repo.cursors.seen[`${repo.id}#issue-${issue.number}`] = Date.parse(issue.updatedAt) || now;
230
251
  }
231
252
  for (const pull of pulls) {
232
253
  repo.cursors.seen[`${repo.id}#pr-${pull.number}`] = Date.parse(pull.updated_at) || now;
233
254
  }
255
+ // Commit cursor: the feed is newest-first, so when anything came back the
256
+ // HEAD entry IS the new cursor. Empty feed keeps the old cursor (nothing
257
+ // new to advance to).
258
+ if (commits.length > 0) {
259
+ repo.cursors.lastCommitSha = commits[0].sha;
260
+ }
234
261
  // Cap the seen map so it cannot grow unbounded.
235
262
  const entries = Object.entries(repo.cursors.seen);
236
263
  if (entries.length > 2000) {
@@ -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 } = 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
@@ -422,7 +519,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
422
519
  // Advance only for acting sweeps: a dry-run must leave the cursors
423
520
  // untouched so the reported actions are actually performed next time
424
521
  // instead of being marked as already-seen.
425
- advanceCursors(repo, issues, pulls);
522
+ advanceCursors(repo, issues, pulls, Date.now(), commits);
426
523
  }
427
524
  // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
428
525
  // pull candidates, so a busy repo would otherwise starve them forever
@@ -433,6 +530,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
433
530
  const capped = [...fullReviews, ...regular];
434
531
  let created = 0;
435
532
  const summary: string[] = [`found ${candidates.length} candidate(s)`];
533
+ // #265: surface the commits delta so the third signal source is
534
+ // observable in sweep summaries (was silently dead before).
535
+ if (newCommits.length > 0) {
536
+ summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
537
+ }
436
538
 
437
539
  if (capped.length && dryRun) {
438
540
  summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
@@ -447,6 +549,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
447
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}` });
448
550
  } else if (taskId) {
449
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
450
553
  const action = candidate.kind === "prReview"
451
554
  ? ("prComment" as const)
452
555
  : candidate.kind === "fullReview"
@@ -470,6 +573,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
470
573
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
471
574
  }
472
575
  repo.sweepFailures = 0;
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) });
473
579
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
474
580
  await saveTeamAutoStore(s);
475
581
  if (created > 0) {
@@ -487,8 +593,12 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
487
593
  // backoff below, and a success clears the state in the block above.
488
594
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
489
595
  repo.lastSweepErrorAt = Date.now();
490
- repo.pausedReason = `sweep failed: ${message}`;
491
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed (auto-retry in ~${sweepBackoffMinutes(repo.sweepFailures)}min): ${message}` });
596
+ repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
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}` });
492
602
  await saveTeamAutoStore(s).catch(() => {});
493
603
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
494
604
  return `error: ${message}`;
@@ -613,9 +723,65 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
613
723
  }
614
724
 
615
725
  // ---------- write-back reconciler ----------
616
-
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;
617
733
  async function reconcileWritebacks(): Promise<void> {
618
- 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;
619
785
  const state0 = deps.getTeamState();
620
786
  // Dead letters: entries whose task is gone or failed without a result can
621
787
  // never deliver - drop them instead of accumulating forever.
@@ -668,7 +834,30 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
668
834
  }
669
835
  }
670
836
  }
671
- 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
+ }
672
861
  if (!pending.length) {
673
862
  return;
674
863
  }
@@ -677,6 +866,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
677
866
  return;
678
867
  }
679
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);
680
874
  const task = state.tasks[entry.taskId];
681
875
  if (!task || (task.status !== "completed" && task.status !== "failed")) {
682
876
  continue;
@@ -718,6 +912,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
718
912
  // push its branch, open a PR, and attach the link to the reply.
719
913
  const repoId = entry.repoId;
720
914
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
915
+ let prDeliveryFailed = false;
721
916
  if (isTeamAutoWrite) {
722
917
  try {
723
918
  const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
@@ -738,11 +933,24 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
738
933
  await sync.removeTaskWorktree(repoId, task.id);
739
934
  } catch (prErr) {
740
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;
741
945
  }
742
946
  }
947
+ if (prDeliveryFailed) {
948
+ continue;
949
+ }
743
950
  if (entry.action === "issueComment" && entry.targetId) {
744
951
  await client.postIssueComment(owner, name, entry.targetId, body);
745
952
  entry.doneAt = Date.now();
953
+ entry.inFlightAt = undefined;
746
954
  writebackDone = true;
747
955
  // Our own comment bumps the issue's updatedAt, which the scanner
748
956
  // treats as new activity - advance the seen cursor so we do not
@@ -755,6 +963,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
755
963
  } else if (entry.action === "prComment" && entry.targetId) {
756
964
  await client.postPullReviewComment(owner, name, entry.targetId, body);
757
965
  entry.doneAt = Date.now();
966
+ entry.inFlightAt = undefined;
758
967
  writebackDone = true;
759
968
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
760
969
  if (prRepo) {
@@ -771,6 +980,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
771
980
  await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
772
981
  entry.targetId = umbrella.targetId;
773
982
  entry.doneAt = Date.now();
983
+ entry.inFlightAt = undefined;
774
984
  writebackDone = true;
775
985
  } else if (entry.targetId == null) {
776
986
  const number = await client.createIssue(
@@ -782,12 +992,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
782
992
  );
783
993
  entry.targetId = number;
784
994
  entry.doneAt = Date.now();
995
+ entry.inFlightAt = undefined;
785
996
  writebackDone = true;
786
997
  }
787
998
  } else {
788
999
  const number = await client.createIssue(owner, name, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`, sectionBody, ["teamclaw"]);
789
1000
  entry.targetId = number;
790
1001
  entry.doneAt = Date.now();
1002
+ entry.inFlightAt = undefined;
791
1003
  writebackDone = true;
792
1004
  }
793
1005
  } else {
@@ -817,11 +1029,75 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
817
1029
  if (s.writebacks.some((w) => w.taskId === taskId)) {
818
1030
  return;
819
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
+ }
820
1041
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
821
1042
  void saveTeamAutoStore(s);
822
1043
  }).catch(() => {});
823
1044
  }
824
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
+
825
1101
  // ---------- scheduling loop ----------
826
1102
 
827
1103
  function scheduleRepo(repo: TeamAutoRepo): void {
@@ -834,11 +1110,20 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
834
1110
  return;
835
1111
  }
836
1112
  let delay: number;
837
- try {
838
- delay = nextFireMs(repo.schedule);
839
- } catch (err) {
840
- logger.error(`TeamAuto: ${repo.id} has an unsupported schedule "${repo.schedule}" and will not be scheduled: ${err instanceof Error ? err.message : String(err)}`);
841
- 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
+ }
842
1127
  }
843
1128
  const timer = setTimeout(() => {
844
1129
  void (async () => {
@@ -846,7 +1131,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
846
1131
  const s = await ensureStore();
847
1132
  const fresh = s.repos.find((r) => r.id === repo.id);
848
1133
  const retryDue = fresh
849
- ? 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))
850
1135
  : false;
851
1136
  if (fresh?.enabled && (fresh.pausedReason === null || retryDue)) {
852
1137
  await runSweep(fresh, false);