@teamclaws/teamclaw 2026.11.4 → 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 +90 -5
  17. package/dist/src/teamauto/scanner.js +22 -1
  18. package/dist/src/teamauto/scheduler.js +587 -182
  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 +100 -4
  42. package/src/teamauto/scanner.ts +23 -2
  43. package/src/teamauto/scheduler.ts +503 -106
  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
@@ -11,10 +11,12 @@ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js
11
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
- import { createRepoSync, teamAutoProjectDir, type TaskDeliveryOracle } from "./repo-sync.js";
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, {
@@ -325,12 +330,41 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
325
330
  return false;
326
331
  }
327
332
  };
333
+ // #orphan-gc: is the worktree's TARGET (issue/PR) closed? An issue closed
334
+ // without our delivery (fixed elsewhere / rejected / the PR superseded)
335
+ // makes the worktree an orphan no matter how dirty it is - the pre-fix GC
336
+ // retained such trees forever ("retained: dirty worktree", 42 and
337
+ // climbing on the live instance). Resolves true only on a POSITIVE closed
338
+ // state; unknown task / unparsable marker / API failure all resolve null
339
+ // (fail toward keep).
340
+ const targetClosedOracle: TaskTargetClosedOracle = async (repoId, taskId) => {
341
+ const teamState = deps.getTeamState();
342
+ const task = teamState?.tasks?.[taskId];
343
+ if (!task || typeof task.description !== "string") {
344
+ return null;
345
+ }
346
+ const parsed = parseClaimMarker(task.description);
347
+ if (!parsed) {
348
+ return null;
349
+ }
350
+ try {
351
+ const [owner, name] = parsed.repoId.split("/");
352
+ if (!owner || !name) {
353
+ return null;
354
+ }
355
+ const fresh = await client.getIssue(owner, name, parsed.number);
356
+ return fresh.state === "closed";
357
+ } catch {
358
+ return null;
359
+ }
360
+ };
328
361
  const timers = new Map<string, NodeJS.Timeout>();
329
362
  const sweeping = new Set<string>();
330
363
  let running = false;
331
364
  let store: TeamAutoStore | null = null;
332
365
  let writebackTimer: NodeJS.Timeout | null = null;
333
366
  let claimRecoveryTimer: NodeJS.Timeout | null = null;
367
+ let gcTimer: NodeJS.Timeout | null = null;
334
368
 
