@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
@@ -12,9 +12,11 @@ import type { TaskInfo, TeamState } from "../types.js";
12
12
  import { createGithubClient } from "./github-client.js";
13
13
  import { learnNorms, renderNormsBlock } from "./norms.js";
14
14
  import { createRepoSync, teamAutoProjectDir, type TaskDeliveryOracle, type TaskTargetClosedOracle } from "./repo-sync.js";
15
+ import { ENVELOPE_LEAK_MARKER } from "./write-payload-guard.js";
15
16
  import { nextFireMs } from "./schedule.js";
16
17
  import { resolveTeamAutoPaths } from "./store.js";
17
18
  import { advanceCursors, sweepRepo, type Candidate } from "./scanner.js";
19
+ import { withStoreLock } from "./store.js";
18
20
  import {
19
21
  consumeDailyBudget,
20
22
  defaultCursors,
@@ -242,7 +244,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
242
244
  entry.attempts = (entry.attempts ?? 0) + 1;
243
245
  entry.lastErrorAt = Date.now();
244
246
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
245
- const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
247
+ // #5651: a non-fast-forward push whose rebase self-heal also failed is
248
+ // deterministic - retrying the same push 6 more times just burns ~25min.
249
+ // Dead-letter immediately (the next sweep re-claims on a fresh branch).
250
+ const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS || /push rejected \(non-fast-forward\) and rebase self-heal failed/.test(message);
246
251
  if (gaveUp && !entry.doneAt) {
247
252
  entry.failedAt = Date.now();
248
253
  recordActivity(store, {
@@ -359,6 +364,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
359
364
  let store: TeamAutoStore | null = null;
360
365
  let writebackTimer: NodeJS.Timeout | null = null;
361
366
  let claimRecoveryTimer: NodeJS.Timeout | null = null;
367
+ let gcTimer: NodeJS.Timeout | null = null;
362
368
 
363
369
  async function ensureStore(): Promise<TeamAutoStore> {
364
370
  if (!store) {
@@ -534,6 +540,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
534
540
  for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
535
541
  try {
536
542
  swept = await sweepRepo(repo, client);
543
+ // #5706 (ggcode): sweep observability - "no new work" is ambiguous
544
+ // between an empty fetch (etag 304 / API silence) and full filter
545
+ // rejection. Log the funnel so starvation diagnoses itself.
546
+ 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"})`);
537
547
  break;
538
548
  } catch (err) {
539
549
  if (classifySweepError(err) !== "network") {
@@ -559,6 +569,17 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
559
569
  // -> still zero candidates -> dryRunDone never set).
560
570
  repo.dryRunDone = true;
561
571
  }
572
+ // #5712 (ggcode) / teamclaw#274: the ENTIRE sweep store transaction -
573
+ // cursor/seen advance, budget consume, task activity, write-back
574
+ // registrations, summary, sweep record, and the commit save - is one
575
+ // read-modify-write section. It previously raced the (locked) 20s
576
+ // write-back reconcile: reconcile's disk reload + tail save clobbered
577
+ // the sweep's writes (live: 20:30 batch lost summary/budget/activity
578
+ // while later claim/write-back saves survived). registerWriteback
579
+ // inside uses the *Unlocked core - the promise-chain mutex is NOT
580
+ // re-entrant.
581
+ let created = 0; // #5712: outside the lock scope - read after commit
582
+ await withStoreLock(async () => {
562
583
  if (!dryRun) {
563
584
  // Advance only for acting sweeps: a dry-run must leave the cursors
564
585
  // untouched so the reported actions are actually performed next time
@@ -572,7 +593,6 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
572
593
  const fullReviews = candidates.filter((c) => c.kind === "fullReview");
573
594
  const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
574
595
  const capped = [...fullReviews, ...regular];
575
- let created = 0;
576
596
  const summary: string[] = [`found ${candidates.length} candidate(s)`];
577
597
  // #265: surface the commits delta so the third signal source is
578
598
  // observable in sweep summaries (was silently dead before).
@@ -593,23 +613,34 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
593
613
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
594
614
  } else if (taskId) {
595
615
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
596
- claimIssue(repo, candidate); // #268: visible claim at enqueue time
616
+ // #claim-dequeue (user 2026-11-15): claiming at ENQUEUE locked a
617
+ // string of issues behind the one-writer-per-repo queue while
618
+ // they waited - and blindly claimed issues where external
619
+ // collaborators had started working in the scan-to-claim gap.
620
+ // Claiming now happens at DEQUEUE (claimTaskAtDequeue, called
621
+ // from the task assignment path) after a fresh conflict check.
597
622
  const action = candidate.kind === "prReview"
598
623
  ? ("prComment" as const)
599
624
  : candidate.kind === "fullReview"
600
625
  ? ("createIssue" as const)
601
- : ("issueComment" as const);
602
- registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
626
+ : candidate.kind === "prRework"
627
+ ? ("prComment" as const)
628
+ : ("issueComment" as const);
629
+ await registerWritebackUnlocked(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
603
630
  created++;
604
631
  }
605
632
  }
606
- repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
633
+ const failedSince = repo.failedTasksSinceLastSweep ?? 0;
634
+ repo.failedTasksSinceLastSweep = 0;
635
+ repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
607
636
  if (capped.some((c) => c.kind === "fullReview")) {
608
637
  repo.cursors.lastFullReviewAt = Date.now();
609
638
  }
610
639
  }
611
640
  } else {
612
- repo.lastSweepSummary = "no new work";
641
+ const failedSince0 = repo.failedTasksSinceLastSweep ?? 0;
642
+ repo.failedTasksSinceLastSweep = 0;
643
+ repo.lastSweepSummary = failedSince0 > 0 ? `no new work; FAILED ${failedSince0} since last sweep` : "no new work";
613
644
  }
614
645
  repo.lastSweepAt = Date.now();
615
646
  if (isAutoPause(repo.pausedReason)) {
@@ -622,6 +653,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
622
653
  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) });
623
654
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
624
655
  await saveTeamAutoStore(s);
656
+ }); // withStoreLock: sweep transaction
625
657
  if (created > 0) {
626
658
  await deps.onTasksCreated().catch((err) => {
627
659
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
@@ -635,6 +667,8 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
635
667
  // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
636
668
  // failed". Auto-pauses are cooldowns now: the timer retries after the
637
669
  // backoff below, and a success clears the state in the block above.
670
+ // #5712: failure bookkeeping is a store RMW too - same lock.
671
+ await withStoreLock(async () => {
638
672
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
639
673
  repo.lastSweepErrorAt = Date.now();
640
674
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
@@ -644,6 +678,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
644
678
  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) });
645
679
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
646
680
  await saveTeamAutoStore(s).catch(() => {});
681
+ }); // withStoreLock: failure bookkeeping
647
682
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
648
683
  return `error: ${message}`;
649
684
  } finally {
@@ -820,6 +855,25 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
820
855
  }
821
856
 
822
857
  async function doReconcileWritebacks(): Promise<void> {
858
+ // #2677: the WHOLE read-modify-write section holds the store lock -
859
+ // an unlocked reload+save here clobbered a concurrently-registered
860
+ // write-back entry (see store.ts withStoreLock).
861
+ await withStoreLock(async () => {
862
+ await doReconcileWritebacksLocked();
863
+ }).catch((err) => {
864
+ // #5677 ask: never swallow a delivery-pass crash silently - a lost
865
+ // entry with zero trace is invisible; surface it in the log AND the
866
+ // activity feed so the failure class is diagnosable.
867
+ const msg = err instanceof Error ? err.message : String(err);
868
+ logger.warn(`TeamAuto: write-back pass CRASHED (entries may retry next tick): ${msg}`);
869
+ void ensureStore().then((s) => {
870
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `delivery pass crashed: ${msg.slice(0, 140)}` });
871
+ return saveTeamAutoStore(s);
872
+ }).catch(() => {});
873
+ });
874
+ }
875
+
876
+ async function doReconcileWritebacksLocked(): Promise<void> {
823
877
  // #269 recurrence: re-read the store from disk EVERY pass - the
824
878
  // closure cache is a startup snapshot that never sees another
825
879
  // process's persisted inFlightAt/doneAt, which is exactly how the
@@ -839,10 +893,73 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
839
893
  if (dead) {
840
894
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
841
895
  deadOnes.push(w);
896
+ // #5641: the 3-day architect-leg outage was invisible because a
897
+ // failed-without-result task produced NO activity line and the next
898
+ // sweep summary still said "created 3/3". Record both surfaces.
899
+ 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)})` : ""}` });
900
+ const failedRepo = s.repos.find((r) => r.id === w.repoId);
901
+ if (failedRepo) {
902
+ failedRepo.failedTasksSinceLastSweep = (failedRepo.failedTasksSinceLastSweep ?? 0) + 1;
903
+ }
842
904
  }
