@teamclaws/teamclaw 2026.11.5 → 2026.11.7

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 (70) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/config-routes.js +7 -3
  4. package/dist/src/controller/controller-service.js +12 -1
  5. package/dist/src/controller/http-server.js +2 -2
  6. package/dist/src/controller/managed-gateway-process.js +17 -1
  7. package/dist/src/controller/provisioning/container-shared.js +6 -1
  8. package/dist/src/controller/provisioning/docker.js +1 -1
  9. package/dist/src/controller/provisioning/kubernetes.js +1 -1
  10. package/dist/src/controller/provisioning/process-supervisor.js +23 -1
  11. package/dist/src/controller/provisioning-config.js +8 -0
  12. package/dist/src/controller/route-table.js +2 -2
  13. package/dist/src/controller/security.js +30 -15
  14. package/dist/src/controller/task-assignment.js +126 -2
  15. package/dist/src/controller/task-results.js +34 -3
  16. package/dist/src/controller/task-routes.js +63 -3
  17. package/dist/src/controller/tunnel-manager.js +11 -0
  18. package/dist/src/controller/tunnel-routes.js +11 -0
  19. package/dist/src/controller/worker-provisioning.js +35 -0
  20. package/dist/src/controller/worker-routes.js +21 -6
  21. package/dist/src/controller/workspace-routes.js +16 -2
  22. package/dist/src/openclaw-workspace.js +39 -20
  23. package/dist/src/task-executor.js +44 -3
  24. package/dist/src/teamauto/github-client.js +107 -5
  25. package/dist/src/teamauto/repo-sync.js +172 -26
  26. package/dist/src/teamauto/scanner.js +22 -1
  27. package/dist/src/teamauto/scheduler.js +988 -190
  28. package/dist/src/teamauto/store.js +171 -3
  29. package/dist/src/teamauto/write-payload-guard.js +209 -0
  30. package/dist/src/types.js +11 -3
  31. package/dist/src/ui/app.js +2 -2
  32. package/dist/src/worker/tools.js +5 -0
  33. package/dist/src/worker/worker-service.js +13 -1
  34. package/dist/src/workspace-browser.js +14 -0
  35. package/openclaw.plugin.json +5 -5
  36. package/package.json +4 -2
  37. package/src/config.ts +3 -3
  38. package/src/controller/config-routes.ts +7 -3
  39. package/src/controller/controller-service.ts +12 -1
  40. package/src/controller/http-server.ts +2 -2
  41. package/src/controller/managed-gateway-process.ts +17 -1
  42. package/src/controller/provisioning/backend-contract.ts +4 -0
  43. package/src/controller/provisioning/container-shared.ts +6 -1
  44. package/src/controller/provisioning/docker.ts +1 -1
  45. package/src/controller/provisioning/kubernetes.ts +1 -1
  46. package/src/controller/provisioning/process-supervisor.ts +23 -1
  47. package/src/controller/provisioning-config.ts +9 -0
  48. package/src/controller/route-table.ts +2 -2
  49. package/src/controller/security.ts +30 -15
  50. package/src/controller/task-assignment.ts +128 -1
  51. package/src/controller/task-results.ts +33 -3
  52. package/src/controller/task-routes.ts +64 -2
  53. package/src/controller/tunnel-manager.ts +12 -1
  54. package/src/controller/tunnel-routes.ts +11 -0
  55. package/src/controller/worker-provisioning.ts +35 -0
  56. package/src/controller/worker-routes.ts +21 -7
  57. package/src/controller/workspace-routes.ts +17 -2
  58. package/src/openclaw-workspace.ts +43 -23
  59. package/src/task-executor.ts +46 -3
  60. package/src/teamauto/github-client.ts +103 -5
  61. package/src/teamauto/repo-sync.ts +158 -23
  62. package/src/teamauto/scanner.ts +23 -2
  63. package/src/teamauto/scheduler.ts +883 -113
  64. package/src/teamauto/store.ts +205 -3
  65. package/src/teamauto/write-payload-guard.ts +222 -0
  66. package/src/types.ts +30 -7
  67. package/src/ui/app.js +2 -2
  68. package/src/worker/tools.ts +5 -0
  69. package/src/worker/worker-service.ts +15 -1
  70. package/src/workspace-browser.ts +15 -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,
@@ -240,9 +242,26 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
240
242
  entry.error = message;
241
243
  entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
242
244
  entry.attempts = (entry.attempts ?? 0) + 1;
245
+ // #5815: identical-error-text circuit breaker. The same message three
246
+ // ladder runs in a row is a structural dead end (zero-diff 422s burned
247
+ // six runs live) - stop early instead of burning the full ladder.
248
+ const sameText = entry.lastErrorText !== undefined && message.slice(0, 120) === entry.lastErrorText.slice(0, 120);
249
+ entry.lastErrorText = message.slice(0, 200);
250
+ entry.lastErrorStreak = sameText ? (entry.lastErrorStreak ?? 0) + 1 : 1;
251
+ const deterministicStreak = (entry.lastErrorStreak ?? 0) >= 3;
243
252
  entry.lastErrorAt = Date.now();