335
369
  async function ensureStore(): Promise<TeamAutoStore> {
336
370
  if (!store) {
@@ -506,6 +540,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
506
540
  for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
507
541
  try {
508
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"})`);
509
547
  break;
510
548
  } catch (err) {
511
549
  if (classifySweepError(err) !== "network") {
@@ -531,6 +569,17 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
531
569
  // -> still zero candidates -> dryRunDone never set).
532
570
  repo.dryRunDone = true;
533
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 () => {
534
583
  if (!dryRun) {
535
584
  // Advance only for acting sweeps: a dry-run must leave the cursors
536
585
  // untouched so the reported actions are actually performed next time
@@ -544,7 +593,6 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
544
593
  const fullReviews = candidates.filter((c) => c.kind === "fullReview");
545
594
  const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
546
595
  const capped = [...fullReviews, ...regular];
547
- let created = 0;
548
596
  const summary: string[] = [`found ${candidates.length} candidate(s)`];
549
597
  // #265: surface the commits delta so the third signal source is
550
598
  // observable in sweep summaries (was silently dead before).
@@ -565,23 +613,34 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
565
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}` });
566
614
  } else if (taskId) {
567
615
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
568
- 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.
569
622
  const action = candidate.kind === "prReview"
570
623
  ? ("prComment" as const)
571
624
  : candidate.kind === "fullReview"
572
625
  ? ("createIssue" as const)
573
- : ("issueComment" as const);
574
- 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);
575
630
  created++;
576
631
  }
577
632
  }
578
- 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` : ""}`;
579
636
  if (capped.some((c) => c.kind === "fullReview")) {
580
637
  repo.cursors.lastFullReviewAt = Date.now();
581
638
  }
582
639
  }
583
640
  } else {
584
- 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";
585
644
  }
586
645
  repo.lastSweepAt = Date.now();
587
646
  if (isAutoPause(repo.pausedReason)) {
@@ -594,6 +653,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
594
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) });
595
654
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
596
655
  await saveTeamAutoStore(s);
656
+ }); // withStoreLock: sweep transaction
597
657
  if (created > 0) {
598
658
  await deps.onTasksCreated().catch((err) => {
599
659
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
@@ -607,6 +667,8 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
607
667
  // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
608
668
  // failed". Auto-pauses are cooldowns now: the timer retries after the
609
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 () => {
610
672
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
611
673
  repo.lastSweepErrorAt = Date.now();
612
674
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
@@ -616,6 +678,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
616
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) });
617
679
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
618
680
  await saveTeamAutoStore(s).catch(() => {});
681
+ }); // withStoreLock: failure bookkeeping
619
682
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
620
683
  return `error: ${message}`;
621
684
  } finally {
@@ -792,6 +855,25 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
792
855
  }
793
856
 
794
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> {
795
877
  // #269 recurrence: re-read the store from disk EVERY pass - the
796
878
  // closure cache is a startup snapshot that never sees another
797
879
  // process's persisted inFlightAt/doneAt, which is exactly how the
@@ -811,10 +893,73 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
811
893
  if (dead) {
812
894
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
813
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
+ }
814
904
  }
815
905
  return !dead;
816
906
  });
817
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
+ }
818
963
  // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
819
964
  // failed-without-result tasks BEFORE the pending loop below, so the
820
965
  // terminal worktree cleanup there never ran for them - the single
@@ -823,7 +968,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
823
968
  for (const w of deadOnes) {
824
969
  const t = state0.tasks[w.taskId];
825
970
  if (t && t.writeMode === "write" && t.projectDir?.includes("__task-")) {
826
- const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle);
971
+ const r = await sync.safeRemoveTaskWorktree(w.repoId, w.taskId, squashDeliveryOracle, targetClosedOracle);
827
972
  if (r.removed) {
828
973
  // #173 follow-up 4: positive removal line - without it a successful
829
974
  // terminal cleanup is invisible in logs (only kept/failed logged).
@@ -845,7 +990,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
845
990
  for (const w of s.writebacks) {
846
991
  if (w.error && !w.doneAt && !w.failedAt && state0) {
847
992
  const t = state0.tasks[w.taskId];
848
- 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()) {
849
996
  w.error = null;
850
997
  }
851
998
  }
@@ -882,25 +1029,35 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
882
1029
  return;
883
1030
  }
884
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
+ }
885
1044
  // #269 intent-first: persist the dispatch intent BEFORE any await so
886
1045
  // an overlapping pass (or a future guard-less caller) filters this
887
1046
  // entry out instead of re-delivering it.
888
1047
  entry.inFlightAt = Date.now();
889
1048
  await saveTeamAutoStore(s);
890
- const task = state.tasks[entry.taskId];
891
- if (!task || (task.status !== "completed" && task.status !== "failed")) {
892
- continue;
893
- }
894
1049
  const repo = s.repos.find((r) => r.id === entry.repoId);
895
1050
  const [owner, name] = entry.repoId.split("/");
896
1051
  try {
897
- if (task.status === "failed" || !task.result) {
898
- // Undeliverable in every future pass: a failed task never gains a
899
- // result, and "completed without result" cannot recover either.
900
- // Mark terminal (issue #24) so the entry is counted, surfaced via
901
- // activity/stats, and never pointlessly retried. Failed-without-
902
- // result entries are additionally dropped by the dead-letter pass
903
- // 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.
904
1061
  markWritebackFailure(
905
1062
  s,
906
1063
  entry,
@@ -911,7 +1068,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
911
1068
  // path left - remove it when the worker never produced deliverable
912
1069
  // commits (safety-checked, undelivered work is retained + logged).
913
1070
  if (task.writeMode === "write" && task.projectDir?.includes("__task-")) {
914
- const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle);
1071
+ const r = await sync.safeRemoveTaskWorktree(entry.repoId, task.id, squashDeliveryOracle, targetClosedOracle);
915
1072
  if (r.removed) {
916
1073
  // #173 follow-up 4: positive removal line - symmetric with the
917
1074
  // boot-GC path which logs both directions.
@@ -923,16 +1080,26 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
923
1080
  } else {
924
1081
  const role = (task.assignedRole ?? "qa") as string;
925
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
+ }
926
1089
  let writebackDone = false;
927
1090
  // WRITE TASKS (collaboration contract): commit the task worktree,
928
1091
  // push its branch, open a PR, and attach the link to the reply.
929
1092
  const repoId = entry.repoId;
930
1093
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
931
1094
  let prDeliveryFailed = false;
932
- 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.
933
1100
  try {
934
1101
  const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
935
- const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
1102
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id, info.defaultBranch, info.cloneUrl);
936
1103
  const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
937
1104
  const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
938
1105
  // Workers often commit themselves inside the worktree - deliver
@@ -940,11 +1107,19 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
940
1107
  // commitAll just added new ones.
941
1108
  const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
942
1109
  if (deliverable) {
943
- await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
944
- 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)}`);
945
- entry.prUrl = pr.url;
946
- body = `${body}\n\nDelivered as PR: ${pr.url}`;
947
- 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
+ }
948
1123
  }
949
1124
  await sync.removeTaskWorktree(repoId, task.id);
950
1125
  } catch (prErr) {
@@ -964,10 +1139,25 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
964
1139
  continue;
965
1140
  }
966
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 {
967
1156
  await client.postIssueComment(owner, name, entry.targetId, body);
968
1157
  entry.doneAt = Date.now();
969
1158
  entry.inFlightAt = undefined;
970
1159
  writebackDone = true;
1160
+ }
971
1161
  // Our own comment bumps the issue's updatedAt, which the scanner
972
1162
  // treats as new activity - advance the seen cursor so we do not
973
1163
  // re-trigger a review of an object we just replied to. External
@@ -977,10 +1167,27 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
977
1167
  issueRepo.cursors.seen[`${entry.repoId}#issue-${entry.targetId}`] = Date.now();
978
1168
  }
979
1169
  } else if (entry.action === "prComment" && entry.targetId) {
980
- await client.postPullReviewComment(owner, name, entry.targetId, body);
981
- entry.doneAt = Date.now();
982
- entry.inFlightAt = undefined;
983
- 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
+ }
984
1191
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
985
1192
  if (prRepo) {
986
1193
  prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
@@ -990,14 +1197,33 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
990
1197
  // (first completed section creates it, the rest post as comments).
991
1198
  const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
992
1199
  if (entry.cycleKey) {
993
- const peers = s.writebacks.filter((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
994
- const umbrella = peers[0];
995
- if (umbrella && umbrella.targetId != null) {
996
- await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
997
- 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;
998
1223
  entry.doneAt = Date.now();
999
1224
  entry.inFlightAt = undefined;
1000
1225
  writebackDone = true;
1226
+ entry.deliveryNote = "section-appended-to-umbrella";
1001
1227
  } else if (entry.targetId == null) {
1002
1228
  const number = await client.createIssue(
1003
1229
  owner,
@@ -1007,6 +1233,18 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1007
1233
  ["teamclaw", "teamclaw:fullreview"],
1008
1234
  );
1009
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);
1010
1248
  entry.doneAt = Date.now();
1011
1249
  entry.inFlightAt = undefined;
1012
1250
  writebackDone = true;
@@ -1027,36 +1265,169 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1027
1265
  // does not linger in the errored/failed stats (issue #24).
1028
1266
  entry.error = null;
1029
1267
  entry.failedAt = null;
1030
- 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)` : ""})` });
1031
1272
  }
1032
1273
  }
1033
1274
  } catch (err) {
1034
- 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
+ });
1035
1282
  }
1036
1283
  void repo;
1037
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
+ }
1038
1301
  s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
1039
1302
  await saveTeamAutoStore(s);
1040
1303
  }
1041
1304
 
1042
1305
  // Register the write-back intent when a task lands in the task store.
1043
- function registerWriteback(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): void {
1044
- void ensureStore().then((s) => {
1045
- if (s.writebacks.some((w) => w.taskId === taskId)) {
1046
- 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" };
1047
1380
  }
1048
- // #269 per-target dedupe (enqueue side): a second registration for
1049
- // the SAME target + action with no doneAt yet is a duplicate in the
1050
- // making - the delivery pass would fan out two comments onto one
1051
- // target. Skip it; the pending original still delivers the content.
1052
- // targetId null (create* actions) cannot be target-deduped pre-delivery
1053
- // and is excluded by the taskId check above.
1054
- if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1055
- 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" };
1386
+ }
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)` });
1056
1415
  }
1057
- s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1058
- void saveTeamAutoStore(s);
1059
- }).catch(() => {});
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
+ }
1060
1431
  }
1061
1432
 
1062
1433
  /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
@@ -1101,6 +1472,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1101
1472
  recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1102
1473
  }
1103
1474
  const s = await ensureStore();
1475
+ await withStoreLock(async () => {
1104
1476
  const freshRepo = s.repos.find((r) => r.id === repo.id);
1105
1477
  if (freshRepo) {
1106
1478
  // +60s guard: our own write (assign or comment) bumps updated_at;
@@ -1108,6 +1480,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1108
1480
  freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1109
1481
  await saveTeamAutoStore(s);
1110
1482
  }
1483
+ });
1111
1484
  } catch (err) {
1112
1485
  logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1113
1486
  }
@@ -1250,57 +1623,78 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1250
1623
  void recoverFailedClaims();
1251
1624
  }, 60_000);
1252
1625
  claimRecoveryTimer.unref?.();
1253
- // Boot reconciliation: heal leftover task worktrees whose task is
1254
- // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
1255
- // on its own. Safety-checked: undelivered work is kept and logged.
1256
- void (async () => {
1257
- try {
1258
- // #173 follow-up 3: with getTeamState() === null the isTerminal
1259
- // predicate below classifies EVERY task as terminal - boot GC must
1260
- // not run blind over an unloaded team state (fails toward skip).
1261
- if (!deps.getTeamState()) {
1262
- logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1263
- return;
1264
- }
1265
- let removed = 0;
1266
- let retained = 0;
1267
- let stale = 0;
1268
- const retainedDetails: string[] = [];
1269
- for (const repo of s.repos) {
1270
- if (!repo.enabled) continue;
1271
- const isTerminal = (taskId: string): boolean => {
1272
- const t = deps.getTeamState()?.tasks[taskId];
1273
- if (t && t.status !== "completed" && t.status !== "failed") return false;
1274
- // Review F1: a terminal task with a pending write-back (push
1275
- // ok / PR failed, 20s-retry window) still needs its worktree -
1276
- // the retry delivers the PR from the surviving branch. Do not
1277
- // GC until the write-back settles (doneAt or dropped). Issue
1278
- // #24: terminally failed write-backs (failedAt) count as settled
1279
- // too - safeRemoveTaskWorktree still retains unpushed work.
1280
- return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1281
- };
1282
- const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle);
1283
- removed += r.removed.length;
1284
- retained += r.retained.length;
1285
- stale += r.stale;
1286
- retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1287
- }
1288
- if (removed || retained || stale) {
1289
- // #173 follow-up 4: per-task retain reasons recorded as activity
1290
- // (PR #167 promised "outcome logged + recorded as activity"); the
1291
- // stale count surfaces dir-gone-but-branch-kept leaks too.
1292
- const detail = retainedDetails.length
1293
- ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1294
- : "";
1295
- const stalePart = stale ? `, stale ${stale}` : "";
1296
- recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1297
- await saveTeamAutoStore(s);
1298
- logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1299
- }
1300
- } catch (err) {
1301
- 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;
1302
1655
  }
1303
- })();
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
+ }
1304
1698
  }
1305
1699
 
1306
1700
  async function stop(): Promise<void> {
@@ -1314,6 +1708,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1314
1708
  if (claimRecoveryTimer) {
1315
1709
  clearInterval(claimRecoveryTimer);
1316
1710
  }
1711
+ if (gcTimer) {
1712
+ clearInterval(gcTimer);
1713
+ }
1317
1714
  writebackTimer = null;
1318
1715
  }
1319
1716
  }
@@ -1336,7 +1733,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1336
1733
  return (s.activity ?? []).slice().reverse();
1337
1734
  }
1338
1735
 
1339
- 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 };
1340
1737
 
1341
1738
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
1342
1739
  async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {