@teamclaws/teamclaw 2026.11.5 → 2026.11.6

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 (47) hide show
  1. package/dist/src/controller/config-routes.js +7 -3
  2. package/dist/src/controller/controller-service.js +12 -1
  3. package/dist/src/controller/provisioning/container-shared.js +6 -1
  4. package/dist/src/controller/provisioning/docker.js +1 -1
  5. package/dist/src/controller/provisioning/kubernetes.js +1 -1
  6. package/dist/src/controller/provisioning/process-supervisor.js +12 -1
  7. package/dist/src/controller/provisioning-config.js +8 -0
  8. package/dist/src/controller/task-assignment.js +65 -2
  9. package/dist/src/controller/task-results.js +34 -3
  10. package/dist/src/controller/task-routes.js +24 -1
  11. package/dist/src/controller/worker-provisioning.js +35 -0
  12. package/dist/src/controller/worker-routes.js +21 -6
  13. package/dist/src/openclaw-workspace.js +39 -20
  14. package/dist/src/task-executor.js +44 -3
  15. package/dist/src/teamauto/github-client.js +88 -5
  16. package/dist/src/teamauto/repo-sync.js +77 -5
  17. package/dist/src/teamauto/scanner.js +22 -1
  18. package/dist/src/teamauto/scheduler.js +556 -180
  19. package/dist/src/teamauto/store.js +46 -0
  20. package/dist/src/teamauto/write-payload-guard.js +209 -0
  21. package/dist/src/types.js +6 -0
  22. package/dist/src/worker/tools.js +5 -0
  23. package/openclaw.plugin.json +1 -1
  24. package/package.json +1 -1
  25. package/src/controller/config-routes.ts +7 -3
  26. package/src/controller/controller-service.ts +12 -1
  27. package/src/controller/provisioning/backend-contract.ts +4 -0
  28. package/src/controller/provisioning/container-shared.ts +6 -1
  29. package/src/controller/provisioning/docker.ts +1 -1
  30. package/src/controller/provisioning/kubernetes.ts +1 -1
  31. package/src/controller/provisioning/process-supervisor.ts +12 -1
  32. package/src/controller/provisioning-config.ts +9 -0
  33. package/src/controller/task-assignment.ts +71 -1
  34. package/src/controller/task-results.ts +33 -3
  35. package/src/controller/task-routes.ts +25 -1
  36. package/src/controller/worker-provisioning.ts +35 -0
  37. package/src/controller/worker-routes.ts +21 -7
  38. package/src/openclaw-workspace.ts +43 -23
  39. package/src/task-executor.ts +46 -3
  40. package/src/teamauto/github-client.ts +83 -5
  41. package/src/teamauto/repo-sync.ts +75 -4
  42. package/src/teamauto/scanner.ts +23 -2
  43. package/src/teamauto/scheduler.ts +472 -103
  44. package/src/teamauto/store.ts +72 -0
  45. package/src/teamauto/write-payload-guard.ts +222 -0
  46. package/src/types.ts +21 -0
  47. package/src/worker/tools.ts +5 -0
@@ -7,9 +7,11 @@ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js
7
7
  import { createGithubClient } from "./github-client.js";
8
8
  import { learnNorms, renderNormsBlock } from "./norms.js";
9
9
  import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
10
+ import { ENVELOPE_LEAK_MARKER } from "./write-payload-guard.js";
10
11
  import { nextFireMs } from "./schedule.js";
11
12
  import { resolveTeamAutoPaths } from "./store.js";
12
13
  import { advanceCursors, sweepRepo } from "./scanner.js";
14
+ import { withStoreLock } from "./store.js";
13
15
  import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, pushSweepRecord, } from "./store.js";
14
16
  /**
15
17
  * TeamAuto scheduler: per-repo cron sweeps -> TeamClaw tasks -> GitHub
@@ -177,7 +179,10 @@ export function createTeamAutoScheduler(deps) {
177
179
  entry.attempts = (entry.attempts ?? 0) + 1;
178
180
  entry.lastErrorAt = Date.now();
179
181
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
180
- const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
182
+ // #5651: a non-fast-forward push whose rebase self-heal also failed is
183
+ // deterministic - retrying the same push 6 more times just burns ~25min.
184
+ // Dead-letter immediately (the next sweep re-claims on a fresh branch).
185
+ const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS || /push rejected \(non-fast-forward\) and rebase self-heal failed/.test(message);
181
186
  if (gaveUp && !entry.doneAt) {
182
187
  entry.failedAt = Date.now();
183
188
  recordActivity(store, {
@@ -281,6 +286,7 @@ export function createTeamAutoScheduler(deps) {
281
286
  let store = null;
282
287
  let writebackTimer = null;
283
288
  let claimRecoveryTimer = null;
289
+ let gcTimer = null;
284
290
  async function ensureStore() {
285
291
  if (!store) {
286
292
  store = await loadTeamAutoStore();
@@ -452,6 +458,10 @@ export function createTeamAutoScheduler(deps) {
452
458
  for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
453
459
  try {
454
460
  swept = await sweepRepo(repo, client);
461
+ // #5706 (ggcode): sweep observability - "no new work" is ambiguous
462
+ // between an empty fetch (etag 304 / API silence) and full filter
463
+ // rejection. Log the funnel so starvation diagnoses itself.
464
+ logger.info(`TeamAuto: scan funnel ${repo.id}: fetched ${swept.issues.length} issue(s)/${swept.pulls.length} pull(s) -> ${swept.candidates.length} candidate(s) (since=${repo.cursors.lastIssueSince ? new Date(repo.cursors.lastIssueSince).toISOString() : "unset"})`);
455
465
  break;
456
466
  }
457
467
  catch (err) {
@@ -478,72 +488,94 @@ export function createTeamAutoScheduler(deps) {
478
488
  // -> still zero candidates -> dryRunDone never set).
479
489
  repo.dryRunDone = true;
480
490
  }
481
- if (!dryRun) {
482
- // Advance only for acting sweeps: a dry-run must leave the cursors
483
- // untouched so the reported actions are actually performed next time
484
- // instead of being marked as already-seen.
485
- advanceCursors(repo, issues, pulls, Date.now(), commits);
486
- }
487
- // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
488
- // pull candidates, so a busy repo would otherwise starve them forever
489
- // (cap filled every sweep, lastFullReviewAt never advancing). They are
490
- // at most one cycle (3 sections) per interval, so this stays bounded.
491
- const fullReviews = candidates.filter((c) => c.kind === "fullReview");
492
- const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
493
- const capped = [...fullReviews, ...regular];
494
- let created = 0;
495
- const summary = [`found ${candidates.length} candidate(s)`];
496
- // #265: surface the commits delta so the third signal source is
497
- // observable in sweep summaries (was silently dead before).
498
- if (newCommits.length > 0) {
499
- summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
500
- }
501
- if (capped.length && dryRun) {
502
- summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
503
- repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
504
- }
505
- else if (capped.length) {
506
- if (!consumeDailyBudget(s, capped.length)) {
507
- summary.push("skipped: daily task budget exhausted");
491
+ // #5712 (ggcode) / teamclaw#274: the ENTIRE sweep store transaction -
492
+ // cursor/seen advance, budget consume, task activity, write-back
493
+ // registrations, summary, sweep record, and the commit save - is one
494
+ // read-modify-write section. It previously raced the (locked) 20s
495
+ // write-back reconcile: reconcile's disk reload + tail save clobbered
496
+ // the sweep's writes (live: 20:30 batch lost summary/budget/activity
497
+ // while later claim/write-back saves survived). registerWriteback
498
+ // inside uses the *Unlocked core - the promise-chain mutex is NOT
499
+ // re-entrant.
500
+ let created = 0; // #5712: outside the lock scope - read after commit
501
+ await withStoreLock(async () => {
502
+ if (!dryRun) {
503
+ // Advance only for acting sweeps: a dry-run must leave the cursors
504
+ // untouched so the reported actions are actually performed next time
505
+ // instead of being marked as already-seen.
506
+ advanceCursors(repo, issues, pulls, Date.now(), commits);
508
507
  }
509
- else {
510
- for (const candidate of capped) {
511
- const taskId = enqueueCandidate(repo, candidate);
512
- if (taskId === "dead-lettered") {
513
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
508
+ // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
509
+ // pull candidates, so a busy repo would otherwise starve them forever
510
+ // (cap filled every sweep, lastFullReviewAt never advancing). They are
511
+ // at most one cycle (3 sections) per interval, so this stays bounded.
512
+ const fullReviews = candidates.filter((c) => c.kind === "fullReview");
513
+ const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
514
+ const capped = [...fullReviews, ...regular];
515
+ const summary = [`found ${candidates.length} candidate(s)`];
516
+ // #265: surface the commits delta so the third signal source is
517
+ // observable in sweep summaries (was silently dead before).
518
+ if (newCommits.length > 0) {
519
+ summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
520
+ }
521
+ if (capped.length && dryRun) {
522
+ summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
523
+ repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
524
+ }
525
+ else if (capped.length) {
526
+ if (!consumeDailyBudget(s, capped.length)) {
527
+ summary.push("skipped: daily task budget exhausted");
528
+ }
529
+ else {
530
+ for (const candidate of capped) {
531
+ const taskId = enqueueCandidate(repo, candidate);
532
+ if (taskId === "dead-lettered") {
533
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
534
+ }
535
+ else if (taskId) {
536
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
537
+ // #claim-dequeue (user 2026-11-15): claiming at ENQUEUE locked a
538
+ // string of issues behind the one-writer-per-repo queue while
539
+ // they waited - and blindly claimed issues where external
540
+ // collaborators had started working in the scan-to-claim gap.
541
+ // Claiming now happens at DEQUEUE (claimTaskAtDequeue, called
542
+ // from the task assignment path) after a fresh conflict check.
543
+ const action = candidate.kind === "prReview"
544
+ ? "prComment"
545
+ : candidate.kind === "fullReview"
546
+ ? "createIssue"
547
+ : candidate.kind === "prRework"
548
+ ? "prComment"
549
+ : "issueComment";
550
+ await registerWritebackUnlocked(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
551
+ created++;
552
+ }
514
553
  }
515
- else if (taskId) {
516
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
517
- claimIssue(repo, candidate); // #268: visible claim at enqueue time
518
- const action = candidate.kind === "prReview"
519
- ? "prComment"
520
- : candidate.kind === "fullReview"
521
- ? "createIssue"
522
- : "issueComment";
523
- registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
524
- created++;
554
+ const failedSince = repo.failedTasksSinceLastSweep ?? 0;
555
+ repo.failedTasksSinceLastSweep = 0;
556
+ repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
557
+ if (capped.some((c) => c.kind === "fullReview")) {
558
+ repo.cursors.lastFullReviewAt = Date.now();
525
559
  }
526
560
  }
527
- repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
528
- if (capped.some((c) => c.kind === "fullReview")) {
529
- repo.cursors.lastFullReviewAt = Date.now();
530
- }
531
561
  }
532
- }
533
- else {
534
- repo.lastSweepSummary = "no new work";
535
- }
536
- repo.lastSweepAt = Date.now();
537
- if (isAutoPause(repo.pausedReason)) {
538
- repo.pausedReason = null;
539
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
540
- }
541
- repo.sweepFailures = 0;
542
- repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
543
- const etagAfter = client.etagStats();
544
- 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) });
545
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
546
- await saveTeamAutoStore(s);
562
+ else {
563
+ const failedSince0 = repo.failedTasksSinceLastSweep ?? 0;
564
+ repo.failedTasksSinceLastSweep = 0;
565
+ repo.lastSweepSummary = failedSince0 > 0 ? `no new work; FAILED ${failedSince0} since last sweep` : "no new work";
566
+ }
567
+ repo.lastSweepAt = Date.now();
568
+ if (isAutoPause(repo.pausedReason)) {
569
+ repo.pausedReason = null;
570
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
571
+ }
572
+ repo.sweepFailures = 0;
573
+ repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
574
+ const etagAfter = client.etagStats();
575
+ 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) });
576
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
577
+ await saveTeamAutoStore(s);
578
+ }); // withStoreLock: sweep transaction
547
579
  if (created > 0) {
548
580
  await deps.onTasksCreated().catch((err) => {
549
581
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
@@ -558,15 +590,18 @@ export function createTeamAutoScheduler(deps) {
558
590
  // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
559
591
  // failed". Auto-pauses are cooldowns now: the timer retries after the
560
592
  // backoff below, and a success clears the state in the block above.
561
- repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
562
- repo.lastSweepErrorAt = Date.now();
563
- repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
564
- const failClass = classifySweepError(err);
565
- repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
566
- const etagAfter = client.etagStats();
567
- 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) });
568
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
569
- await saveTeamAutoStore(s).catch(() => { });
593
+ // #5712: failure bookkeeping is a store RMW too - same lock.
594
+ await withStoreLock(async () => {
595
+ repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
596
+ repo.lastSweepErrorAt = Date.now();
597
+ repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
598
+ const failClass = classifySweepError(err);
599
+ repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
600
+ const etagAfter = client.etagStats();
601
+ 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) });
602
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
603
+ await saveTeamAutoStore(s).catch(() => { });
604
+ }); // withStoreLock: failure bookkeeping
570
605
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
571
606
  return `error: ${message}`;
572
607
  }
@@ -737,6 +772,24 @@ export function createTeamAutoScheduler(deps) {
737
772
  }
738
773
  }
739
774
  async function doReconcileWritebacks() {
775
+ // #2677: the WHOLE read-modify-write section holds the store lock -
776
+ // an unlocked reload+save here clobbered a concurrently-registered
777
+ // write-back entry (see store.ts withStoreLock).
778
+ await withStoreLock(async () => {
779
+ await doReconcileWritebacksLocked();
780
+ }).catch((err) => {
781
+ // #5677 ask: never swallow a delivery-pass crash silently - a lost
782
+ // entry with zero trace is invisible; surface it in the log AND the
783
+ // activity feed so the failure class is diagnosable.
784
+ const msg = err instanceof Error ? err.message : String(err);
785
+ logger.warn(`TeamAuto: write-back pass CRASHED (entries may retry next tick): ${msg}`);
786
+ void ensureStore().then((s) => {
787
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `delivery pass crashed: ${msg.slice(0, 140)}` });
788
+ return saveTeamAutoStore(s);
789
+ }).catch(() => { });
790
+ });
791
+ }
792
+ async function doReconcileWritebacksLocked() {
740
793
  // #269 recurrence: re-read the store from disk EVERY pass - the
741
794
  // closure cache is a startup snapshot that never sees another
742
795
  // process's persisted inFlightAt/doneAt, which is exactly how the
@@ -758,12 +811,81 @@ export function createTeamAutoScheduler(deps) {
758
811
  if (dead) {
759
812
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
760
813
  deadOnes.push(w);
814
+ // #5641: the 3-day architect-leg outage was invisible because a
815
+ // failed-without-result task produced NO activity line and the next
816
+ // sweep summary still said "created 3/3". Record both surfaces.
817
+ recordActivity(s, { at: Date.now(), repoId: w.repoId, kind: "task", text: `task failed without result, write-back dropped: ${w.taskId}${t?.error ? ` (${String(t.error).slice(0, 120)})` : ""}` });
818
+ const failedRepo = s.repos.find((r) => r.id === w.repoId);
819
+ if (failedRepo) {
820
+ failedRepo.failedTasksSinceLastSweep = (failedRepo.failedTasksSinceLastSweep ?? 0) + 1;
821
+ }
761
822
  }
762
823
  return !dead;
763
824
  });
764
825
  if (s.writebacks.length !== before) {
765
826
  await saveTeamAutoStore(s);
766
827
  }
828
+ // #5725 (ggcode): settle self-audit. A COMPLETED teamauto task with a
829
+ // textual result whose write-back entry is absent AND whose ok line is
830
+ // missing from the activity feed means the registration (or the whole
831
+ // entry) was lost - the ladder redundancy channel silently failed.
832
+ // Alarm once per task so the observability contract survives entry loss.
833
+ let auditDirty = false;
834
+ if (state0) {
835
+ s.orphanResultAlarms ??= {};
836
+ s.deliveredResults ??= {};
837
+ // #5738 (ggcode, 2026-11-17): ONE-TIME migration. The #5736 backfill
838
+ // only stamped entries still present in the write-back array at
839
+ // deploy time - historically delivered legs were already pruned, so
840
+ // they all re-entered the alarm domain on the first settled pass
841
+ // (23 tasks, 99 lines in 80s). Seed the ledger once from the task
842
+ // state itself: everything completed with a result inside the audit
843
+ // window at init time is treated as delivered (the sentinel verified
844
+ // those 23 were all normally delivered). Accepted trade-off: any
845
+ // genuine pre-deploy orphan is pardoned once - signal > archaeology.
846
+ if (!s.deliveredResultsInit) {
847
+ s.deliveredResultsInit = true;
848
+ for (const task of Object.values(state0.tasks ?? {})) {
849
+ if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
850
+ s.deliveredResults[task.id] = task.completedAt;
851
+ }
852
+ }
853
+ auditDirty = true;
854
+ }
855
+ for (const task of Object.values(state0.tasks ?? {})) {
856
+ if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-"))
857
+ continue;
858
+ if (task.completedAt && Date.now() - task.completedAt > 24 * 3600_000)
859
+ continue;
860
+ // #5738: once-per-task gate; the audit now persists its own
861
+ // mutations in the same pass (auditDirty save below), so the gate
862
+ // survives the next 20s disk reload instead of re-alarming.
863
+ const lastAlarmAt = s.orphanResultAlarms[task.id];
864
+ if (lastAlarmAt)
865
+ continue;
866
+ // #5736: delivered-source is the DURABLE ledger (entry present OR
867
+ // recorded at prune time) - never the activity ring, which rolls in
868
+ // hours and made every normal delivery a false orphan.
869
+ const hasEntry = s.writebacks.some((w) => w.taskId === task.id) || Boolean(s.deliveredResults[task.id]);
870
+ if (!hasEntry) {
871
+ s.orphanResultAlarms[task.id] = Date.now();
872
+ auditDirty = true;
873
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `orphan result alarm: task ${task.id} completed with a result but has NO write-back entry and no delivery record (registration lost - ladder redundancy silently absent)` });
874
+ logger.warn(`TeamAuto: orphan completed task ${task.id} without write-back entry`);
875
+ }
876
+ }
877
+ if (Object.keys(s.orphanResultAlarms).length > 200) {
878
+ const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
879
+ for (const [k] of entries.slice(0, entries.length - 100))
880
+ delete s.orphanResultAlarms[k];
881
+ }
882
+ // #5738: the gate lives on disk - persist audit mutations in the SAME
883
+ // pass that makes them, or the next 20s reload resets the gate and
884
+ // re-alarms everything (99 lines / 23 tasks live).
885
+ if (auditDirty) {
886
+ await saveTeamAutoStore(s);
887
+ }
888
+ }
767
889
  // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
768
890
  // failed-without-result tasks BEFORE the pending loop below, so the
769
891
  // terminal worktree cleanup there never ran for them - the single
@@ -795,7 +917,9 @@ export function createTeamAutoScheduler(deps) {
795
917
  for (const w of s.writebacks) {
796
918
  if (w.error && !w.doneAt && !w.failedAt && state0) {
797
919
  const t = state0.tasks[w.taskId];
798
- if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
920
+ // #5719: a FAILED task WITH a result is deliverable too (the result is
921
+ // the work product - analysis/diagnostic legs). Same backoff reset.
922
+ if (t && t.result && (t.status === "completed" || t.status === "failed") && (w.nextAttemptAt ?? 0) <= Date.now()) {
799
923
  w.error = null;
800
924
  }
801
925
  }
@@ -832,25 +956,35 @@ export function createTeamAutoScheduler(deps) {
832
956
  return;
833
957
  }
834
958
  for (const entry of pending) {
959
+ // #5685 (ggcode, 2026-11-16): gate on a TERMINAL task BEFORE touching
960
+ // the entry. The old order stamped inFlightAt first and `continue`d
961
+ // for still-running tasks, leaving the sticky intent to wedge the
962
+ // entry out of pendingAll until the 600s stale reset - a completed
963
+ // task's write-back was deliverable in exactly one 20s window every
964
+ // ~10 minutes (live: the 02:30 fullReview legs delivered 8m42s-9m51s
965
+ // after completion, long misread as deliberate "slow release"). The
966
+ // intent stamp now happens only when the pass is about to dispatch.
967
+ const task = state.tasks[entry.taskId];
968
+ if (!task || (task.status !== "completed" && task.status !== "failed")) {
969
+ continue;
970
+ }
835
971
  // #269 intent-first: persist the dispatch intent BEFORE any await so
836
972
  // an overlapping pass (or a future guard-less caller) filters this
837
973
  // entry out instead of re-delivering it.
838
974
  entry.inFlightAt = Date.now();
839
975
  await saveTeamAutoStore(s);
840
- const task = state.tasks[entry.taskId];
841
- if (!task || (task.status !== "completed" && task.status !== "failed")) {
842
- continue;
843
- }
844
976
  const repo = s.repos.find((r) => r.id === entry.repoId);
845
977
  const [owner, name] = entry.repoId.split("/");
846
978
  try {
847
- if (task.status === "failed" || !task.result) {
848
- // Undeliverable in every future pass: a failed task never gains a
849
- // result, and "completed without result" cannot recover either.
850
- // Mark terminal (issue #24) so the entry is counted, surfaced via
851
- // activity/stats, and never pointlessly retried. Failed-without-
852
- // result entries are additionally dropped by the dead-letter pass
853
- // on the next reconcile.
979
+ if (!task.result) {
980
+ // Undeliverable in every future pass: "completed without result"
981
+ // cannot recover. #5719 (ggcode, 2026-11-16): a FAILED task WITH a
982
+ // textual result is NOT in this class - the result is the
983
+ // deliverable (analysis/diagnostic work products). It now falls
984
+ // through to normal delivery with an error footer; only
985
+ // result-less entries (failed or completed) stay terminal.
986
+ // Failed-without-result entries are additionally dropped by the
987
+ // dead-letter pass on the next reconcile.
854
988
  markWritebackFailure(s, entry, task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result", { terminal: true });
855
989
  // Terminal write task: its dispatch-time worktree has no delivery
856
990
  // path left - remove it when the worker never produced deliverable
@@ -870,16 +1004,26 @@ export function createTeamAutoScheduler(deps) {
870
1004
  else {
871
1005
  const role = (task.assignedRole ?? "qa");
872
1006
  let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
1007
+ // #5719: a failed-with-result task delivers its result (the work
1008
+ // product) with the failure context appended - never silently
1009
+ // dropped as before.
1010
+ if (task.status === "failed" && task.error) {
1011
+ body = `${body}\n\n---\n[task reported failed: ${task.error.slice(0, 300)}]`;
1012
+ }
873
1013
  let writebackDone = false;
874
1014
  // WRITE TASKS (collaboration contract): commit the task worktree,
875
1015
  // push its branch, open a PR, and attach the link to the reply.
876
1016
  const repoId = entry.repoId;
877
1017
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
878
1018
  let prDeliveryFailed = false;
879
- if (isTeamAutoWrite) {
1019
+ if (isTeamAutoWrite && task.status !== "failed") {
1020
+ // #5719: a FAILED write task's worktree carries no deliverable by
1021
+ // construction (that is usually WHY it failed) - the PR step just
1022
+ // burns retries against an empty worktree. Deliver the result
1023
+ // comment directly; the worktree is cleaned by the terminal pass.
880
1024
  try {
881
1025
  const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
882
- const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
1026
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id, info.defaultBranch, info.cloneUrl);
883
1027
  const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
884
1028
  const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
885
1029
  // Workers often commit themselves inside the worktree - deliver
@@ -887,11 +1031,20 @@ export function createTeamAutoScheduler(deps) {
887
1031
  // commitAll just added new ones.
888
1032
  const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
889
1033
  if (deliverable) {
890
- await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
891
- const pr = await client.createPullRequest(repoId.split("/")[0], repoId.split("/")[1], branch, info.defaultBranch, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 120), `${task.result.trim()}\n${MARKER_FOOTER(role)}`);
892
- entry.prUrl = pr.url;
893
- body = `${body}\n\nDelivered as PR: ${pr.url}`;
894
- recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1034
+ const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
1035
+ if (push.alreadyDelivered) {
1036
+ // #stale-base follow-up: a previous incarnation already
1037
+ // delivered this branch (PR merged). Skip PR creation and
1038
+ // the retry ladder - the task's work is on the remote.
1039
+ body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
1040
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `already delivered on ${branch} - skipped duplicate push/PR` });
1041
+ }
1042
+ else {
1043
+ const pr = await client.createPullRequest(repoId.split("/")[0], repoId.split("/")[1], branch, info.defaultBranch, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 120), `${task.result.trim()}\n${MARKER_FOOTER(role)}`);
1044
+ entry.prUrl = pr.url;
1045
+ body = `${body}\n\nDelivered as PR: ${pr.url}`;
1046
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1047
+ }
895
1048
  }
896
1049
  await sync.removeTaskWorktree(repoId, task.id);
897
1050
  }
@@ -912,10 +1065,26 @@ export function createTeamAutoScheduler(deps) {
912
1065
  continue;
913
1066
  }
914
1067
  if (entry.action === "issueComment" && entry.targetId) {
915
- await client.postIssueComment(owner, name, entry.targetId, body);
916
- entry.doneAt = Date.now();
917
- entry.inFlightAt = undefined;
918
- writebackDone = true;
1068
+ // #5725 / #5660 parity: the worker may have posted the same body
1069
+ // directly during its execution window (takeOwnership legs deliver
1070
+ // an ownership-wrap comment themselves). Posting again duplicates;
1071
+ // skipping silently breaks the observability contract. Exact
1072
+ // whitespace-normalized match -> mark done + record the skip.
1073
+ const normalizedBody = body.replace(/\s+/g, " ").trim();
1074
+ const existingBodies = await client.getIssueCommentBodies(owner, name, entry.targetId);
1075
+ if (existingBodies.some((b) => b.replace(/\s+/g, " ").trim() === normalizedBody)) {
1076
+ entry.doneAt = Date.now();
1077
+ entry.inFlightAt = undefined;
1078
+ writebackDone = true;
1079
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `dedupe-skipped: identical body already on issue #${entry.targetId} (worker direct-post) - ladder posting skipped` });
1080
+ logger.info(`TeamAuto: write-back ${entry.taskId} issueComment deduped - identical body already on issue #${entry.targetId}`);
1081
+ }
1082
+ else {
1083
+ await client.postIssueComment(owner, name, entry.targetId, body);
1084
+ entry.doneAt = Date.now();
1085
+ entry.inFlightAt = undefined;
1086
+ writebackDone = true;
1087
+ }
919
1088
  // Our own comment bumps the issue's updatedAt, which the scanner
920
1089
  // treats as new activity - advance the seen cursor so we do not
921
1090
  // re-trigger a review of an object we just replied to. External
@@ -926,10 +1095,28 @@ export function createTeamAutoScheduler(deps) {
926
1095
  }
927
1096
  }
928
1097
  else if (entry.action === "prComment" && entry.targetId) {
929
- await client.postPullReviewComment(owner, name, entry.targetId, body);
930
- entry.doneAt = Date.now();
931
- entry.inFlightAt = undefined;
932
- writebackDone = true;
1098
+ // #5660 (ggcode, 2026-11-15): the worker already posted the same
1099
+ // review body directly during its execution window; the ladder
1100
+ // then delivered the IDENTICAL text 20s later - readers got the
1101
+ // review twice. Before posting, check the target's existing
1102
+ // feedback (reviews + comments, whitespace-normalized): an exact
1103
+ // match means delivery already happened through the other
1104
+ // channel - mark done and record the skip.
1105
+ const normalized = body.replace(/\s+/g, " ").trim();
1106
+ const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => []);
1107
+ if (existing.includes(normalized)) {
1108
+ entry.doneAt = Date.now();
1109
+ entry.inFlightAt = undefined;
1110
+ writebackDone = true;
1111
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `dedupe-skipped: identical review body already on PR #${entry.targetId} (worker direct-post) - ladder posting skipped` });
1112
+ logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
1113
+ }
1114
+ else {
1115
+ await client.postPullReviewComment(owner, name, entry.targetId, body);
1116
+ entry.doneAt = Date.now();
1117
+ entry.inFlightAt = undefined;
1118
+ writebackDone = true;
1119
+ }
933
1120
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
934
1121
  if (prRepo) {
935
1122
  prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
@@ -940,18 +1127,49 @@ export function createTeamAutoScheduler(deps) {
940
1127
  // (first completed section creates it, the rest post as comments).
941
1128
  const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
942
1129
  if (entry.cycleKey) {
943
- const peers = s.writebacks.filter((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
944
- const umbrella = peers[0];
945
- if (umbrella && umbrella.targetId != null) {
946
- await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
947
- entry.targetId = umbrella.targetId;
1130
+ // #5685 (ggcode, 2026-11-16): the umbrella pointer must survive
1131
+ // the end-of-pass pruning of done write-back entries (and
1132
+ // process restarts). The old lookup only saw peers delivered
1133
+ // in the SAME pass, so every cross-pass section minted its own
1134
+ // duplicate umbrella - live: cycle 20772 produced issues
1135
+ // #5686/#5687/#5688 (three "Joint full review" umbrellas,
1136
+ // zero section comments). The store map is the durable
1137
+ // pointer; an in-pass done peer remains as a fallback for
1138
+ // stores written before this fix.
1139
+ const cycleKey = `${entry.repoId}|${entry.cycleKey}`;
1140
+ s.fullReviewUmbrellas = s.fullReviewUmbrellas ?? {};
1141
+ const peerEntry = s.writebacks.find((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
1142
+ const umbrellaNumber = s.fullReviewUmbrellas[cycleKey] ?? peerEntry?.targetId ?? null;
1143
+ if (umbrellaNumber != null) {
1144
+ // Crash-retry guard: this entry may BE the creator whose
1145
+ // createIssue + umbrella-map write persisted but whose doneAt
1146
+ // did not. The umbrella body already carries its section, so
1147
+ // a creator retry completes silently instead of re-posting.
1148
+ if (entry.targetId !== umbrellaNumber) {
1149
+ await client.postIssueComment(owner, name, umbrellaNumber, sectionBody);
1150
+ }
1151
+ entry.targetId = umbrellaNumber;
1152
+ s.fullReviewUmbrellas[cycleKey] = umbrellaNumber;
948
1153
  entry.doneAt = Date.now();
949
1154
  entry.inFlightAt = undefined;
950
1155
  writebackDone = true;
1156
+ entry.deliveryNote = "section-appended-to-umbrella";
951
1157
  }
952
1158
  else if (entry.targetId == null) {
953
1159
  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"]);
954
1160
  entry.targetId = number;
1161
+ s.fullReviewUmbrellas[cycleKey] = number;
1162
+ entry.deliveryNote = "umbrella-created";
1163
+ // Persist the umbrella pointer immediately: done entries are
1164
+ // pruned at end-of-pass, and a crash between create and the
1165
+ // tail save must not lose the only record of the umbrella.
1166
+ const umbrellaKeys = Object.keys(s.fullReviewUmbrellas);
1167
+ if (umbrellaKeys.length > 100) {
1168
+ for (const staleKey of umbrellaKeys.slice(0, umbrellaKeys.length - 100)) {
1169
+ delete s.fullReviewUmbrellas[staleKey];
1170
+ }
1171
+ }
1172
+ await saveTeamAutoStore(s);
955
1173
  entry.doneAt = Date.now();
956
1174
  entry.inFlightAt = undefined;
957
1175
  writebackDone = true;
@@ -974,36 +1192,170 @@ export function createTeamAutoScheduler(deps) {
974
1192
  // does not linger in the errored/failed stats (issue #24).
975
1193
  entry.error = null;
976
1194
  entry.failedAt = null;
977
- recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id}${entry.attempts ? `, after ${entry.attempts} failed attempt(s)` : ""})` });
1195
+ // #5735: distinguish created-vs-appended so umbrella cycles stop
1196
+ // reading as double-creates (two "createIssue #N ok" lines for
1197
+ // one issue is by design: first creates, peers append sections).
1198
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok${entry.deliveryNote ? ` [${entry.deliveryNote}]` : ""} (${task.id}${entry.attempts ? `, after ${entry.attempts} failed attempt(s)` : ""})` });
978
1199
  }
979
1200
  }
980
1201
  }
981
1202
  catch (err) {
982
- markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
1203
+ const message = err instanceof Error ? err.message : String(err);
1204
+ markWritebackFailure(s, entry, message, {
1205
+ // #5704: an envelope-frame rejection is deterministic corruption -
1206
+ // the payload cannot change between attempts. Fail terminally
1207
+ // instead of burning the retry ladder re-posting the same frame.
1208
+ terminal: message.includes(ENVELOPE_LEAK_MARKER),
1209
+ });
983
1210
  }
984
1211
  void repo;
985
1212
  }
1213
+ // #5736 (ggcode): record deliveries into the durable ledger BEFORE the
1214
+ // done-entry prune - the write-back array and the tiny activity ring are
1215
+ // both short-lived, but the orphan audit runs for 24h after completion.
1216
+ // Without this, every normally-delivered task alarms as an orphan once
1217
+ // its entry is pruned and its ok line rolls off the ring.
1218
+ s.deliveredResults ??= {};
1219
+ for (const w of s.writebacks) {
1220
+ if (w.doneAt) {
1221
+ s.deliveredResults[w.taskId] = w.doneAt;
1222
+ }
1223
+ }
1224
+ const deliveredEntries = Object.entries(s.deliveredResults);
1225
+ if (deliveredEntries.length > 2000) {
1226
+ deliveredEntries.sort((a, b) => a[1] - b[1]);
1227
+ for (const [k] of deliveredEntries.slice(0, deliveredEntries.length - 1500))
1228
+ delete s.deliveredResults[k];
1229
+ }
986
1230
  s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
987
1231
  await saveTeamAutoStore(s);
988
1232
  }
989
1233
  // Register the write-back intent when a task lands in the task store.
990
- function registerWriteback(taskId, action, repoId, targetId, cycleKey) {
991
- void ensureStore().then((s) => {
992
- if (s.writebacks.some((w) => w.taskId === taskId)) {
993
- return;
1234
+ // #5643 (user report 2026-11-15): this used to be fire-and-forget
1235
+ // (void ensureStore().then(...).catch(() => {})) - the push+save raced the
1236
+ // sweep's own awaited store save AND swallowed its own errors. The 11-15
1237
+ // 02:00 batch lost ALL THREE fullReview write-back entries that way
1238
+ // (tasks + activity + "created 3/3" persisted; the entries did not), so
1239
+ // completed reviews delivered nothing, silently. Registration is now part
1240
+ // of the sweep transaction: the caller awaits it before the sweep's own
1241
+ // save, and failures propagate instead of vanishing.
1242
+ async function registerWriteback(taskId, action, repoId, targetId, cycleKey) {
1243
+ // #5712 (ggcode) / teamclaw#274: every store read-modify-write must hold
1244
+ // withStoreLock. Public entry takes the lock; the sweep transaction calls
1245
+ // the *Unlocked core directly because IT already holds the lock (the
1246
+ // promise-chain mutex is NOT re-entrant - nesting would deadlock).
1247
+ await withStoreLock(() => registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey));
1248
+ }
1249
+ async function registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey) {
1250
+ const s = await ensureStore();
1251
+ if (s.writebacks.some((w) => w.taskId === taskId)) {
1252
+ return;
1253
+ }
1254
+ // #269 per-target dedupe (enqueue side): a second registration for
1255
+ // the SAME target + action with no doneAt yet is a duplicate in the
1256
+ // making - the delivery pass would fan out two comments onto one
1257
+ // target. Skip it; the pending original still delivers the content.
1258
+ // targetId null (create* actions) cannot be target-deduped pre-delivery
1259
+ // and is excluded by the taskId check above.
1260
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1261
+ return;
1262
+ }
1263
+ s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1264
+ await saveTeamAutoStore(s);
1265
+ }
1266
+ // #claim-dequeue (user report 2026-11-15): claim at DEQUEUE time, not
1267
+ // enqueue. Enqueue-time claims locked a whole queue of issues behind the
1268
+ // one-writer-per-repo serialization while they waited; and a blind claim
1269
+ // over issues where external collaborators had begun working (comments,
1270
+ // assignees) only produced conflicts. At dequeue we re-check FRESH state:
1271
+ // - any assignee -> stand down (a human or another bot owns it)
1272
+ // - any external comment posted after the task was enqueued -> stand
1273
+ // down (someone is actively working; our own bot's comments excluded)
1274
+ // Only a quiet, unowned issue gets claimed (assign, comment fallback),
1275
+ // with the existing seen+60s self-bump guard.
1276
+ async function claimTaskAtDequeue(task) {
1277
+ const kindMatch = /^\[([^\]]+)\]/.exec(task.title);
1278
+ if (!kindMatch || kindMatch[1] !== "takeOwnership")
1279
+ return { claimed: false, reason: "not a takeOwnership task" };
1280
+ const numMatch = /issue #(\d+)/.exec(task.title);
1281
+ if (!numMatch)
1282
+ return { claimed: false, reason: "no issue number" };
1283
+ const issueNumber = Number(numMatch[1]);
1284
+ const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(task.description);
1285
+ if (!repoMatch)
1286
+ return { claimed: false, reason: "no repo in description" };
1287
+ const repoId = repoMatch[1];
1288
+ const [owner, name] = repoId.split("/");
1289
+ if (!owner || !name)
1290
+ return { claimed: false, reason: "bad repo id" };
1291
+ const client = createGithubClient(auth);
1292
+ // #5740 (ggcode, 2026-11-17): eligibility CHECK failures (fetch failed on
1293
+ // getIssue/getAuthenticatedUser/getIssueCommentsSince) must NOT let the
1294
+ // task run unclaimed - the conflict check is the core #claim-dequeue
1295
+ // contract. Only the WRITE phase (assign/comment) may continue
1296
+ // unclaimed on failure (original 2026-11-15 semantics). The caller
1297
+ // reverts the assignment on retryEligibility so the next auto-assign
1298
+ // pass re-checks; a network blip delays execution by ~20s, an outage
1299
+ // loops at assignment cadence instead of silently bypassing the gate.
1300
+ let login;
1301
+ try {
1302
+ const fresh = await client.getIssue(owner, name, issueNumber);
1303
+ if (fresh.state !== "open") {
1304
+ return { claimed: false, reason: "issue closed" };
994
1305
  }
995
- // #269 per-target dedupe (enqueue side): a second registration for
996
- // the SAME target + action with no doneAt yet is a duplicate in the
997
- // making - the delivery pass would fan out two comments onto one
998
- // target. Skip it; the pending original still delivers the content.
999
- // targetId null (create* actions) cannot be target-deduped pre-delivery
1000
- // and is excluded by the taskId check above.
1001
- if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1002
- return;
1306
+ const s0 = await ensureStore();
1307
+ const repo0 = s0.repos.find((r) => r.id === repoId);
1308
+ if ((repo0?.policy.skipAssignedToHumans ?? true) && fresh.assignees.length > 0) {
1309
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: issue #${issueNumber} has assignee(s) ${fresh.assignees.join(",")} at dequeue - standing down` });
1310
+ return { claimed: false, reason: "assignees present" };
1311
+ }
1312
+ // External-work check: comments posted after the task was ENQUEUED.
1313
+ const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
1314
+ login = (await client.getAuthenticatedUser()).login;
1315
+ const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
1316
+ const external = comments.filter((c) => c.user !== login);
1317
+ if (external.length > 0) {
1318
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: ${external.length} external comment(s) since enqueue on issue #${issueNumber} (latest by @${external[external.length - 1]?.user}) - standing down` });
1319
+ return { claimed: false, reason: "external activity" };
1003
1320
  }
1004
- s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1005
- void saveTeamAutoStore(s);
1006
- }).catch(() => { });
1321
+ }
1322
+ catch (err) {
1323
+ const msg = err instanceof Error ? err.message : String(err);
1324
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue ELIGIBILITY CHECK failed for issue #${issueNumber}: ${msg.slice(0, 120)} - reverting assignment, will retry` });
1325
+ return { claimed: false, reason: "eligibility-check-failed", retryEligibility: true };
1326
+ }
1327
+ // #5740 (ggcode, 2026-11-17): the WRITE phase keeps the original
1328
+ // 2026-11-15 "continue unclaimed" semantics when it fails (the
1329
+ // eligibility checks DID pass), but it must not vanish silently - the
1330
+ // caller swallows rejections - so record the audit line here and return
1331
+ // a non-retrying result.
1332
+ try {
1333
+ try {
1334
+ await client.assignIssue(owner, name, issueNumber, login);
1335
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} as @${login} (at dequeue)` });
1336
+ }
1337
+ catch {
1338
+ // Fallback: a visible claim comment carries the same placeholder
1339
+ // semantics when the App lacks the assignees write surface.
1340
+ await client.postIssueComment(owner, name, issueNumber, `TeamClaw (teamclaw/developer, @${login}) has taken ownership of this issue and is implementing it autonomously - a PR will follow.`);
1341
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)` });
1342
+ }
1343
+ const s = await ensureStore();
1344
+ await withStoreLock(async () => {
1345
+ const freshRepo = s.repos.find((r) => r.id === repoId);
1346
+ if (freshRepo) {
1347
+ // +60s guard: our own write (assign or comment) bumps updated_at.
1348
+ freshRepo.cursors.seen[`${repoId}#issue-${issueNumber}`] = Date.now() + 60_000;
1349
+ await saveTeamAutoStore(s);
1350
+ }
1351
+ });
1352
+ return { claimed: true };
1353
+ }
1354
+ catch (err) {
1355
+ const msg = err instanceof Error ? err.message : String(err);
1356
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue WRITE failed for issue #${issueNumber}: ${msg.slice(0, 120)} - continuing unclaimed` });
1357
+ return { claimed: false, reason: "claim write failed" };
1358
+ }
1007
1359
  }
1008
1360
  /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
1009
1361
  * assignIssue was dead code and registerWriteback had no assign action, so
@@ -1048,13 +1400,15 @@ export function createTeamAutoScheduler(deps) {
1048
1400
  recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1049
1401
  }
1050
1402
  const s = await ensureStore();
1051
- const freshRepo = s.repos.find((r) => r.id === repo.id);
1052
- if (freshRepo) {
1053
- // +60s guard: our own write (assign or comment) bumps updated_at;
1054
- // see helper doc.
1055
- freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1056
- await saveTeamAutoStore(s);
1057
- }
1403
+ await withStoreLock(async () => {
1404
+ const freshRepo = s.repos.find((r) => r.id === repo.id);
1405
+ if (freshRepo) {
1406
+ // +60s guard: our own write (assign or comment) bumps updated_at;
1407
+ // see helper doc.
1408
+ freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1409
+ await saveTeamAutoStore(s);
1410
+ }
1411
+ });
1058
1412
  }
1059
1413
  catch (err) {
1060
1414
  logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
@@ -1199,60 +1553,79 @@ export function createTeamAutoScheduler(deps) {
1199
1553
  void recoverFailedClaims();
1200
1554
  }, 60_000);
1201
1555
  claimRecoveryTimer.unref?.();
1202
- // Boot reconciliation: heal leftover task worktrees whose task is
1203
- // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
1204
- // on its own. Safety-checked: undelivered work is kept and logged.
1205
- void (async () => {
1206
- try {
1207
- // #173 follow-up 3: with getTeamState() === null the isTerminal
1208
- // predicate below classifies EVERY task as terminal - boot GC must
1209
- // not run blind over an unloaded team state (fails toward skip).
1210
- if (!deps.getTeamState()) {
1211
- logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1212
- return;
1213
- }
1214
- let removed = 0;
1215
- let retained = 0;
1216
- let stale = 0;
1217
- const retainedDetails = [];
1218
- for (const repo of s.repos) {
1219
- if (!repo.enabled)
1220
- continue;
1221
- const isTerminal = (taskId) => {
1222
- const t = deps.getTeamState()?.tasks[taskId];
1223
- if (t && t.status !== "completed" && t.status !== "failed")
1224
- return false;
1225
- // Review F1: a terminal task with a pending write-back (push
1226
- // ok / PR failed, 20s-retry window) still needs its worktree -
1227
- // the retry delivers the PR from the surviving branch. Do not
1228
- // GC until the write-back settles (doneAt or dropped). Issue
1229
- // #24: terminally failed write-backs (failedAt) count as settled
1230
- // too - safeRemoveTaskWorktree still retains unpushed work.
1231
- return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1232
- };
1233
- const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle);
1234
- removed += r.removed.length;
1235
- retained += r.retained.length;
1236
- stale += r.stale;
1237
- retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1238
- }
1239
- if (removed || retained || stale) {
1240
- // #173 follow-up 4: per-task retain reasons recorded as activity
1241
- // (PR #167 promised "outcome logged + recorded as activity"); the
1242
- // stale count surfaces dir-gone-but-branch-kept leaks too.
1243
- const detail = retainedDetails.length
1244
- ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1245
- : "";
1246
- const stalePart = stale ? `, stale ${stale}` : "";
1247
- recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1248
- await saveTeamAutoStore(s);
1249
- logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1250
- }
1556
+ // #gc-periodic: worktree GC used to be boot-only with an enabled-repo
1557
+ // filter - two defects (live-instance audit 2026-11-14): (a) a disabled
1558
+ // repo ("do no NEW work") never got cleaned at all; (b) the single boot
1559
+ // pass ran before the device-flow auth warmed up, so every targetClosed
1560
+ // oracle call failed toward keep and closed-target orphans stayed (4
1561
+ // confirmed misretains). Now a recurring pass: first run delayed 60s
1562
+ // (auth warm), then every 6h - transient oracle failures self-heal on
1563
+ // the next pass.
1564
+ const gcDelay = setTimeout(() => {
1565
+ void runGcPass();
1566
+ gcTimer = setInterval(() => {
1567
+ void runGcPass();
1568
+ }, 6 * 60 * 60_000);
1569
+ gcTimer.unref?.();
1570
+ }, 60_000);
1571
+ gcDelay.unref?.();
1572
+ }
1573
+ /** #gc-periodic: one full worktree GC pass over ALL bound repos (enabled
1574
+ * or not - GC is hygiene, not new work). Shared by the boot-delayed first
1575
+ * run and the 6h recurrence. */
1576
+ async function runGcPass() {
1577
+ try {
1578
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
1579
+ // predicate below classifies EVERY task as terminal - GC must not run
1580
+ // blind over an unloaded team state (fails toward skip).
1581
+ if (!deps.getTeamState()) {
1582
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1583
+ return;
1251
1584
  }
1252
- catch (err) {
1253
- logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
1585
+ const s = await ensureStore();
1586
+ let removed = 0;
1587
+ let retained = 0;
1588
+ let stale = 0;
1589
+ const retainedDetails = [];
1590
+ for (const repo of s.repos) {
1591
+ const isTerminal = (taskId) => {
1592
+ const t = deps.getTeamState()?.tasks[taskId];
1593
+ if (t && t.status !== "completed" && t.status !== "failed")
1594
+ return false;
1595
+ // Review F1: a terminal task with a pending write-back (push
1596
+ // ok / PR failed, 20s-retry window) still needs its worktree -
1597
+ // the retry delivers the PR from the surviving branch. Do not
1598
+ // GC until the write-back settles (doneAt or dropped). Issue
1599
+ // #24: terminally failed write-backs (failedAt) count as settled
1600
+ // too - safeRemoveTaskWorktree still retains unpushed work.
1601
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1602
+ };
1603
+ // #gc3: no task record anywhere in team-state -> the owner ruled
1604
+ // outright deletion (2026-11-14, "全删") - such worktrees can never
1605
+ // be judged by any oracle and were retained forever.
1606
+ const isUnknownTask = (taskId) => !deps.getTeamState()?.tasks?.[taskId];
1607
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle, isUnknownTask);
1608
+ removed += r.removed.length;
1609
+ retained += r.retained.length;
1610
+ stale += r.stale;
1611
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1254
1612
  }
1255
- })();
1613
+ if (removed || retained || stale) {
1614
+ // #173 follow-up 4: per-task retain reasons recorded as activity
1615
+ // (PR #167 promised "outcome logged + recorded as activity"); the
1616
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
1617
+ const detail = retainedDetails.length
1618
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1619
+ : "";
1620
+ const stalePart = stale ? `, stale ${stale}` : "";
1621
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1622
+ await saveTeamAutoStore(s);
1623
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1624
+ }
1625
+ }
1626
+ catch (err) {
1627
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
1628
+ }
1256
1629
  }
1257
1630
  async function stop() {
1258
1631
  running = false;
@@ -1265,6 +1638,9 @@ export function createTeamAutoScheduler(deps) {
1265
1638
  if (claimRecoveryTimer) {
1266
1639
  clearInterval(claimRecoveryTimer);
1267
1640
  }
1641
+ if (gcTimer) {
1642
+ clearInterval(gcTimer);
1643
+ }
1268
1644
  writebackTimer = null;
1269
1645
  }
1270
1646
  }
@@ -1279,7 +1655,7 @@ export function createTeamAutoScheduler(deps) {
1279
1655
  const s = await ensureStore();
1280
1656
  return (s.activity ?? []).slice().reverse();
1281
1657
  }
1282
- return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
1658
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, claimTaskAtDequeue, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
1283
1659
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
1284
1660
  async function ensureWriteWorktree(repoId, taskId) {
1285
1661
  const wtAbs = await sync.ensureTaskWorktree(repoId, taskId);