843
905
  return !dead;
844
906
  });
845
907
  if (s.writebacks.length !== before) { await saveTeamAutoStore(s); }
908
+ // #5725 (ggcode): settle self-audit. A COMPLETED teamauto task with a
909
+ // textual result whose write-back entry is absent AND whose ok line is
910
+ // missing from the activity feed means the registration (or the whole
911
+ // entry) was lost - the ladder redundancy channel silently failed.
912
+ // Alarm once per task so the observability contract survives entry loss.
913
+ let auditDirty = false;
914
+ if (state0) {
915
+ s.orphanResultAlarms ??= {};
916
+ s.deliveredResults ??= {};
917
+ // #5738 (ggcode, 2026-11-17): ONE-TIME migration. The #5736 backfill
918
+ // only stamped entries still present in the write-back array at
919
+ // deploy time - historically delivered legs were already pruned, so
920
+ // they all re-entered the alarm domain on the first settled pass
921
+ // (23 tasks, 99 lines in 80s). Seed the ledger once from the task
922
+ // state itself: everything completed with a result inside the audit
923
+ // window at init time is treated as delivered (the sentinel verified
924
+ // those 23 were all normally delivered). Accepted trade-off: any
925
+ // genuine pre-deploy orphan is pardoned once - signal > archaeology.
926
+ if (!s.deliveredResultsInit) {
927
+ s.deliveredResultsInit = true;
928
+ for (const task of Object.values(state0.tasks ?? {})) {
929
+ if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
930
+ s.deliveredResults[task.id] = task.completedAt;
931
+ }
932
+ }
933
+ auditDirty = true;
934
+ }
935
+ for (const task of Object.values(state0.tasks ?? {})) {
936
+ if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-")) continue;
937
+ if (task.completedAt && Date.now() - task.completedAt > 24 * 3600_000) continue;
938
+ // #5738: once-per-task gate; the audit now persists its own
939
+ // mutations in the same pass (auditDirty save below), so the gate
940
+ // survives the next 20s disk reload instead of re-alarming.
941
+ const lastAlarmAt = s.orphanResultAlarms[task.id];
942
+ if (lastAlarmAt) continue;
943
+ // #5736: delivered-source is the DURABLE ledger (entry present OR
944
+ // recorded at prune time) - never the activity ring, which rolls in
945
+ // hours and made every normal delivery a false orphan.
946
+ const hasEntry = s.writebacks.some((w) => w.taskId === task.id) || Boolean(s.deliveredResults[task.id]);
947
+ if (!hasEntry) {
948
+ s.orphanResultAlarms[task.id] = Date.now();
949
+ auditDirty = true;
950
+ 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)` });
951
+ logger.warn(`TeamAuto: orphan completed task ${task.id} without write-back entry`);
952
+ }
953
+ }
954
+ if (Object.keys(s.orphanResultAlarms).length > 200) {
955
+ const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
956
+ for (const [k] of entries.slice(0, entries.length - 100)) delete s.orphanResultAlarms[k];
957
+ }
958
+ // #5738: the gate lives on disk - persist audit mutations in the SAME
959
+ // pass that makes them, or the next 20s reload resets the gate and
960
+ // re-alarms everything (99 lines / 23 tasks live).
961
+ if (auditDirty) { await saveTeamAutoStore(s); }
962
+ }
846
963
  // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
847
964
  // failed-without-result tasks BEFORE the pending loop below, so the
848
965
  // terminal worktree cleanup there never ran for them - the single
@@ -873,7 +990,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
873
990
  for (const w of s.writebacks) {
874
991
  if (w.error && !w.doneAt && !w.failedAt && state0) {
875
992
  const t = state0.tasks[w.taskId];
876
- if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
993
+ // #5719: a FAILED task WITH a result is deliverable too (the result is
994
+ // the work product - analysis/diagnostic legs). Same backoff reset.
995
+ if (t && t.result && (t.status === "completed" || t.status === "failed") && (w.nextAttemptAt ?? 0) <= Date.now()) {
877
996
  w.error = null;
878
997
  }
879
998
  }
@@ -910,25 +1029,35 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
910
1029
  return;
911
1030
  }
912
1031
  for (const entry of pending) {
1032
+ // #5685 (ggcode, 2026-11-16): gate on a TERMINAL task BEFORE touching
1033
+ // the entry. The old order stamped inFlightAt first and `continue`d
1034
+ // for still-running tasks, leaving the sticky intent to wedge the
1035
+ // entry out of pendingAll until the 600s stale reset - a completed
1036
+ // task's write-back was deliverable in exactly one 20s window every
1037
+ // ~10 minutes (live: the 02:30 fullReview legs delivered 8m42s-9m51s
1038
+ // after completion, long misread as deliberate "slow release"). The
1039
+ // intent stamp now happens only when the pass is about to dispatch.
1040
+ const task = state.tasks[entry.taskId];
1041
+ if (!task || (task.status !== "completed" && task.status !== "failed")) {
1042
+ continue;
1043
+ }
913
1044
  // #269 intent-first: persist the dispatch intent BEFORE any await so
914
1045
  // an overlapping pass (or a future guard-less caller) filters this
915
1046
  // entry out instead of re-delivering it.
916
1047
  entry.inFlightAt = Date.now();
917
1048
  await saveTeamAutoStore(s);
918
- const task = state.tasks[entry.taskId];
919
- if (!task || (task.status !== "completed" && task.status !== "failed")) {
920
- continue;
921
- }
922
1049
  const repo = s.repos.find((r) => r.id === entry.repoId);
923
1050
  const [owner, name] = entry.repoId.split("/");
924
1051
  try {
925
- if (task.status === "failed" || !task.result) {
926
- // Undeliverable in every future pass: a failed task never gains a
927
- // result, and "completed without result" cannot recover either.
928
- // Mark terminal (issue #24) so the entry is counted, surfaced via
929
- // activity/stats, and never pointlessly retried. Failed-without-
930
- // result entries are additionally dropped by the dead-letter pass
931
- // on the next reconcile.
1052
+ if (!task.result) {
1053
+ // Undeliverable in every future pass: "completed without result"
1054
+ // cannot recover. #5719 (ggcode, 2026-11-16): a FAILED task WITH a
1055
+ // textual result is NOT in this class - the result is the
1056
+ // deliverable (analysis/diagnostic work products). It now falls
1057
+ // through to normal delivery with an error footer; only
1058
+ // result-less entries (failed or completed) stay terminal.
1059
+ // Failed-without-result entries are additionally dropped by the
1060
+ // dead-letter pass on the next reconcile.
932
1061
  markWritebackFailure(
933
1062
  s,
934
1063
  entry,
@@ -951,16 +1080,26 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
951
1080
  } else {
952
1081
  const role = (task.assignedRole ?? "qa") as string;
953
1082
  let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
1083
+ // #5719: a failed-with-result task delivers its result (the work
1084
+ // product) with the failure context appended - never silently
1085
+ // dropped as before.
1086
+ if (task.status === "failed" && task.error) {
1087
+ body = `${body}\n\n---\n[task reported failed: ${task.error.slice(0, 300)}]`;
1088
+ }
954
1089
  let writebackDone = false;
955
1090
  // WRITE TASKS (collaboration contract): commit the task worktree,
956
1091
  // push its branch, open a PR, and attach the link to the reply.
957
1092
  const repoId = entry.repoId;
958
1093
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
959
1094
  let prDeliveryFailed = false;
960
- if (isTeamAutoWrite) {
1095
+ if (isTeamAutoWrite && task.status !== "failed") {
1096
+ // #5719: a FAILED write task's worktree carries no deliverable by
1097
+ // construction (that is usually WHY it failed) - the PR step just
1098
+ // burns retries against an empty worktree. Deliver the result
1099
+ // comment directly; the worktree is cleaned by the terminal pass.
961
1100
  try {
962
1101
  const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
963
- const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
1102
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id, info.defaultBranch, info.cloneUrl);
964
1103
  const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
965
1104
  const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
966
1105
  // Workers often commit themselves inside the worktree - deliver
@@ -968,11 +1107,19 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
968
1107
  // commitAll just added new ones.
969
1108
  const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
970
1109
  if (deliverable) {
971
- await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
972
- 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)}`);
973
- entry.prUrl = pr.url;
974
- body = `${body}\n\nDelivered as PR: ${pr.url}`;
975
- recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1110
+ const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
1111
+ if (push.alreadyDelivered) {
1112
+ // #stale-base follow-up: a previous incarnation already
1113
+ // delivered this branch (PR merged). Skip PR creation and
1114
+ // the retry ladder - the task's work is on the remote.
1115
+ body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
1116
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `already delivered on ${branch} - skipped duplicate push/PR` });
1117
+ } else {
1118
+ 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)}`);
1119
+ entry.prUrl = pr.url;
1120
+ body = `${body}\n\nDelivered as PR: ${pr.url}`;
1121
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1122
+ }
976
1123
  }
977
1124
  await sync.removeTaskWorktree(repoId, task.id);
978
1125
  } catch (prErr) {
@@ -992,10 +1139,25 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
992
1139
  continue;
993
1140
  }
994
1141
  if (entry.action === "issueComment" && entry.targetId) {
1142
+ // #5725 / #5660 parity: the worker may have posted the same body
1143
+ // directly during its execution window (takeOwnership legs deliver
1144
+ // an ownership-wrap comment themselves). Posting again duplicates;
1145
+ // skipping silently breaks the observability contract. Exact
1146
+ // whitespace-normalized match -> mark done + record the skip.
1147
+ const normalizedBody = body.replace(/\s+/g, " ").trim();
1148
+ const existingBodies = await client.getIssueCommentBodies(owner, name, entry.targetId);
1149
+ if (existingBodies.some((b) => b.replace(/\s+/g, " ").trim() === normalizedBody)) {
1150
+ entry.doneAt = Date.now();
1151
+ entry.inFlightAt = undefined;
1152
+ writebackDone = true;
1153
+ 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` });
1154
+ logger.info(`TeamAuto: write-back ${entry.taskId} issueComment deduped - identical body already on issue #${entry.targetId}`);
1155
+ } else {
995
1156
  await client.postIssueComment(owner, name, entry.targetId, body);
996
1157
  entry.doneAt = Date.now();
997
1158
  entry.inFlightAt = undefined;
998
1159
  writebackDone = true;
1160
+ }
999
1161
  // Our own comment bumps the issue's updatedAt, which the scanner