244
253
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
245
- const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
254
+ // #5651: a non-fast-forward push whose rebase self-heal also failed is
255
+ // deterministic - retrying the same push 6 more times just burns ~25min.
256
+ // Dead-letter immediately (the next sweep re-claims on a fresh branch).
257
+ // #5767 (ggcode, 2026-11-18): deterministic hook/environment failures are
258
+ // not transient - a repo pre-commit calling bash4+ builtins on a bash3.2
259
+ // host ("mapfile: command not found") retried 6 times for 33 minutes
260
+ // before dying. Same fail-fast as the #5651 non-fast-forward signature:
261
+ // hook-not-found / command-not-found / not-executable signatures are
262
+ // structural, every retry is a guaranteed repeat.
263
+ const deterministicHookFailure = /(?:hooks?\/[^:]*: line \d+: \w+: command not found|hook declined|cannot run hook|exited with error before)/.test(message);
264
+ const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS || deterministicStreak || /push rejected \(non-fast-forward\) and rebase self-heal failed/.test(message) || deterministicHookFailure;
246
265
  if (gaveUp && !entry.doneAt) {
247
266
  entry.failedAt = Date.now();
248
267
  recordActivity(store, {
@@ -359,6 +378,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
359
378
  let store: TeamAutoStore | null = null;
360
379
  let writebackTimer: NodeJS.Timeout | null = null;
361
380
  let claimRecoveryTimer: NodeJS.Timeout | null = null;
381
+ let gcTimer: NodeJS.Timeout | null = null;
362
382
 
363
383
  async function ensureStore(): Promise<TeamAutoStore> {
364
384
  if (!store) {
@@ -367,17 +387,33 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
367
387
  return store;
368
388
  }
369
389
 
390
+ /**
391
+ * #5792 (ggcode, 2026-11-19): one fresh handle per locked transaction.
392
+ * The 20s reconcile pass reassigns the closure `store` from disk on EVERY
393
+ * pass; a section that captured `ensureStore()` BEFORE that flip and saves
394
+ * AFTER it re-writes a stale snapshot, erasing everything persisted in
395
+ * between. Live shape (the #5792 zero-fire regression): the sweep captured
396
+ * its handle before the unlocked network phase; registerWritebackUnlocked -
397
+ * called inside the sweep's locked tx - re-resolved the flipped closure, so
398
+ * the entry was pushed and saved onto the NEW object while the tx tail
399
+ * re-saved the OLD handle: "created 2/2" logged, writebacks[] empty on
400
+ * disk, zero ladder rows, orphan alarms ~10min after completion, 100% of
401
+ * tasks after the 3b1a175 deploy restart re-based the tick grid onto the
402
+ * sweep window. Every load->mutate->save section that spans an await
403
+ * boundary must take its handle UNDER the lock via this helper.
404
+ */
405
+ async function reloadStoreUnlocked(): Promise<TeamAutoStore> {
406
+ store = await loadTeamAutoStore();
407
+ return store;
408
+ }
409
+
370
410
  // ---------- public repo management ----------
371
411
 
372
412
  async function addRepo(repoId: string, options: { schedule?: string; keywordInclude?: string[]; keywordExclude?: string[] } = {}): Promise<TeamAutoRepo> {
373
- const s = await ensureStore();
374
413
  const normalized = repoId.trim().replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, "");
375
414
  if (!/^[\w.-]+\/[\w.-]+$/.test(normalized)) {
376
415
  throw new Error(`invalid repo id: ${repoId} (expected owner/repo)`);
377
416
  }
378
- if (s.repos.some((r) => r.id === normalized)) {
379
- throw new Error(`${normalized} is already bound`);
380
- }
381
417
  const [owner, name] = normalized.split("/");
382
418
  const info = await client.getRepoInfo(owner, name);
383
419
  if (!info.permissions.pull) {
@@ -385,6 +421,13 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
385
421
  }
386
422
  const schedule = options.schedule?.trim() || "*/30 * * * *";
387
423
  nextFireMs(schedule); // validates: throws ScheduleParseError for unsupported expressions
424
+ // #5792: captured AFTER the network await - a capture before
425
+ // getRepoInfo could be orphaned by a reconcile reload and the bind
426
+ // save would then erase concurrent writeback registrations.
427
+ const s = await ensureStore();
428
+ if (s.repos.some((r) => r.id === normalized)) {
429
+ throw new Error(`${normalized} is already bound`);
430
+ }
388
431
  const repo: TeamAutoRepo = {
389
432
  id: normalized,
390
433
  enabled: true,
@@ -523,6 +566,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
523
566
  return "sweep already in progress";
524
567
  }
525
568
  sweeping.add(repo.id);
569
+ // #5792: frozen identity for the under-lock rebind below - the repo node
570
+ // used inside the tx must come from the FRESH store handle, not this
571
+ // possibly-orphaned snapshot.
572
+ const repoOuter = repo;
573
+ const repoOuterId = repo.id;
526
574
  const sweepStartedAt = Date.now();
527
575
  const etagBefore = client.etagStats();
528
576
  try {
@@ -534,6 +582,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
534
582
  for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
535
583
  try {
536
584
  swept = await sweepRepo(repo, client);
585
+ // #5706 (ggcode): sweep observability - "no new work" is ambiguous
586
+ // between an empty fetch (etag 304 / API silence) and full filter
587
+ // rejection. Log the funnel so starvation diagnoses itself.
588
+ 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
589
  break;
538
590
  } catch (err) {
539
591
  if (classifySweepError(err) !== "network") {
@@ -559,6 +611,27 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
559
611
  // -> still zero candidates -> dryRunDone never set).
560
612
  repo.dryRunDone = true;
561
613
  }
614
+ // #5712 (ggcode) / teamclaw#274: the ENTIRE sweep store transaction -
615
+ // cursor/seen advance, budget consume, task activity, write-back
616
+ // registrations, summary, sweep record, and the commit save - is one
617
+ // read-modify-write section. It previously raced the (locked) 20s
618
+ // write-back reconcile: reconcile's disk reload + tail save clobbered
619
+ // the sweep's writes (live: 20:30 batch lost summary/budget/activity
620
+ // while later claim/write-back saves survived). registerWriteback
621
+ // inside uses the *Unlocked core - the promise-chain mutex is NOT
622
+ // re-entrant.
623
+ let created = 0; // #5712: outside the lock scope - read after commit
624
+ let sweepSummary: string | null = null; // #5792: read after the commit
625
+ await withStoreLock(async () => {
626
+ // #5792 (ggcode): bind ONE fresh handle (and repo node) under the
627
+ // lock. The outer `s` was captured before the unlocked network phase;
628
+ // a 20s reconcile reload during sweepRepo orphaned it, and the tail
629
+ // save below then erased the writeback registrations that
630
+ // registerWritebackUnlocked had just persisted onto the reloaded
631
+ // closure ("created 2/2" logged, writebacks[] empty on disk, zero
632
+ // ladder rows - the #5792 zero-fire regression).
633
+ const s = await reloadStoreUnlocked();
634
+ const repo = s.repos.find((r) => r.id === repoOuterId) ?? repoOuter;
562
635
  if (!dryRun) {
563
636
  // Advance only for acting sweeps: a dry-run must leave the cursors
564
637
  // untouched so the reported actions are actually performed next time
@@ -572,7 +645,6 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
572
645
  const fullReviews = candidates.filter((c) => c.kind === "fullReview");
573
646
  const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
574
647
  const capped = [...fullReviews, ...regular];
575
- let created = 0;
576
648
  const summary: string[] = [`found ${candidates.length} candidate(s)`];
577
649
  // #265: surface the commits delta so the third signal source is
578
650
  // observable in sweep summaries (was silently dead before).
@@ -593,23 +665,42 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
593
665
  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
666
  } else if (taskId) {
595
667
  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
668
+ // #claim-dequeue (user 2026-11-15): claiming at ENQUEUE locked a
669
+ // string of issues behind the one-writer-per-repo queue while
670
+ // they waited - and blindly claimed issues where external
671
+ // collaborators had started working in the scan-to-claim gap.
672
+ // Claiming now happens at DEQUEUE (claimTaskAtDequeue, called
673
+ // from the task assignment path) after a fresh conflict check.
597
674
  const action = candidate.kind === "prReview"
598
675
  ? ("prComment" as const)
599
676
  : candidate.kind === "fullReview"
600
677
  ? ("createIssue" as const)
601
- : ("issueComment" as const);
602
- registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
678
+ : candidate.kind === "prRework"
679
+ ? ("prComment" as const)
680
+ : ("issueComment" as const);
681
+ await registerWritebackUnlocked(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
603
682
  created++;
604
683
  }
605
684
  }
606
- repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
685
+ // #5824: the admission check consumed capped.length UP FRONT,
686
+ // but duplicate-active (or dead-letter) skips never enqueue - the
687
+ // budget burned on nothing (live: created 0/2, budget 11->13).
688
+ // Refund the difference so the ledger tracks CREATED tasks only;
689
+ // the capped.length admission gate above still bounds the batch.
690
+ if (created < capped.length) {
691
+ s.budget.tasksToday = Math.max(0, s.budget.tasksToday - (capped.length - created));
692
+ }
693
+ const failedSince = repo.failedTasksSinceLastSweep ?? 0;
694
+ repo.failedTasksSinceLastSweep = 0;
695
+ repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
607
696
  if (capped.some((c) => c.kind === "fullReview")) {
608
697
  repo.cursors.lastFullReviewAt = Date.now();
609
698
  }
610
699
  }
611
700
  } else {
612
- repo.lastSweepSummary = "no new work";
701
+ const failedSince0 = repo.failedTasksSinceLastSweep ?? 0;
702
+ repo.failedTasksSinceLastSweep = 0;
703
+ repo.lastSweepSummary = failedSince0 > 0 ? `no new work; FAILED ${failedSince0} since last sweep` : "no new work";
613
704
  }
614
705
  repo.lastSweepAt = Date.now();
615
706
  if (isAutoPause(repo.pausedReason)) {
@@ -621,20 +712,28 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
621
712
  const etagAfter = client.etagStats();
622
713
  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
714
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
715
+ sweepSummary = repo.lastSweepSummary; // #5792: post-commit readers use the tx-scoped repo
624
716
  await saveTeamAutoStore(s);
717
+ }); // withStoreLock: sweep transaction
625
718
  if (created > 0) {
626
719
  await deps.onTasksCreated().catch((err) => {
627
720
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
628
721
  });
629
722
  }
630
- logger.info(`TeamAuto: sweep ${repo.id} -> ${repo.lastSweepSummary}`);
631
- return repo.lastSweepSummary ?? "sweep complete";
723
+ logger.info(`TeamAuto: sweep ${repo.id} -> ${sweepSummary}`);
724
+ return sweepSummary ?? "sweep complete";
632
725
  } catch (err) {
633
726
  const message = err instanceof Error ? err.message : String(err);
634
727
  // Transient failures (network blips, restart-interrupted sweeps) used to
635
728
  // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
636
729
  // failed". Auto-pauses are cooldowns now: the timer retries after the
637
730
  // backoff below, and a success clears the state in the block above.
731
+ // #5712: failure bookkeeping is a store RMW too - same lock.
732
+ await withStoreLock(async () => {
733
+ // #5792: fresh handle under the lock (same stale-snapshot class as
734
+ // the sweep transaction above).
735
+ const s = await reloadStoreUnlocked();
736
+ const repo = s.repos.find((r) => r.id === repoOuterId) ?? repoOuter;
638
737
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
639
738
  repo.lastSweepErrorAt = Date.now();
640
739
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
@@ -644,6 +743,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
644
743
  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
744
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
646
745
  await saveTeamAutoStore(s).catch(() => {});
746
+ }); // withStoreLock: failure bookkeeping
647
747
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
648
748
  return `error: ${message}`;
649
749
  } finally {
@@ -820,6 +920,25 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
820
920
  }
821
921
 
822
922
  async function doReconcileWritebacks(): Promise<void> {
923
+ // #2677: the WHOLE read-modify-write section holds the store lock -
924
+ // an unlocked reload+save here clobbered a concurrently-registered
925
+ // write-back entry (see store.ts withStoreLock).
926
+ await withStoreLock(async () => {
927
+ await doReconcileWritebacksLocked();
928
+ }).catch((err) => {
929
+ // #5677 ask: never swallow a delivery-pass crash silently - a lost
930
+ // entry with zero trace is invisible; surface it in the log AND the
931
+ // activity feed so the failure class is diagnosable.
932
+ const msg = err instanceof Error ? err.message : String(err);
933
+ logger.warn(`TeamAuto: write-back pass CRASHED (entries may retry next tick): ${msg}`);
934
+ void ensureStore().then((s) => {
935
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `delivery pass crashed: ${msg.slice(0, 140)}` });
936
+ return saveTeamAutoStore(s);
937
+ }).catch(() => {});
938
+ });
939
+ }
940
+
941
+ async function doReconcileWritebacksLocked(): Promise<void> {
823
942
  // #269 recurrence: re-read the store from disk EVERY pass - the
824
943
  // closure cache is a startup snapshot that never sees another
825
944
  // process's persisted inFlightAt/doneAt, which is exactly how the
@@ -839,10 +958,258 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
839
958
  if (dead) {
840
959
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
841
960
  deadOnes.push(w);
961
+ // #5641: the 3-day architect-leg outage was invisible because a
962
+ // failed-without-result task produced NO activity line and the next
963
+ // sweep summary still said "created 3/3". Record both surfaces.
964
+ 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)})` : ""}` });
965
+ const failedRepo = s.repos.find((r) => r.id === w.repoId);
966
+ if (failedRepo) {
967
+ failedRepo.failedTasksSinceLastSweep = (failedRepo.failedTasksSinceLastSweep ?? 0) + 1;
968
+ }
842
969
  }
843
970
  return !dead;
844
971
  });
845
972
  if (s.writebacks.length !== before) { await saveTeamAutoStore(s); }
973
+ // #5725 (ggcode): settle self-audit. A COMPLETED teamauto task with a
974
+ // textual result whose write-back entry is absent AND whose ok line is
975
+ // missing from the activity feed means the registration (or the whole
976
+ // entry) was lost - the ladder redundancy channel silently failed.
977
+ // Alarm once per task so the observability contract survives entry loss.
978
+ let auditDirty = false;
979
+ if (state0) {
980
+ s.orphanResultAlarms ??= {};
981
+ s.deliveredResults ??= {};
982
+ // #5738 (ggcode, 2026-11-17): ONE-TIME migration. The #5736 backfill
983
+ // only stamped entries still present in the write-back array at
984
+ // deploy time - historically delivered legs were already pruned, so
985
+ // they all re-entered the alarm domain on the first settled pass
986
+ // (23 tasks, 99 lines in 80s). Seed the ledger once from the task
987
+ // state itself: everything completed with a result inside the audit
988
+ // window at init time is treated as delivered (the sentinel verified
989
+ // those 23 were all normally delivered). Accepted trade-off: any
990
+ // genuine pre-deploy orphan is pardoned once - signal > archaeology.
991
+ // #5770: gate the one-time migration on an EMPTY table, not just the
992
+ // flag - a generation-window store clobber can wipe the flag while
993
+ // the table survives (or vice versa), and a re-run re-stamps
994
+ // completedAt as deliveredAt for the current window, forging delivery
995
+ // records that mask genuine orphans (live: 57cc2770/e975ddac stamped
996
+ // at the exact completion millisecond, audit went silent).
997
+ if (!s.deliveredResultsInit && Object.keys(s.deliveredResults).length === 0) {
998
+ s.deliveredResultsInit = true;
999
+ for (const task of Object.values(state0.tasks ?? {})) {
1000
+ if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
1001
+ s.deliveredResults[task.id] = task.completedAt;
1002
+ }
1003
+ }
1004
+ auditDirty = true;
1005
+ }
1006
+ let alarmedThisPass = 0; // #5772: at most ONE orphan alarm per settle pass
1007
+ // #5777: tasks whose direct-send delivery lands AFTER completion
1008
+ // (live: delivered 5m21s post-completed, zero ladder/ledger trail)
1009
+ // would alarm at the first tick. Grace period first; at grace
1010
+ // expiry the audit checks the GitHub surface ONCE for a teamclaw
1011
+ // marker comment and back-fills the ledger when the product exists.
1012
+ const ghClient = createGithubClient(auth);
1013
+ for (const task of Object.values(state0.tasks ?? {})) {
1014
+ if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-")) continue;
1015
+ // #5772: 24h -> 6h audit window. A restart replays the audit over
1016
+ // HISTORICAL completed tasks whose write-back entries are long
1017
+ // pruned and whose ledger truth died in a generation-window clobber
1018
+ // - that population is exactly the false-alarm storm (14 healthy
1019
+ // tasks at once, live). Genuine orphans surface within hours; the
1020
+ // remaining tail is not worth storm-shaped noise.
1021
+ if (task.completedAt && Date.now() - task.completedAt > 6 * 3600_000) continue;
1022
+ // #5738: once-per-task gate; the audit now persists its own
1023
+ // mutations in the same pass (auditDirty save below), so the gate
1024
+ // survives the next 20s disk reload instead of re-alarming.
1025
+ const lastAlarmAt = s.orphanResultAlarms[task.id];
1026
+ if (lastAlarmAt) continue;
1027
+ // #5777: direct-send grace - do not judge before a slow worker
1028
+ // direct-post has had its chance.
1029
+ if (task.completedAt && Date.now() - task.completedAt < 10 * 60_000) continue;
1030
+ // #5736: delivered-source is the DURABLE ledger (entry present OR
1031
+ // recorded at prune time) - never the activity ring, which rolls in
1032
+ // hours and made every normal delivery a false orphan.
1033
+ // #5770: a REAL delivery happens >= one reconcile tick (20s) after
1034
+ // completion; a ledger stamp within 2s of completedAt is a migration
1035
+ // artifact, not evidence of delivery - do not let it silence the
1036
+ // orphan audit.
1037
+ const deliveredAt = s.deliveredResults[task.id];
1038
+ const ledgerIsArtifact = deliveredAt !== undefined && task.completedAt !== undefined && Math.abs(deliveredAt - task.completedAt) < 2000;
1039
+ const hasEntry = s.writebacks.some((w) => w.taskId === task.id) || (deliveredAt !== undefined && !ledgerIsArtifact);
1040
+ if (!hasEntry) {
1041
+ // #5777: grace expired and still no books - verify the GitHub
1042
+ // surface ONCE for a teamclaw marker comment (worker direct-send
1043
+ // shape) before declaring an orphan. A marker hit back-fills the
1044
+ // ledger; only a genuinely bare issue alarms.
1045
+ // #5781: channel-aware verification - a prReview task's product
1046
+ // lives on the PR review surface (reviews + PR conversation
1047
+ // comments), which getIssueCommentBodies cannot see (live:
1048
+ // d7152fe0 delivered two COMMENTED reviews, issue-surface check
1049
+ // matched zero, false orphan). Route by target type: PR number
1050
+ // -> feedback bodies (reviews + comments), issue number ->
1051
+ // issue comments.
1052
+ const prNumMatch = /(?:PR|pull request) #(\d+)/i.exec(`${task.title}`);
1053
+ const numMatch = prNumMatch ?? /issue #(\d+)/.exec(`${task.title}`);
1054
+ const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(`${task.description}`);
1055
+ // #5783 contract 5b: the fetched bodies must stay visible BELOW the
1056
+ // evidence check - the self-heal gate distinguishes "surface
1057
+ // completely silent" (rescue re-delivery) from "surface carries
1058
+ // bare/foreign bodies that match no evidence" (orphan alarm).
1059
+ let targetBodies: string[] = [];
1060
+ if (numMatch && repoMatch) {
1061
+ const [o, n] = repoMatch[1].split("/");
1062
+ const targetNum = Number(numMatch[1]);
1063
+ targetBodies = prNumMatch
1064
+ ? await ghClient.getPullFeedbackBodies(o, n, targetNum).catch(() => [] as string[])
1065
+ : await ghClient.getIssueCommentBodies(o, n, targetNum).catch(() => [] as string[]);
1066
+ // #5780: workers deliver in more shapes than the ladder marker -
1067
+ // narrative bodies ("Fix delivered ... via TeamClaw autonomous")
1068
+ // and branch-reference footers carry no [teamclaw:] prefix and
1069
+ // zeroed the evidence check (live: 8fdf5efd false-alarmed).
1070
+ // #5730/23da7606 sharpening: exotic bodies with ZERO teamclaw
1071
+ // references exist too (first wild case, mk:false on all
1072
+ // three predicates). The universal fallback: a direct-send
1073
+ // body IS the task result - fingerprint match on its first
1074
+ // 60 chars catches every shape, marker or not.
1075
+ const resultFingerprint = task.result.replace(/\s+/g, " ").trim().slice(0, 60);
1076
+ const ghEvidence = targetBodies.some((b) => /\[teamclaw[:\]]/i.test(b) || /teamclaw|teamauto/i.test(b) || /teamclaw\/task-/.test(b) || (resultFingerprint.length >= 40 && b.replace(/\s+/g, " ").includes(resultFingerprint)));
1077
+ if (ghEvidence) {
1078
+ // #5785 reconciliation (rebase of #284 onto the 085fc67
1079
+ // chain): the undelivered-PR self-check now lives in the
1080
+ // dedicated PR-face settle audit below - a REST probe via
1081
+ // listPullsByHead plus the durable prDeliveries ledger. This
1082
+ // inline local-evidence variant (085fc67/e882af2) is removed
1083
+ // so a WRITE task with issue-face evidence but a missing PR
1084
+ // leg has exactly ONE alarm path, not two competing ones.
1085
+ s.deliveredResults[task.id] = Date.now();
1086
+ auditDirty = true;
1087
+ recordActivity(s, { at: Date.now(), repoId: repoMatch[1], kind: "writeback", text: `ledger back-filled from GitHub evidence: ${task.id} direct-send delivery verified on issue #${numMatch[1]} (no ladder trail - #5777 timing shape)` });
1088
+ await saveTeamAutoStore(s).catch(() => {});
1089
+ continue;
1090
+ }
1091
+ }
1092
+ // #5792 self-heal (ggcode): the registration was lost in
1093
+ // flight (live: the sweep transaction's stale tail-save erased
1094
+ // it - "created 2/2" logged, zero ladder rows). Re-register from
1095
+ // the already-parsed target so the ladder re-delivers the result
1096
+ // instead of only alarming: prReview bodies have NO direct-send
1097
+ // surface, so without this the review verdict (e.g. a REQUEST
1098
+ // CHANGES on a live PR) is lost forever.
1099
+ // #5783 contract 5b gate: the rescue is for a COMPLETELY SILENT
1100
+ // surface only. When the surface already carries bodies that
1101
+ // match no evidence (live shape: a bare worker direct-post or a
1102
+ // foreign/human review), the audit must take the verdict the
1103
+ // evidence predicate hands it - the alarm. Re-registering there
1104
+ // swallowed the alarm (5b regression after bb09e1e) and would
1105
+ // re-post a duplicate beside the unverified body.
1106
+ // #5785 reconciliation: WRITE tasks are ALSO out of scope - their
1107
+ // lost registration is the PR-face settle audit's jurisdiction
1108
+ // (listPullsByHead probe + prDeliveries ledger below). A healed
1109
+ // issueComment entry here would sit in s.writebacks and mask
1110
+ // that audit exactly like the live incident's comment-shaped
1111
+ // evidence did, or re-deliver a comment beside an unknown
1112
+ // push/PR state - the double-delivery hazard #5785 documents.
1113
+ if (numMatch && repoMatch && targetBodies.length === 0 && task.writeMode !== "write") {
1114
+ const healTargetNum = Number(numMatch[1]);
1115
+ await registerWritebackUnlocked(task.id, prNumMatch ? "prComment" : "issueComment", repoMatch[1], healTargetNum);
1116
+ if (s.writebacks.some((w) => w.taskId === task.id)) {
1117
+ recordActivity(s, { at: Date.now(), repoId: repoMatch[1], kind: "writeback", text: `orphan self-heal: re-registered ${prNumMatch ? "prComment" : "issueComment"} #${healTargetNum} for ${task.id} (registration lost in flight - #5792); the ladder will re-deliver` });
1118
+ logger.warn(`TeamAuto: orphan self-heal re-registered ${prNumMatch ? "prComment" : "issueComment"} #${healTargetNum} for ${task.id}`);
1119
+ auditDirty = true;
1120
+ await saveTeamAutoStore(s).catch(() => {});
1121
+ if (++alarmedThisPass >= 1) break; // storm cap: one audit ACTION per pass
1122
+ continue;
1123
+ }
1124
+ // Re-registration was skipped (e.g. another task's OPEN entry
1125
+ // owns this target) - fall through to the alarm below.
1126
+ }
1127
+ s.orphanResultAlarms[task.id] = Date.now();
1128
+ auditDirty = true;
1129
+ 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)` });
1130
+ logger.warn(`TeamAuto: orphan completed task ${task.id} without write-back entry`);
1131
+ // #5772: persist the gate IMMEDIATELY on the alarming branch -
1132
+ // deferring to the block-tail save lost the write to a
1133
+ // restart-timeline clobber once already (#5738 regression).
1134
+ await saveTeamAutoStore(s).catch(() => {});
1135
+ if (++alarmedThisPass >= 1) break; // storm cap: one per pass
1136
+ }
1137
+ }
1138
+ // #5785 (ggcode, 2026-11-18): undelivered-PR audit - the PR-face
1139
+ // sibling of the orphan-result audit above. A completed WRITE task
1140
+ // delivers on TWO faces: the issue/review comment (verified above)
1141
+ // and the push+createPR leg, which per the WRITE collaboration
1142
+ // contract ONLY the write-back ladder performs. The orphan audit is
1143
+ // comment-shaped: a worker direct-post on the issue face back-fills
1144
+ // deliveredResults and silences it, while the PR face never came
1145
+ // into existence (live: branch pushed, zero PR across a 10m42s
1146
+ // three-probe window, writebacks [] throughout, gate silent - the
1147
+ // issue-face delivery masked the missing PR face entirely).
1148
+ // Contract: a completed WRITE task inside the audit window must
1149
+ // (a) still own a write-back entry (the ladder owns its PR face;
1150
+ // delivery failures surface via the retry ladder and the
1151
+ // "completed task delivery LOST" alarm), or (b) carry a durable
1152
+ // PR-face record (prDeliveries - stamped at prune time from
1153
+ // entry.prUrl), or (c) show a PR (any state) whose head is its task
1154
+ // branch. None of the three => ONE undelivered-PR alarm line.
1155
+ let prAlarmedThisPass = 0;
1156
+ for (const task of Object.values(state0.tasks ?? {})) {
1157
+ if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-")) continue;
1158
+ // Same shape predicate as the delivery path's isTeamAutoWrite:
1159
+ // only dispatched WRITE tasks carry the PR-face contract.
1160
+ if (task.writeMode !== "write" || !task.projectDir?.includes("__task-")) continue;
1161
+ // The window math needs completedAt (the task system stamps it on
1162
+ // completion); tasks without it are not judgeable here.
1163
+ if (!task.completedAt) continue;
1164
+ if (Date.now() - task.completedAt > 6 * 3600_000) continue;
1165
+ if (s.undeliveredPrAlarms?.[task.id]) continue;
1166
+ // Same #5777 grace as the orphan audit: a slow ladder delivery (or
1167
+ // a manual push+PR) gets its window before judgement.
1168
+ if (Date.now() - task.completedAt < 10 * 60_000) continue;
1169
+ if (s.writebacks.some((w) => w.taskId === task.id)) continue;
1170
+ if (s.prDeliveries?.[task.id]) continue;
1171
+ const prRepoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(`${task.description}`);
1172
+ const taskBranch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
1173
+ let prFaceUrl: string | null = null;
1174
+ if (prRepoMatch) {
1175
+ const [prOwner, prName] = prRepoMatch[1].split("/");
1176
+ // Distinguish fetch FAILURE (null -> retry next settle pass; a
1177
+ // blip must not gate the check permanently) from a definitive
1178
+ // empty list (-> alarm).
1179
+ const pulls = await ghClient.listPullsByHead(prOwner, prName, taskBranch).catch(() => null);
1180
+ if (pulls === null) continue;
1181
+ const hit = pulls.find((p) => p.htmlUrl) ?? pulls[0];
1182
+ if (hit) prFaceUrl = hit.htmlUrl || `#${hit.number}`;
1183
+ }
1184
+ s.undeliveredPrAlarms ??= {};
1185
+ s.undeliveredPrAlarms[task.id] = Date.now();
1186
+ auditDirty = true;
1187
+ if (prFaceUrl) {
1188
+ s.prDeliveries ??= {};
1189
+ s.prDeliveries[task.id] = prFaceUrl;
1190
+ recordActivity(s, { at: Date.now(), repoId: prRepoMatch?.[1] ?? "*", kind: "writeback", text: `PR face verified: ${task.id} has no write-back entry but PR ${prFaceUrl} exists for branch ${taskBranch} - createPR fired through another path (undelivered-PR audit pardon, #5785)` });
1191
+ } else {
1192
+ recordActivity(s, { at: Date.now(), repoId: prRepoMatch?.[1] ?? "*", kind: "writeback", text: `undelivered-PR alarm: task ${task.id} completed (WRITE) with NO write-back entry and no PR from branch ${taskBranch} - the createPR leg never fired (enqueue-side registration skipped; the issue-face delivery masked it - #5785)` });
1193
+ logger.warn(`TeamAuto: undelivered PR for completed WRITE task ${task.id} (branch ${taskBranch})`);
1194
+ // Same #5738 discipline as the orphan alarm: persist the gate on
1195
+ // the alarming branch, not only at the block tail.
1196
+ await saveTeamAutoStore(s).catch(() => {});
1197
+ }
1198
+ if (++prAlarmedThisPass >= 1) break; // storm cap: one per pass
1199
+ }
1200
+ if (s.undeliveredPrAlarms && Object.keys(s.undeliveredPrAlarms).length > 200) {
1201
+ const prGateEntries = Object.entries(s.undeliveredPrAlarms).sort((a, b) => a[1] - b[1]);
1202
+ for (const [k] of prGateEntries.slice(0, prGateEntries.length - 100)) delete s.undeliveredPrAlarms[k];
1203
+ }
1204
+ if (Object.keys(s.orphanResultAlarms).length > 200) {
1205
+ const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
1206
+ for (const [k] of entries.slice(0, entries.length - 100)) delete s.orphanResultAlarms[k];
1207
+ }
1208
+ // #5738: the gate lives on disk - persist audit mutations in the SAME
1209
+ // pass that makes them, or the next 20s reload resets the gate and
1210
+ // re-alarms everything (99 lines / 23 tasks live).
1211
+ if (auditDirty) { await saveTeamAutoStore(s); }
1212
+ }
846
1213
  // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
847
1214
  // failed-without-result tasks BEFORE the pending loop below, so the
848
1215
  // terminal worktree cleanup there never ran for them - the single
@@ -873,7 +1240,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
873
1240
  for (const w of s.writebacks) {
874
1241
  if (w.error && !w.doneAt && !w.failedAt && state0) {
875
1242
  const t = state0.tasks[w.taskId];
876
- if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
1243
+ // #5719: a FAILED task WITH a result is deliverable too (the result is
1244
+ // the work product - analysis/diagnostic legs). Same backoff reset.
1245
+ if (t && t.result && (t.status === "completed" || t.status === "failed") && (w.nextAttemptAt ?? 0) <= Date.now()) {
877
1246
  w.error = null;
878
1247
  }
879
1248
  }
@@ -910,25 +1279,35 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
910
1279
  return;
911
1280
  }
912
1281
  for (const entry of pending) {
1282
+ // #5685 (ggcode, 2026-11-16): gate on a TERMINAL task BEFORE touching
1283
+ // the entry. The old order stamped inFlightAt first and `continue`d
1284
+ // for still-running tasks, leaving the sticky intent to wedge the
1285
+ // entry out of pendingAll until the 600s stale reset - a completed
1286
+ // task's write-back was deliverable in exactly one 20s window every
1287
+ // ~10 minutes (live: the 02:30 fullReview legs delivered 8m42s-9m51s
1288
+ // after completion, long misread as deliberate "slow release"). The
1289
+ // intent stamp now happens only when the pass is about to dispatch.
1290
+ const task = state.tasks[entry.taskId];
1291
+ if (!task || (task.status !== "completed" && task.status !== "failed")) {
1292
+ continue;
1293
+ }
913
1294
  // #269 intent-first: persist the dispatch intent BEFORE any await so
914
1295
  // an overlapping pass (or a future guard-less caller) filters this
915
1296
  // entry out instead of re-delivering it.
916
1297
  entry.inFlightAt = Date.now();
917
1298
  await saveTeamAutoStore(s);
918
- const task = state.tasks[entry.taskId];
919
- if (!task || (task.status !== "completed" && task.status !== "failed")) {
920
- continue;
921
- }
922
1299
  const repo = s.repos.find((r) => r.id === entry.repoId);
923
1300
  const [owner, name] = entry.repoId.split("/");
924
1301
  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.
1302
+ if (!task.result) {
1303
+ // Undeliverable in every future pass: "completed without result"
1304
+ // cannot recover. #5719 (ggcode, 2026-11-16): a FAILED task WITH a
1305
+ // textual result is NOT in this class - the result is the
1306
+ // deliverable (analysis/diagnostic work products). It now falls
1307
+ // through to normal delivery with an error footer; only
1308
+ // result-less entries (failed or completed) stay terminal.
1309
+ // Failed-without-result entries are additionally dropped by the
1310
+ // dead-letter pass on the next reconcile.
932
1311
  markWritebackFailure(
933
1312
  s,
934
1313
  entry,
@@ -951,28 +1330,96 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
951
1330
  } else {
952
1331
  const role = (task.assignedRole ?? "qa") as string;
953
1332
  let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
1333
+ // #5719: a failed-with-result task delivers its result (the work
1334
+ // product) with the failure context appended - never silently
1335
+ // dropped as before.
1336
+ if (task.status === "failed" && task.error) {
1337
+ body = `${body}\n\n---\n[task reported failed: ${task.error.slice(0, 300)}]`;
1338
+ }
954
1339
  let writebackDone = false;
955
1340
  // WRITE TASKS (collaboration contract): commit the task worktree,
956
1341
  // push its branch, open a PR, and attach the link to the reply.
957
1342
  const repoId = entry.repoId;
958
1343
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
959
1344
  let prDeliveryFailed = false;
960
- if (isTeamAutoWrite) {
1345
+ if (isTeamAutoWrite && task.status !== "failed") {
1346
+ // #5719: a FAILED write task's worktree carries no deliverable by
1347
+ // construction (that is usually WHY it failed) - the PR step just
1348
+ // burns retries against an empty worktree. Deliver the result
1349
+ // comment directly; the worktree is cleaned by the terminal pass.
961
1350
  try {
962
1351
  const info = await client.getRepoInfo(repoId.split("/")[0]!, repoId.split("/")[1]!);
963
- const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
1352
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id, info.defaultBranch, info.cloneUrl);
964
1353
  const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
965
1354
  const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
966
1355
  // Workers often commit themselves inside the worktree - deliver
967
1356
  // whenever the branch carries commits beyond base, not only when
968
1357
  // commitAll just added new ones.
969
- const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
1358
+ // #5815: compare against the REMOTE base tip, not the stale
1359
+ // local baseline - a stale checkout makes a zero-commit branch
1360
+ // look deliverable and the PR dies on a deterministic 422
1361
+ // (zero diff) six times in a row.
1362
+ const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch, info.cloneUrl));
970
1363
  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}` });
1364
+ const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch, (pushErr) => {
1365
+ // #5788: dedicated push-failure activity line - symmetric
1366
+ // with the createPR ladder rows.
1367
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `push failed for ${branch}: ${pushErr.slice(0, 140)} - branch is LOCAL-ONLY until this is resolved` });
1368
+ });
1369
+ if (push.alreadyDelivered) {
1370
+ // #stale-base follow-up: a previous incarnation already
1371
+ // delivered this branch (PR merged). Skip PR creation and
1372
+ // the retry ladder - the task's work is on the remote.
1373
+ body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
1374
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `already delivered on ${branch} - skipped duplicate push/PR` });
1375
+ // #5785: this shape delivered a PR in a previous
1376
+ // incarnation - record the PR face so the settle audit
1377
+ // does not re-verify it against GitHub forever after.
1378
+ s.prDeliveries ??= {};
1379
+ s.prDeliveries[task.id] = `branch:${branch} (previous delivery)`;
1380
+ } else {
1381
+ let pr;
1382
+ let prSkippedForZeroDiff = false;
1383
+ try {
1384
+ 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)}`);
1385
+ } catch (prErr) {
1386
+ // #5788: a 422 on a freshly-pushed head almost always
1387
+ // means the push NEVER LANDED (live: two stranded legs,
1388
+ // generic "Validation Failed" masked it). Probe the head
1389
+ // and disambiguate the failure text before rethrowing.
1390
+ const pmsg = prErr instanceof Error ? prErr.message : String(prErr);
1391
+ if (/422|Validation Failed/i.test(pmsg)) {
1392
+ const probe = await sync.branchExistsRemotely(wtDir, branch).catch(() => false);
1393
+ if (!probe) {
1394
+ throw new Error(`createPR 422 with head branch ABSENT on remote - the PUSH never landed for ${branch} (see push-failure activity; local-only branch)`);
1395
+ }
1396
+ // #5815: branch IS present but PR still 422 - the zero-
1397
+ // diff shape (head is an ancestor of base: the task
1398
+ // completed with analysis-only output / misplaced-repo
1399
+ // verdict). NOT retriable: every ladder run is the same
1400
+ // 422. Deliver the result as the comment directly with
1401
+ // an analysis note, like the #5719 failed-write path.
1402
+ const zeroDiff = await sync.branchIsAncestorOfRemoteBase(wtDir, branch, info.defaultBranch).catch(() => false);
1403
+ if (zeroDiff) {
1404
+ body = `${body}\n\nNo code changes (analysis-only completion - no PR needed).`;
1405
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `zero-diff 422 classified: ${task.id} completed with analysis-only output - delivering as comment, PR ladder skipped (#5815)` });
1406
+ prDeliveryFailed = false;
1407
+ prSkippedForZeroDiff = true;
1408
+ }
1409
+ if (!prSkippedForZeroDiff) throw prErr;
1410
+ } else {
1411
+ throw prErr;
1412
+ }
1413
+ }
1414
+ if (prSkippedForZeroDiff) {
1415
+ // fall through to the comment delivery below with the
1416
+ // analysis-amended body - no PR to attach.
1417
+ } else if (pr) {
1418
+ entry.prUrl = pr.url;
1419
+ body = `${body}\n\nDelivered as PR: ${pr.url}`;
1420
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1421
+ }
1422
+ }
976
1423
  }
977
1424
  await sync.removeTaskWorktree(repoId, task.id);
978
1425
  } catch (prErr) {
@@ -985,6 +1432,12 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
985
1432
  // two comments 2s apart. Fail atomically instead: the entry
986
1433
  // keeps its failed state + backoff and replays BOTH steps
987
1434
  // (PR first, then comment) on the next attempt.
1435
+ // #5767: a COMPLETED task whose delivery exhausts is the worst
1436
+ // outcome (work done, product lost, owner unaware) - surface it
1437
+ // as its own alarm line, not just the retry-ladder failure row.
1438
+ if (task.status === "completed") {
1439
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `completed task delivery LOST: ${task.id} finished but its worktree/PR delivery keeps failing (${prErr instanceof Error ? prErr.message.slice(0, 120) : String(prErr)}) - manual delivery may be required` });
1440
+ }
988
1441
  prDeliveryFailed = true;
989
1442
  }
990
1443
  }
@@ -992,10 +1445,42 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
992
1445
  continue;
993
1446
  }
994
1447
  if (entry.action === "issueComment" && entry.targetId) {
1448
+ // #5818 defense-in-depth: the target may have been closed since
1449
+ // enqueue/dequeue - commenting on a closed issue pollutes the
1450
+ // resolution record. Re-check state first; closed -> skip with a
1451
+ // visible line (the result stays in the task record for manual
1452
+ // retrieval if ever needed).
1453
+ try {
1454
+ const targetIssue = await client.getIssue(owner, name, entry.targetId);
1455
+ if (targetIssue.state !== "open") {
1456
+ entry.doneAt = Date.now();
1457
+ entry.inFlightAt = undefined;
1458
+ writebackDone = true;
1459
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `issueComment #${entry.targetId} skipped: issue CLOSED at delivery time - result retained in task record (#5818)` });
1460
+ logger.info(`TeamAuto: write-back ${entry.taskId} skipped - target issue #${entry.targetId} closed`);
1461
+ }
1462
+ } catch { /* state check failed - attempt delivery anyway */ }
1463
+ }
1464
+ if (entry.action === "issueComment" && entry.targetId && !writebackDone) {
1465
+ // #5725 / #5660 parity: the worker may have posted the same body
1466
+ // directly during its execution window (takeOwnership legs deliver
1467
+ // an ownership-wrap comment themselves). Posting again duplicates;
1468
+ // skipping silently breaks the observability contract. Exact
1469
+ // whitespace-normalized match -> mark done + record the skip.
1470
+ const normalizedBody = body.replace(/\s+/g, " ").trim();
1471
+ const existingBodies = await client.getIssueCommentBodies(owner, name, entry.targetId);
1472
+ if (existingBodies.some((b) => b.replace(/\s+/g, " ").trim() === normalizedBody)) {
1473
+ entry.doneAt = Date.now();
1474
+ entry.inFlightAt = undefined;
1475
+ writebackDone = true;
1476
+ 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` });
1477
+ logger.info(`TeamAuto: write-back ${entry.taskId} issueComment deduped - identical body already on issue #${entry.targetId}`);
1478
+ } else {
995
1479
  await client.postIssueComment(owner, name, entry.targetId, body);
996
1480
  entry.doneAt = Date.now();
997
1481
  entry.inFlightAt = undefined;
998
1482
  writebackDone = true;
1483
+ }
999
1484
  // Our own comment bumps the issue's updatedAt, which the scanner
1000
1485
  // treats as new activity - advance the seen cursor so we do not
1001
1486
  // re-trigger a review of an object we just replied to. External
@@ -1005,10 +1490,44 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1005
1490
  issueRepo.cursors.seen[`${entry.repoId}#issue-${entry.targetId}`] = Date.now();
1006
1491
  }
1007
1492
  } 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;
1493
+ // #5660 (ggcode, 2026-11-15): the worker already posted the same
1494
+ // review body directly during its execution window; the ladder
1495
+ // then delivered the IDENTICAL text 20s later - readers got the
1496
+ // review twice. Before posting, check the target's existing
1497
+ // feedback (reviews + comments, whitespace-normalized): an exact
1498
+ // match means delivery already happened through the other
1499
+ // channel - mark done and record the skip.
1500
+ // #5783: the prComment channel shipped BARE worker results - no
1501
+ // MARKER_FOOTER - so the evidence predicate (#5777-#5781 chain)
1502
+ // never matched its own deliveries and every prReview leg
1503
+ // false-alarmed. Append the footer like every other channel.
1504
+ // #5783 residual (same day): the shared body construction above
1505
+ // ALREADY appends one MARKER_FOOTER for every channel, so the
1506
+ // extra append here shipped the marker TWICE; and
1507
+ // getPullFeedbackBodies returns whitespace-COLLAPSED bodies, so
1508
+ // a "\n---\n[teamclaw:]" strip can never match the existing
1509
+ // side - a footered worker direct-post still double-delivered.
1510
+ // Post exactly ONE footer (stripping any footer blocks the
1511
+ // worker echoed into its result) and dedupe footer-agnostic
1512
+ // AFTER collapsing, so bare, footered and twice-footered shapes
1513
+ // all compare equal on both sides.
1514
+ const collapse = (t: string) => t.replace(/\s+/g, " ").trim();
1515
+ const stripCollapsedFooter = (t: string) => collapse(t).replace(/ ?--- ?\[teamclaw:[^\]]+\].*$/, "").trim();
1516
+ const postBody = `${body.replace(/\n?---\n\[teamclaw:[^\]]+\][^\n]*/g, "").trimEnd()}\n${MARKER_FOOTER(role)}`;
1517
+ const normalized = stripCollapsedFooter(body);
1518
+ const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => [] as string[]);
1519
+ if (existing.some((b) => stripCollapsedFooter(b) === normalized)) {
1520
+ entry.doneAt = Date.now();
1521
+ entry.inFlightAt = undefined;
1522
+ writebackDone = true;
1523
+ 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` });
1524
+ logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
1525
+ } else {
1526
+ await client.postPullReviewComment(owner, name, entry.targetId, postBody);
1527
+ entry.doneAt = Date.now();
1528
+ entry.inFlightAt = undefined;
1529
+ writebackDone = true;
1530
+ }
1012
1531
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
1013
1532
  if (prRepo) {
1014
1533
  prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
@@ -1018,14 +1537,33 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1018
1537
  // (first completed section creates it, the rest post as comments).
1019
1538
  const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
1020
1539
  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;
1540
+ // #5685 (ggcode, 2026-11-16): the umbrella pointer must survive
1541
+ // the end-of-pass pruning of done write-back entries (and
1542
+ // process restarts). The old lookup only saw peers delivered
1543
+ // in the SAME pass, so every cross-pass section minted its own
1544
+ // duplicate umbrella - live: cycle 20772 produced issues
1545
+ // #5686/#5687/#5688 (three "Joint full review" umbrellas,
1546
+ // zero section comments). The store map is the durable
1547
+ // pointer; an in-pass done peer remains as a fallback for
1548
+ // stores written before this fix.
1549
+ const cycleKey = `${entry.repoId}|${entry.cycleKey}`;
1550
+ s.fullReviewUmbrellas = s.fullReviewUmbrellas ?? {};
1551
+ const peerEntry = s.writebacks.find((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
1552
+ const umbrellaNumber = s.fullReviewUmbrellas[cycleKey] ?? peerEntry?.targetId ?? null;
1553
+ if (umbrellaNumber != null) {
1554
+ // Crash-retry guard: this entry may BE the creator whose
1555
+ // createIssue + umbrella-map write persisted but whose doneAt
1556
+ // did not. The umbrella body already carries its section, so
1557
+ // a creator retry completes silently instead of re-posting.
1558
+ if (entry.targetId !== umbrellaNumber) {
1559
+ await client.postIssueComment(owner, name, umbrellaNumber, sectionBody);
1560
+ }
1561
+ entry.targetId = umbrellaNumber;
1562
+ s.fullReviewUmbrellas[cycleKey] = umbrellaNumber;
1026
1563
  entry.doneAt = Date.now();
1027
1564
  entry.inFlightAt = undefined;
1028
1565
  writebackDone = true;
1566
+ entry.deliveryNote = "section-appended-to-umbrella";
1029
1567
  } else if (entry.targetId == null) {
1030
1568
  const number = await client.createIssue(
1031
1569
  owner,
@@ -1035,6 +1573,18 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1035
1573
  ["teamclaw", "teamclaw:fullreview"],
1036
1574
  );
1037
1575
  entry.targetId = number;
1576
+ s.fullReviewUmbrellas[cycleKey] = number;
1577
+ entry.deliveryNote = "umbrella-created";
1578
+ // Persist the umbrella pointer immediately: done entries are
1579
+ // pruned at end-of-pass, and a crash between create and the
1580
+ // tail save must not lose the only record of the umbrella.
1581
+ const umbrellaKeys = Object.keys(s.fullReviewUmbrellas);
1582
+ if (umbrellaKeys.length > 100) {
1583
+ for (const staleKey of umbrellaKeys.slice(0, umbrellaKeys.length - 100)) {
1584
+ delete s.fullReviewUmbrellas[staleKey];
1585
+ }
1586
+ }
1587
+ await saveTeamAutoStore(s);
1038
1588
  entry.doneAt = Date.now();
1039
1589
  entry.inFlightAt = undefined;
1040
1590
  writebackDone = true;
@@ -1055,36 +1605,211 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1055
1605
  // does not linger in the errored/failed stats (issue #24).
1056
1606
  entry.error = null;
1057
1607
  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)` : ""})` });
1608
+ // #5735: distinguish created-vs-appended so umbrella cycles stop
1609
+ // reading as double-creates (two "createIssue #N ok" lines for
1610
+ // one issue is by design: first creates, peers append sections).
1611
+ 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
1612
  }
1060
1613
  }
1061
1614
  } catch (err) {
1062
- markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
1615
+ const message = err instanceof Error ? err.message : String(err);
1616
+ markWritebackFailure(s, entry, message, {
1617
+ // #5704: an envelope-frame rejection is deterministic corruption -
1618
+ // the payload cannot change between attempts. Fail terminally
1619
+ // instead of burning the retry ladder re-posting the same frame.
1620
+ terminal: message.includes(ENVELOPE_LEAK_MARKER),
1621
+ });
1063
1622
  }
1064
1623
  void repo;
1065
1624
  }
1625
+ // #5736 (ggcode): record deliveries into the durable ledger BEFORE the
1626
+ // done-entry prune - the write-back array and the tiny activity ring are
1627
+ // both short-lived, but the orphan audit runs for 24h after completion.
1628
+ // Without this, every normally-delivered task alarms as an orphan once
1629
+ // its entry is pruned and its ok line rolls off the ring.
1630
+ s.deliveredResults ??= {};
1631
+ s.prDeliveries ??= {};
1632
+ for (const w of s.writebacks) {
1633
+ if (w.doneAt) {
1634
+ s.deliveredResults[w.taskId] = w.doneAt;
1635
+ // #5785: PR-face delivery must be durable too - the entry (and its
1636
+ // prUrl) dies at the prune below, and the undelivered-PR audit needs
1637
+ // to tell "PR opened, entry pruned" apart from "registration never
1638
+ // happened" without re-probing GitHub for every healthy task.
1639
+ if (w.prUrl) {
1640
+ s.prDeliveries[w.taskId] = w.prUrl;
1641
+ }
1642
+ }
1643
+ }
1644
+ const deliveredEntries = Object.entries(s.deliveredResults);
1645
+ if (deliveredEntries.length > 2000) {
1646
+ deliveredEntries.sort((a, b) => a[1] - b[1]);
1647
+ for (const [k] of deliveredEntries.slice(0, deliveredEntries.length - 1500)) delete s.deliveredResults[k];
1648
+ }
1066
1649
  s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
1067
1650
  await saveTeamAutoStore(s);
1068
1651
  }
1069
1652
 
1070
1653
  // 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;
1654
+ // #5643 (user report 2026-11-15): this used to be fire-and-forget
1655
+ // (void ensureStore().then(...).catch(() => {})) - the push+save raced the
1656
+ // sweep's own awaited store save AND swallowed its own errors. The 11-15
1657
+ // 02:00 batch lost ALL THREE fullReview write-back entries that way
1658
+ // (tasks + activity + "created 3/3" persisted; the entries did not), so
1659
+ // completed reviews delivered nothing, silently. Registration is now part
1660
+ // of the sweep transaction: the caller awaits it before the sweep's own
1661
+ // save, and failures propagate instead of vanishing.
1662
+ async function registerWriteback(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): Promise<void> {
1663
+ // #5712 (ggcode) / teamclaw#274: every store read-modify-write must hold
1664
+ // withStoreLock. Public entry takes the lock; the sweep transaction calls
1665
+ // the *Unlocked core directly because IT already holds the lock (the
1666
+ // promise-chain mutex is NOT re-entrant - nesting would deadlock).
1667
+ await withStoreLock(async () => {
1668
+ await reloadStoreUnlocked(); // #5792: fresh handle under the lock
1669
+ return registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey);
1670
+ });
1671
+ }
1672
+
1673
+ async function registerWritebackUnlocked(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): Promise<void> {
1674
+ const s = await ensureStore();
1675
+ if (s.writebacks.some((w) => w.taskId === taskId)) {
1676
+ return;
1677
+ }
1678
+ // #5785 (ggcode, 2026-11-18): the enqueue-side per-target dedupe is
1679
+ // REMOVED. It skipped a registration whenever ANY pending entry aimed at
1680
+ // the same target + action, on the assumption "the pending original
1681
+ // still delivers the content" - but write-back content is per-task
1682
+ // (task.result): a different task's entry delivers ITS OWN result,
1683
+ // never this one. Live shape: a later leg on the same issue enrolled
1684
+ // while an earlier leg's entry was still pending; the later task's
1685
+ // registration was silently swallowed, so its completed WRITE result
1686
+ // never entered the ladder - the branch sat on the remote with no PR
1687
+ // (writebacks [] across the whole 10m42s observation window) and only
1688
+ // the worker's issue-face direct-post kept the orphan audit quiet.
1689
+ // Duplicate protection is fully covered by the other three guards:
1690
+ // (1) same-taskId idempotency above (a re-registration of ONE task),
1691
+ // (2) the #269 delivery-side per-target cap (ONE entry per target key
1692
+ // per pass - co-target rows serialize across 20s passes), and
1693
+ // (3) exact-body dedupe at post time (worker direct-posts).
1694
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1695
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `co-target write-back registered: ${taskId} joins ${s.writebacks.filter((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt).length} pending ${action} row(s) on #${targetId} - rows serialize via the delivery-side per-pass cap (#5785)` });
1696
+ }
1697
+ s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1698
+ await saveTeamAutoStore(s);
1699
+ }
1700
+
1701
+ // #claim-dequeue (user report 2026-11-15): claim at DEQUEUE time, not
1702
+ // enqueue. Enqueue-time claims locked a whole queue of issues behind the
1703
+ // one-writer-per-repo serialization while they waited; and a blind claim
1704
+ // over issues where external collaborators had begun working (comments,
1705
+ // assignees) only produced conflicts. At dequeue we re-check FRESH state:
1706
+ // - any assignee -> stand down (a human or another bot owns it)
1707
+ // - any external comment posted after the task was enqueued -> stand
1708
+ // down (someone is actively working; our own bot's comments excluded)
1709
+ // Only a quiet, unowned issue gets claimed (assign, comment fallback),
1710
+ // with the existing seen+60s self-bump guard.
1711
+ async function claimTaskAtDequeue(task: {
1712
+ id: string;
1713
+ title: string;
1714
+ description: string;
1715
+ createdAt?: number;
1716
+ }): Promise<{ claimed: boolean; reason?: string; retryEligibility?: boolean }> {
1717
+ const kindMatch = /^\[([^\]]+)\]/.exec(task.title);
1718
+ if (!kindMatch || kindMatch[1] !== "takeOwnership") return { claimed: false, reason: "not a takeOwnership task" };
1719
+ const numMatch = /issue #(\d+)/.exec(task.title);
1720
+ if (!numMatch) return { claimed: false, reason: "no issue number" };
1721
+ const issueNumber = Number(numMatch[1]);
1722
+ const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(task.description);
1723
+ if (!repoMatch) return { claimed: false, reason: "no repo in description" };
1724
+ const repoId = repoMatch[1];
1725
+ const [owner, name] = repoId.split("/");
1726
+ if (!owner || !name) return { claimed: false, reason: "bad repo id" };
1727
+ const client = createGithubClient(auth);
1728
+ // #5740 (ggcode, 2026-11-17): eligibility CHECK failures (fetch failed on
1729
+ // getIssue/getAuthenticatedUser/getIssueCommentsSince) must NOT let the
1730
+ // task run unclaimed - the conflict check is the core #claim-dequeue
1731
+ // contract. Only the WRITE phase (assign/comment) may continue
1732
+ // unclaimed on failure (original 2026-11-15 semantics). The caller
1733
+ // reverts the assignment on retryEligibility so the next auto-assign
1734
+ // pass re-checks; a network blip delays execution by ~20s, an outage
1735
+ // loops at assignment cadence instead of silently bypassing the gate.
1736
+ let login: string;
1737
+ try {
1738
+ const fresh = await client.getIssue(owner, name, issueNumber);
1739
+ if (fresh.state !== "open") {
1740
+ return { claimed: false, reason: "issue closed" };
1075
1741
  }
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;
1742
+ const s0 = await ensureStore();
1743
+ const repo0 = s0.repos.find((r) => r.id === repoId);
1744
+ if ((repo0?.policy.skipAssignedToHumans ?? true) && fresh.assignees.length > 0) {
1745
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: issue #${issueNumber} has assignee(s) ${fresh.assignees.join(",")} at dequeue - standing down` });
1746
+ return { claimed: false, reason: "assignees present" };
1747
+ }
1748
+ // External-work check: comments posted after the task was ENQUEUED.
1749
+ const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
1750
+ login = (await client.getAuthenticatedUser()).login;
1751
+ const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
1752
+ // #5819: same-account multi-seat blindness. Filtering purely by
1753
+ // account excludes ALL seats sharing the bot account - a sibling seat
1754
+ // claiming the same issue ([claim master_coordinator] ...) was
1755
+ // invisible and both seats implemented it (live: #5812 double
1756
+ // delivery). Content-aware: same-account comments carrying a SEAT
1757
+ // declaration ([claim X]/[done X]) count as external UNLESS X is one
1758
+ // of teamauto's own roles (those are this pipeline's own prior legs -
1759
+ // retry legs must not stand down on their own history).
1760
+ const seatDecl = /\[(claim|done)\s+([a-z_-]+)\s*\]/i;
1761
+ const teamautoRoles = new Set(["developer", "qa", "architect", "security-engineer", "security-engineer-role"]);
1762
+ const external = comments.filter((c) => {
1763
+ if (c.user !== login) return true;
1764
+ const m = seatDecl.exec(String((c as { body?: string }).body ?? ""));
1765
+ return Boolean(m && !teamautoRoles.has(m[2]!.toLowerCase()));
1766
+ });
1767
+ if (external.length > 0) {
1768
+ 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` });
1769
+ return { claimed: false, reason: "external activity" };
1770
+ }
1771
+ } catch (err) {
1772
+ const msg = err instanceof Error ? err.message : String(err);
1773
+ 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` });
1774
+ return { claimed: false, reason: "eligibility-check-failed", retryEligibility: true };
1775
+ }
1776
+ // #5740 (ggcode, 2026-11-17): the WRITE phase keeps the original
1777
+ // 2026-11-15 "continue unclaimed" semantics when it fails (the
1778
+ // eligibility checks DID pass), but it must not vanish silently - the
1779
+ // caller swallows rejections - so record the audit line here and return
1780
+ // a non-retrying result.
1781
+ try {
1782
+ let claimNote = "";
1783
+ try {
1784
+ await client.assignIssue(owner, name, issueNumber, login);
1785
+ claimNote = `claimed issue #${issueNumber} as @${login} (at dequeue)`;
1786
+ } catch {
1787
+ // Fallback: a visible claim comment carries the same placeholder
1788
+ // semantics when the App lacks the assignees write surface.
1789
+ 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.`);
1790
+ claimNote = `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)`;
1084
1791
  }
1085
- s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1086
- void saveTeamAutoStore(s);
1087
- }).catch(() => {});
1792
+ await withStoreLock(async () => {
1793
+ // #5792: one fresh handle under the lock. The old shape captured
1794
+ // `s` before the claim writes (network awaits) and saved it inside
1795
+ // the lock - a reconcile reload in between orphaned the handle and
1796
+ // the save wiped concurrent registrations; the claim activity note
1797
+ // also only persisted when it rode the same (possibly stale) object.
1798
+ const s = await reloadStoreUnlocked();
1799
+ recordActivity(s, { at: Date.now(), repoId, kind: "claim", text: claimNote });
1800
+ const freshRepo = s.repos.find((r) => r.id === repoId);
1801
+ if (freshRepo) {
1802
+ // +60s guard: our own write (assign or comment) bumps updated_at.
1803
+ freshRepo.cursors.seen[`${repoId}#issue-${issueNumber}`] = Date.now() + 60_000;
1804
+ await saveTeamAutoStore(s);
1805
+ }
1806
+ });
1807
+ return { claimed: true };
1808
+ } catch (err) {
1809
+ const msg = err instanceof Error ? err.message : String(err);
1810
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue WRITE failed for issue #${issueNumber}: ${msg.slice(0, 120)} - continuing unclaimed` });
1811
+ return { claimed: false, reason: "claim write failed" };
1812
+ }
1088
1813
  }
1089
1814
 
1090
1815
  /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
@@ -1119,16 +1844,22 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1119
1844
  return;
1120
1845
  }
1121
1846
  const { login } = await client.getAuthenticatedUser();
1847
+ let claimNote = "";
1122
1848
  try {
1123
1849
  await client.assignIssue(owner, name, candidate.number, login);
1124
- recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
1850
+ claimNote = `claimed issue #${candidate.number} as @${login}`;
1125
1851
  } catch {
1126
1852
  // Fallback: a visible claim comment carries the same placeholder
1127
1853
  // semantics when the App lacks the assignees write surface.
1128
1854
  await client.postIssueComment(owner, name, candidate.number, `TeamClaw (teamclaw/developer, @${login}) has taken ownership of this issue and is implementing it autonomously - a PR will follow.`);
1129
- recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1855
+ claimNote = `claimed issue #${candidate.number} via comment (assign unavailable)`;
1130
1856
  }
1131
- const s = await ensureStore();
1857
+ await withStoreLock(async () => {
1858
+ // #5792: one fresh handle under the lock (same stale-snapshot class
1859
+ // as the sweep transaction - the capture used to predate the claim
1860
+ // network writes).
1861
+ const s = await reloadStoreUnlocked();
1862
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "claim", text: claimNote });
1132
1863
  const freshRepo = s.repos.find((r) => r.id === repo.id);
1133
1864
  if (freshRepo) {
1134
1865
  // +60s guard: our own write (assign or comment) bumps updated_at;
@@ -1136,6 +1867,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1136
1867
  freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1137
1868
  await saveTeamAutoStore(s);
1138
1869
  }
1870
+ });
1139
1871
  } catch (err) {
1140
1872
  logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
1141
1873
  }
@@ -1162,6 +1894,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1162
1894
  if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1163
1895
  continue;
1164
1896
  }
1897
+ // #5823-loop: "Cancelled: ..." terminal states (#5818 closed / #5823
1898
+ // stand-down) are VERDICTS, not failures - recovering them re-opens the
1899
+ // issue, the next leg re-verdicts the same way, and the pair loops
1900
+ // forever burning a leg per sweep (live: #5827/#5829 two-loop at
1901
+ // 11:32/11:47). #claim-recovery is for real execution failures only.
1902
+ if (typeof task.error === "string" && task.error.startsWith("Cancelled:")) {
1903
+ continue;
1904
+ }
1165
1905
  if (s.failedClaimRecovery[taskId]) {
1166
1906
  continue;
1167
1907
  }
@@ -1278,57 +2018,84 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1278
2018
  void recoverFailedClaims();
1279
2019
  }, 60_000);
1280
2020
  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)}`);
2021
+ // #gc-periodic: worktree GC used to be boot-only with an enabled-repo
2022
+ // filter - two defects (live-instance audit 2026-11-14): (a) a disabled
2023
+ // repo ("do no NEW work") never got cleaned at all; (b) the single boot
2024
+ // pass ran before the device-flow auth warmed up, so every targetClosed
2025
+ // oracle call failed toward keep and closed-target orphans stayed (4
2026
+ // confirmed misretains). Now a recurring pass: first run delayed 60s
2027
+ // (auth warm), then every 6h - transient oracle failures self-heal on
2028
+ // the next pass.
2029
+ const gcDelay = setTimeout(() => {
2030
+ void runGcPass();
2031
+ gcTimer = setInterval(() => {
2032
+ void runGcPass();
2033
+ }, 6 * 60 * 60_000);
2034
+ gcTimer.unref?.();
2035
+ }, 60_000);
2036
+ gcDelay.unref?.();
2037
+ }
2038
+
2039
+ /** #gc-periodic: one full worktree GC pass over ALL bound repos (enabled
2040
+ * or not - GC is hygiene, not new work). Shared by the boot-delayed first
2041
+ * run and the 6h recurrence. */
2042
+ async function runGcPass(): Promise<void> {
2043
+ try {
2044
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
2045
+ // predicate below classifies EVERY task as terminal - GC must not run
2046
+ // blind over an unloaded team state (fails toward skip).
2047
+ if (!deps.getTeamState()) {
2048
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
2049
+ return;
1330
2050
  }
1331
- })();
2051
+ const s = await ensureStore();
2052
+ let removed = 0;
2053
+ let retained = 0;
2054
+ let stale = 0;
2055
+ const retainedDetails: string[] = [];
2056
+ for (const repo of s.repos) {
2057
+ const isTerminal = (taskId: string): boolean => {
2058
+ const t = deps.getTeamState()?.tasks[taskId];
2059
+ if (t && t.status !== "completed" && t.status !== "failed") return false;
2060
+ // Review F1: a terminal task with a pending write-back (push
2061
+ // ok / PR failed, 20s-retry window) still needs its worktree -
2062
+ // the retry delivers the PR from the surviving branch. Do not
2063
+ // GC until the write-back settles (doneAt or dropped). Issue
2064
+ // #24: terminally failed write-backs (failedAt) count as settled
2065
+ // too - safeRemoveTaskWorktree still retains unpushed work.
2066
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
2067
+ };
2068
+ // #gc3: no task record anywhere in team-state -> the owner ruled
2069
+ // outright deletion (2026-11-14, "全删") - such worktrees can never
2070
+ // be judged by any oracle and were retained forever.
2071
+ const isUnknownTask = (taskId: string): boolean => !deps.getTeamState()?.tasks?.[taskId];
2072
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle, isUnknownTask);
2073
+ removed += r.removed.length;
2074
+ retained += r.retained.length;
2075
+ stale += r.stale;
2076
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
2077
+ }
2078
+ if (removed || retained || stale) {
2079
+ // #173 follow-up 4: per-task retain reasons recorded as activity
2080
+ // (PR #167 promised "outcome logged + recorded as activity"); the
2081
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
2082
+ const detail = retainedDetails.length
2083
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
2084
+ : "";
2085
+ const stalePart = stale ? `, stale ${stale}` : "";
2086
+ await withStoreLock(async () => {
2087
+ // #5792: fresh handle under the lock - the capture predates the
2088
+ // (long) gcTaskWorktrees git awaits and could be orphaned by a
2089
+ // reconcile reload; saving it wiped concurrent registrations.
2090
+ const sGc = await reloadStoreUnlocked();
2091
+ recordActivity(sGc, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
2092
+ await saveTeamAutoStore(sGc);
2093
+ });
2094
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
2095
+ }
2096
+ } catch (err) {
2097
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
2098
+ }
1332
2099
  }
1333
2100
 
1334
2101
  async function stop(): Promise<void> {
@@ -1342,6 +2109,9 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1342
2109
  if (claimRecoveryTimer) {
1343
2110
  clearInterval(claimRecoveryTimer);
1344
2111
  }
2112
+ if (gcTimer) {
2113
+ clearInterval(gcTimer);
2114
+ }
1345
2115
  writebackTimer = null;
1346
2116
  }
1347
2117
  }
@@ -1364,7 +2134,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1364
2134
  return (s.activity ?? []).slice().reverse();
1365
2135
  }
1366
2136
 
1367
- return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
2137
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, claimTaskAtDequeue, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
1368
2138
 
1369
2139
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
1370
2140
  async function ensureWriteWorktree(repoId: string, taskId: string): Promise<string> {