1000
1162
  // treats as new activity - advance the seen cursor so we do not
1001
1163
  // re-trigger a review of an object we just replied to. External
@@ -1005,10 +1167,27 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1005
1167
  issueRepo.cursors.seen[`${entry.repoId}#issue-${entry.targetId}`] = Date.now();
1006
1168
  }
1007
1169
  } else if (entry.action === "prComment" && entry.targetId) {
1008
- await client.postPullReviewComment(owner, name, entry.targetId, body);
1009
- entry.doneAt = Date.now();
1010
- entry.inFlightAt = undefined;
1011
- writebackDone = true;
1170
+ // #5660 (ggcode, 2026-11-15): the worker already posted the same
1171
+ // review body directly during its execution window; the ladder
1172
+ // then delivered the IDENTICAL text 20s later - readers got the
1173
+ // review twice. Before posting, check the target's existing
1174
+ // feedback (reviews + comments, whitespace-normalized): an exact
1175
+ // match means delivery already happened through the other
1176
+ // channel - mark done and record the skip.
1177
+ const normalized = body.replace(/\s+/g, " ").trim();
1178
+ const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => [] as string[]);
1179
+ if (existing.includes(normalized)) {
1180
+ entry.doneAt = Date.now();
1181
+ entry.inFlightAt = undefined;
1182
+ writebackDone = true;
1183
+ 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` });
1184
+ logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
1185
+ } else {
1186
+ await client.postPullReviewComment(owner, name, entry.targetId, body);
1187
+ entry.doneAt = Date.now();
1188
+ entry.inFlightAt = undefined;
1189
+ writebackDone = true;
1190
+ }
1012
1191
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
1013
1192
  if (prRepo) {
1014
1193
  prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
@@ -1018,14 +1197,33 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1018
1197
  // (first completed section creates it, the rest post as comments).
1019
1198
  const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
1020
1199
  if (entry.cycleKey) {
1021
- const peers = s.writebacks.filter((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
1022
- const umbrella = peers[0];
1023
- if (umbrella && umbrella.targetId != null) {
1024
- await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
1025
- entry.targetId = umbrella.targetId;
1200
+ // #5685 (ggcode, 2026-11-16): the umbrella pointer must survive
1201
+ // the end-of-pass pruning of done write-back entries (and
1202
+ // process restarts). The old lookup only saw peers delivered
1203
+ // in the SAME pass, so every cross-pass section minted its own
1204
+ // duplicate umbrella - live: cycle 20772 produced issues
1205
+ // #5686/#5687/#5688 (three "Joint full review" umbrellas,
1206
+ // zero section comments). The store map is the durable
1207
+ // pointer; an in-pass done peer remains as a fallback for
1208
+ // stores written before this fix.
1209
+ const cycleKey = `${entry.repoId}|${entry.cycleKey}`;
1210
+ s.fullReviewUmbrellas = s.fullReviewUmbrellas ?? {};
1211
+ const peerEntry = s.writebacks.find((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
1212
+ const umbrellaNumber = s.fullReviewUmbrellas[cycleKey] ?? peerEntry?.targetId ?? null;
1213
+ if (umbrellaNumber != null) {
1214
+ // Crash-retry guard: this entry may BE the creator whose
1215
+ // createIssue + umbrella-map write persisted but whose doneAt
1216
+ // did not. The umbrella body already carries its section, so
1217
+ // a creator retry completes silently instead of re-posting.
1218
+ if (entry.targetId !== umbrellaNumber) {
1219
+ await client.postIssueComment(owner, name, umbrellaNumber, sectionBody);
1220
+ }
1221
+ entry.targetId = umbrellaNumber;
1222
+ s.fullReviewUmbrellas[cycleKey] = umbrellaNumber;
1026
1223
  entry.doneAt = Date.now();
1027
1224
  entry.inFlightAt = undefined;
1028
1225
  writebackDone = true;
1226
+ entry.deliveryNote = "section-appended-to-umbrella";
1029
1227
  } else if (entry.targetId == null) {
1030
1228
  const number = await client.createIssue(
1031
1229
  owner,
@@ -1035,6 +1233,18 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1035
1233
  ["teamclaw", "teamclaw:fullreview"],
1036
1234
  );
1037
1235
  entry.targetId = number;
1236
+ s.fullReviewUmbrellas[cycleKey] = number;
1237
+ entry.deliveryNote = "umbrella-created";
1238
+ // Persist the umbrella pointer immediately: done entries are
1239
+ // pruned at end-of-pass, and a crash between create and the
1240
+ // tail save must not lose the only record of the umbrella.
1241
+ const umbrellaKeys = Object.keys(s.fullReviewUmbrellas);
1242
+ if (umbrellaKeys.length > 100) {
1243
+ for (const staleKey of umbrellaKeys.slice(0, umbrellaKeys.length - 100)) {
1244
+ delete s.fullReviewUmbrellas[staleKey];
1245
+ }
1246
+ }
1247
+ await saveTeamAutoStore(s);
1038
1248
  entry.doneAt = Date.now();
1039
1249
  entry.inFlightAt = undefined;
1040
1250
  writebackDone = true;
@@ -1055,36 +1265,169 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1055
1265
  // does not linger in the errored/failed stats (issue #24).
1056
1266
  entry.error = null;
1057
1267
  entry.failedAt = null;
1058
- 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)` : ""})` });
1268
+ // #5735: distinguish created-vs-appended so umbrella cycles stop
1269
+ // reading as double-creates (two "createIssue #N ok" lines for
1270
+ // one issue is by design: first creates, peers append sections).
1271
+ 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)` : ""})` });
1059
1272
  }
1060
1273
  }
1061
1274
  } catch (err) {
1062
- markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
1275
+ const message = err instanceof Error ? err.message : String(err);
1276
+ markWritebackFailure(s, entry, message, {
1277
+ // #5704: an envelope-frame rejection is deterministic corruption -
1278
+ // the payload cannot change between attempts. Fail terminally
1279
+ // instead of burning the retry ladder re-posting the same frame.
1280
+ terminal: message.includes(ENVELOPE_LEAK_MARKER),
1281
+ });
1063
1282
  }
1064
1283
  void repo;
1065
1284
  }
1285
+ // #5736 (ggcode): record deliveries into the durable ledger BEFORE the
1286
+ // done-entry prune - the write-back array and the tiny activity ring are
1287
+ // both short-lived, but the orphan audit runs for 24h after completion.
1288
+ // Without this, every normally-delivered task alarms as an orphan once
1289
+ // its entry is pruned and its ok line rolls off the ring.
1290
+ s.deliveredResults ??= {};
1291
+ for (const w of s.writebacks) {
1292
+ if (w.doneAt) {
1293
+ s.deliveredResults[w.taskId] = w.doneAt;
1294
+ }
1295
+ }
1296
+ const deliveredEntries = Object.entries(s.deliveredResults);
1297
+ if (deliveredEntries.length > 2000) {
1298
+ deliveredEntries.sort((a, b) => a[1] - b[1]);
1299
+ for (const [k] of deliveredEntries.slice(0, deliveredEntries.length - 1500)) delete s.deliveredResults[k];
1300
+ }
1066
1301
  s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
1067
1302
  await saveTeamAutoStore(s);
1068
1303
  }
1069
1304
 
1070
1305
  // Register the write-back intent when a task lands in the task store.
1071
- function registerWriteback(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): void {
1072
- void ensureStore().then((s) => {
1073
- if (s.writebacks.some((w) => w.taskId === taskId)) {
1074
- return;
1306
+ // #5643 (user report 2026-11-15): this used to be fire-and-forget
1307
+ // (void ensureStore().then(...).catch(() => {})) - the push+save raced the
1308
+ // sweep's own awaited store save AND swallowed its own errors. The 11-15
1309
+ // 02:00 batch lost ALL THREE fullReview write-back entries that way
1310
+ // (tasks + activity + "created 3/3" persisted; the entries did not), so
1311
+ // completed reviews delivered nothing, silently. Registration is now part
1312
+ // of the sweep transaction: the caller awaits it before the sweep's own
1313
+ // save, and failures propagate instead of vanishing.
1314
+ async function registerWriteback(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): Promise<void> {
1315
+ // #5712 (ggcode) / teamclaw#274: every store read-modify-write must hold
1316
+ // withStoreLock. Public entry takes the lock; the sweep transaction calls
1317
+ // the *Unlocked core directly because IT already holds the lock (the
1318
+ // promise-chain mutex is NOT re-entrant - nesting would deadlock).
1319
+ await withStoreLock(() => registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey));
1320
+ }
1321
+
1322
+ async function registerWritebackUnlocked(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): Promise<void> {
1323
+ const s = await ensureStore();
1324
+ if (s.writebacks.some((w) => w.taskId === taskId)) {
1325
+ return;
1326
+ }
1327
+ // #269 per-target dedupe (enqueue side): a second registration for
1328
+ // the SAME target + action with no doneAt yet is a duplicate in the
1329
+ // making - the delivery pass would fan out two comments onto one
1330
+ // target. Skip it; the pending original still delivers the content.
1331
+ // targetId null (create* actions) cannot be target-deduped pre-delivery
1332
+ // and is excluded by the taskId check above.
1333
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1334
+ return;
1335
+ }
1336
+ s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1337
+ await saveTeamAutoStore(s);
1338
+ }
1339
+
1340
+ // #claim-dequeue (user report 2026-11-15): claim at DEQUEUE time, not
1341
+ // enqueue. Enqueue-time claims locked a whole queue of issues behind the
1342
+ // one-writer-per-repo serialization while they waited; and a blind claim
1343
+ // over issues where external collaborators had begun working (comments,
1344
+ // assignees) only produced conflicts. At dequeue we re-check FRESH state:
1345
+ // - any assignee -> stand down (a human or another bot owns it)
1346
+ // - any external comment posted after the task was enqueued -> stand
1347
+ // down (someone is actively working; our own bot's comments excluded)
1348
+ // Only a quiet, unowned issue gets claimed (assign, comment fallback),
1349
+ // with the existing seen+60s self-bump guard.
1350
+ async function claimTaskAtDequeue(task: {
1351
+ id: string;
1352
+ title: string;
1353
+ description: string;
1354
+ createdAt?: number;
1355
+ }): Promise<{ claimed: boolean; reason?: string; retryEligibility?: boolean }> {
1356
+ const kindMatch = /^\[([^\]]+)\]/.exec(task.title);
1357
+ if (!kindMatch || kindMatch[1] !== "takeOwnership") return { claimed: false, reason: "not a takeOwnership task" };
1358
+ const numMatch = /issue #(\d+)/.exec(task.title);
1359
+ if (!numMatch) return { claimed: false, reason: "no issue number" };
1360
+ const issueNumber = Number(numMatch[1]);
1361
+ const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(task.description);
1362
+ if (!repoMatch) return { claimed: false, reason: "no repo in description" };
1363
+ const repoId = repoMatch[1];
1364
+ const [owner, name] = repoId.split("/");
1365
+ if (!owner || !name) return { claimed: false, reason: "bad repo id" };
1366
+ const client = createGithubClient(auth);
1367
+ // #5740 (ggcode, 2026-11-17): eligibility CHECK failures (fetch failed on
1368
+ // getIssue/getAuthenticatedUser/getIssueCommentsSince) must NOT let the
1369
+ // task run unclaimed - the conflict check is the core #claim-dequeue
1370
+ // contract. Only the WRITE phase (assign/comment) may continue
1371
+ // unclaimed on failure (original 2026-11-15 semantics). The caller
1372
+ // reverts the assignment on retryEligibility so the next auto-assign
1373
+ // pass re-checks; a network blip delays execution by ~20s, an outage
1374
+ // loops at assignment cadence instead of silently bypassing the gate.
1375
+ let login: string;
1376
+ try {
1377
+ const fresh = await client.getIssue(owner, name, issueNumber);
1378
+ if (fresh.state !== "open") {
1379
+ return { claimed: false, reason: "issue closed" };
1075
1380
  }
1076
- // #269 per-target dedupe (enqueue side): a second registration for
1077
- // the SAME target + action with no doneAt yet is a duplicate in the
1078
- // making - the delivery pass would fan out two comments onto one
1079
- // target. Skip it; the pending original still delivers the content.
1080
- // targetId null (create* actions) cannot be target-deduped pre-delivery
1081
- // and is excluded by the taskId check above.
1082
- if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1083
- return;
1381
+ const s0 = await ensureStore();
1382
+ const repo0 = s0.repos.find((r) => r.id === repoId);
1383
+ if ((repo0?.policy.skipAssignedToHumans ?? true) && fresh.assignees.length > 0) {
1384
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: issue #${issueNumber} has assignee(s) ${fresh.assignees.join(",")} at dequeue - standing down` });
1385
+ return { claimed: false, reason: "assignees present" };
1084
1386
  }
1085
- s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1086
- void saveTeamAutoStore(s);
1087
- }).catch(() => {});
1387
+ // External-work check: comments posted after the task was ENQUEUED.
1388
+ const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
1389
+ login = (await client.getAuthenticatedUser()).login;
1390
+ const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
1391
+ const external = comments.filter((c) => c.user !== login);
1392
+ if (external.length > 0) {
1393
+ 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` });
1394
+ return { claimed: false, reason: "external activity" };
1395
+ }
1396
+ } catch (err) {
1397
+ const msg = err instanceof Error ? err.message : String(err);
1398
+ 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` });
1399
+ return { claimed: false, reason: "eligibility-check-failed", retryEligibility: true };
1400
+ }
1401
+ // #5740 (ggcode, 2026-11-17): the WRITE phase keeps the original
1402
+ // 2026-11-15 "continue unclaimed" semantics when it fails (the
1403
+ // eligibility checks DID pass), but it must not vanish silently - the
1404
+ // caller swallows rejections - so record the audit line here and return
1405
+ // a non-retrying result.
1406
+ try {
1407
+ try {
1408
+ await client.assignIssue(owner, name, issueNumber, login);
1409
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} as @${login} (at dequeue)` });
1410
+ } catch {
1411
+ // Fallback: a visible claim comment carries the same placeholder
1412
+ // semantics when the App lacks the assignees write surface.
1413
+ 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.`);
1414
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)` });
1415
+ }
1416
+ const s = await ensureStore();
1417
+ await withStoreLock(async () => {
1418
+ const freshRepo = s.repos.find((r) => r.id === repoId);
1419
+ if (freshRepo) {
1420
+ // +60s guard: our own write (assign or comment) bumps updated_at.
1421
+ freshRepo.cursors.seen[`${repoId}#issue-${issueNumber}`] = Date.now() + 60_000;
1422
+ await saveTeamAutoStore(s);
1423
+ }
1424
+ });
1425
+ return { claimed: true };
1426
+ } catch (err) {
1427
+ const msg = err instanceof Error ? err.message : String(err);
1428
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue WRITE failed for issue #${issueNumber}: ${msg.slice(0, 120)} - continuing unclaimed` });
1429
+ return { claimed: false, reason: "claim write failed" };
1430
+ }
1088
1431
  }
1089
1432
 
1090
1433
  /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
@@ -1129,6 +1472,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1129
1472
  recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1130
1473
  }
1131
1474
  const s = await ensureStore();
1475
+ await withStoreLock(async () => {
1132
1476
  const freshRepo = s.repos.find((r) => r.id === repo.id);
1133
1477
  if (freshRepo) {
1134
1478
  // +60s guard: our own write (assign or comment) bumps updated_at;
@@ -1136,6 +1480,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1136
1480
  freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1137
1481
  await saveTeamAutoStore(s);
1138
1482
  }
1483
+ });
1139
1484
  } catch (err) {
1140
1485
  logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1141
1486
  }
@@ -1278,57 +1623,78 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1278
1623
  void recoverFailedClaims();
1279
1624
  }, 60_000);
1280
1625
  claimRecoveryTimer.unref?.();
1281
- // Boot reconciliation: heal leftover task worktrees whose task is
1282
- // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
1283
- // on its own. Safety-checked: undelivered work is kept and logged.
1284
- void (async () => {
1285
- try {
1286
- // #173 follow-up 3: with getTeamState() === null the isTerminal
1287
- // predicate below classifies EVERY task as terminal - boot GC must
1288
- // not run blind over an unloaded team state (fails toward skip).
1289
- if (!deps.getTeamState()) {
1290
- logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1291
- return;
1292
- }
1293
- let removed = 0;
1294
- let retained = 0;
1295
- let stale = 0;
1296
- const retainedDetails: string[] = [];
1297
- for (const repo of s.repos) {
1298
- if (!repo.enabled) continue;
1299
- const isTerminal = (taskId: string): boolean => {
1300
- const t = deps.getTeamState()?.tasks[taskId];
1301
- if (t && t.status !== "completed" && t.status !== "failed") return false;
1302
- // Review F1: a terminal task with a pending write-back (push
1303
- // ok / PR failed, 20s-retry window) still needs its worktree -
1304
- // the retry delivers the PR from the surviving branch. Do not
1305
- // GC until the write-back settles (doneAt or dropped). Issue
1306
- // #24: terminally failed write-backs (failedAt) count as settled
1307
- // too - safeRemoveTaskWorktree still retains unpushed work.
1308
- return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1309
- };
1310
- const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle);
1311
- removed += r.removed.length;
1312
- retained += r.retained.length;
1313
- stale += r.stale;
1314
- retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1315
- }
1316
- if (removed || retained || stale) {
1317
- // #173 follow-up 4: per-task retain reasons recorded as activity
1318
- // (PR #167 promised "outcome logged + recorded as activity"); the
1319
- // stale count surfaces dir-gone-but-branch-kept leaks too.
1320
- const detail = retainedDetails.length
1321
- ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1322
- : "";
1323
- const stalePart = stale ? `, stale ${stale}` : "";
1324
- recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1325
- await saveTeamAutoStore(s);
1326
- logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1327
- }
1328
- } catch (err) {
1329
- logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
1626
+ // #gc-periodic: worktree GC used to be boot-only with an enabled-repo
1627
+ // filter - two defects (live-instance audit 2026-11-14): (a) a disabled
1628
+ // repo ("do no NEW work") never got cleaned at all; (b) the single boot
1629
+ // pass ran before the device-flow auth warmed up, so every targetClosed
1630
+ // oracle call failed toward keep and closed-target orphans stayed (4
1631
+ // confirmed misretains). Now a recurring pass: first run delayed 60s
1632
+ // (auth warm), then every 6h - transient oracle failures self-heal on
1633
+ // the next pass.
1634
+ const gcDelay = setTimeout(() => {
1635
+ void runGcPass();
1636
+ gcTimer = setInterval(() => {
1637
+ void runGcPass();
1638
+ }, 6 * 60 * 60_000);
1639
+ gcTimer.unref?.();
1640
+ }, 60_000);
1641
+ gcDelay.unref?.();
1642
+ }
1643
+
1644
+ /** #gc-periodic: one full worktree GC pass over ALL bound repos (enabled
1645
+ * or not - GC is hygiene, not new work). Shared by the boot-delayed first
1646
+ * run and the 6h recurrence. */
1647
+ async function runGcPass(): Promise<void> {
1648
+ try {
1649
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
1650
+ // predicate below classifies EVERY task as terminal - GC must not run
1651
+ // blind over an unloaded team state (fails toward skip).
1652
+ if (!deps.getTeamState()) {
1653
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1654
+ return;
1330
1655
  }
1331
- })();
1656
+ const s = await ensureStore();
1657
+ let removed = 0;
1658
+ let retained = 0;
1659
+ let stale = 0;
1660
+ const retainedDetails: string[] = [];
1661
+ for (const repo of s.repos) {
1662
+ const isTerminal = (taskId: string): boolean => {
1663
+ const t = deps.getTeamState()?.tasks[taskId];
1664
+ if (t && t.status !== "completed" && t.status !== "failed") return false;
1665
+ // Review F1: a terminal task with a pending write-back (push
1666
+ // ok / PR failed, 20s-retry window) still needs its worktree -
1667
+ // the retry delivers the PR from the surviving branch. Do not
1668
+ // GC until the write-back settles (doneAt or dropped). Issue
1669
+ // #24: terminally failed write-backs (failedAt) count as settled
1670
+ // too - safeRemoveTaskWorktree still retains unpushed work.
1671
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1672
+ };
1673
+ // #gc3: no task record anywhere in team-state -> the owner ruled
1674
+ // outright deletion (2026-11-14, "全删") - such worktrees can never
1675
+ // be judged by any oracle and were retained forever.
1676
+ const isUnknownTask = (taskId: string): boolean => !deps.getTeamState()?.tasks?.[taskId];
1677
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle, isUnknownTask);
1678
+ removed += r.removed.length;
1679
+ retained += r.retained.length;
1680
+ stale += r.stale;
1681
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1682
+ }
1683
+ if (removed || retained || stale) {
1684
+ // #173 follow-up 4: per-task retain reasons recorded as activity
1685
+ // (PR #167 promised "outcome logged + recorded as activity"); the
1686
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
1687
+ const detail = retainedDetails.length
1688
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1689
+ : "";
1690
+ const stalePart = stale ? `, stale ${stale}` : "";
1691
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1692
+ await saveTeamAutoStore(s);
1693
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1694
+ }
1695
+ } catch (err) {
1696
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
1697
+ }
1332
1698
  }
1333
1699
 
1334
1700
  async function stop(): Promise<void> {
@@ -1342,6 +1708,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1342
1708
  if (claimRecoveryTimer) {
1343
1709
  clearInterval(claimRecoveryTimer);
1344
1710
  }
1711
+ if (gcTimer) {
1712
+ clearInterval(gcTimer);
1713
+ }
1345
1714
  writebackTimer = null;
1346
1715
  }
1347
1716
  }
@@ -1364,7 +1733,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1364
1733
  return (s.activity ?? []).slice().reverse();
1365
1734
  }
1366
1735
 
1367
- return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
1736
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, claimTaskAtDequeue, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
1368
1737
 
1369
1738
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
1370
1739
  async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {