@teamclaws/teamclaw 2026.11.6 → 2026.11.8

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 (43) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/http-server.js +18 -6
  4. package/dist/src/controller/managed-gateway-process.js +17 -1
  5. package/dist/src/controller/preview-proxy.js +55 -8
  6. package/dist/src/controller/provisioning/process-supervisor.js +11 -0
  7. package/dist/src/controller/route-table.js +2 -2
  8. package/dist/src/controller/security.js +85 -17
  9. package/dist/src/controller/task-assignment.js +62 -1
  10. package/dist/src/controller/task-routes.js +39 -2
  11. package/dist/src/controller/tunnel-manager.js +11 -0
  12. package/dist/src/controller/tunnel-routes.js +11 -0
  13. package/dist/src/controller/workspace-routes.js +16 -2
  14. package/dist/src/teamauto/github-client.js +19 -0
  15. package/dist/src/teamauto/repo-sync.js +96 -22
  16. package/dist/src/teamauto/scheduler.js +458 -36
  17. package/dist/src/teamauto/store.js +125 -3
  18. package/dist/src/types.js +5 -3
  19. package/dist/src/ui/app.js +2 -2
  20. package/dist/src/worker/worker-service.js +13 -1
  21. package/dist/src/workspace-browser.js +14 -0
  22. package/openclaw.plugin.json +5 -5
  23. package/package.json +4 -2
  24. package/src/config.ts +3 -3
  25. package/src/controller/http-server.ts +19 -5
  26. package/src/controller/managed-gateway-process.ts +17 -1
  27. package/src/controller/preview-proxy.ts +54 -8
  28. package/src/controller/provisioning/process-supervisor.ts +11 -0
  29. package/src/controller/route-table.ts +2 -2
  30. package/src/controller/security.ts +90 -17
  31. package/src/controller/task-assignment.ts +58 -1
  32. package/src/controller/task-routes.ts +39 -1
  33. package/src/controller/tunnel-manager.ts +12 -1
  34. package/src/controller/tunnel-routes.ts +11 -0
  35. package/src/controller/workspace-routes.ts +17 -2
  36. package/src/teamauto/github-client.ts +21 -1
  37. package/src/teamauto/repo-sync.ts +85 -21
  38. package/src/teamauto/scheduler.ts +434 -33
  39. package/src/teamauto/store.ts +133 -3
  40. package/src/types.ts +9 -7
  41. package/src/ui/app.js +2 -2
  42. package/src/worker/worker-service.ts +15 -1
  43. package/src/workspace-browser.ts +15 -0
@@ -242,12 +242,26 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
242
242
  entry.error = message;
243
243
  entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
244
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;
245
252
  entry.lastErrorAt = Date.now();
246
253
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
247
254
  // #5651: a non-fast-forward push whose rebase self-heal also failed is
248
255
  // deterministic - retrying the same push 6 more times just burns ~25min.
249
256
  // 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);
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;
251
265
  if (gaveUp && !entry.doneAt) {
252
266
  entry.failedAt = Date.now();
253
267
  recordActivity(store, {
@@ -373,17 +387,33 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
373
387
  return store;
374
388
  }
375
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
+
376
410
  // ---------- public repo management ----------
377
411
 
378
412
  async function addRepo(repoId: string, options: { schedule?: string; keywordInclude?: string[]; keywordExclude?: string[] } = {}): Promise<TeamAutoRepo> {
379
- const s = await ensureStore();
380
413
  const normalized = repoId.trim().replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, "");
381
414
  if (!/^[\w.-]+\/[\w.-]+$/.test(normalized)) {
382
415
  throw new Error(`invalid repo id: ${repoId} (expected owner/repo)`);
383
416
  }
384
- if (s.repos.some((r) => r.id === normalized)) {
385
- throw new Error(`${normalized} is already bound`);
386
- }
387
417
  const [owner, name] = normalized.split("/");
388
418
  const info = await client.getRepoInfo(owner, name);
389
419
  if (!info.permissions.pull) {
@@ -391,6 +421,13 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
391
421
  }
392
422
  const schedule = options.schedule?.trim() || "*/30 * * * *";
393
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
+ }
394
431
  const repo: TeamAutoRepo = {
395
432
  id: normalized,
396
433
  enabled: true,
@@ -529,6 +566,11 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
529
566
  return "sweep already in progress";
530
567
  }
531
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;
532
574
  const sweepStartedAt = Date.now();
533
575
  const etagBefore = client.etagStats();
534
576
  try {
@@ -579,7 +621,17 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
579
621
  // inside uses the *Unlocked core - the promise-chain mutex is NOT
580
622
  // re-entrant.
581
623
  let created = 0; // #5712: outside the lock scope - read after commit
624
+ let sweepSummary: string | null = null; // #5792: read after the commit
582
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;
583
635
  if (!dryRun) {
584
636
  // Advance only for acting sweeps: a dry-run must leave the cursors
585
637
  // untouched so the reported actions are actually performed next time
@@ -630,6 +682,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
630
682
  created++;
631
683
  }
632
684
  }
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
+ }
633
693
  const failedSince = repo.failedTasksSinceLastSweep ?? 0;
634
694
  repo.failedTasksSinceLastSweep = 0;
635
695
  repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
@@ -652,6 +712,7 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
652
712
  const etagAfter = client.etagStats();
653
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) });
654
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
655
716
  await saveTeamAutoStore(s);
656
717
  }); // withStoreLock: sweep transaction
657
718
  if (created > 0) {
@@ -659,8 +720,8 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
659
720
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
660
721
  });
661
722
  }
662
- logger.info(`TeamAuto: sweep ${repo.id} -> ${repo.lastSweepSummary}`);
663
- return repo.lastSweepSummary ?? "sweep complete";
723
+ logger.info(`TeamAuto: sweep ${repo.id} -> ${sweepSummary}`);
724
+ return sweepSummary ?? "sweep complete";
664
725
  } catch (err) {
665
726
  const message = err instanceof Error ? err.message : String(err);
666
727
  // Transient failures (network blips, restart-interrupted sweeps) used to
@@ -669,6 +730,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
669
730
  // backoff below, and a success clears the state in the block above.
670
731
  // #5712: failure bookkeeping is a store RMW too - same lock.
671
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;
672
737
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
673
738
  repo.lastSweepErrorAt = Date.now();
674
739
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
@@ -923,7 +988,13 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
923
988
  // window at init time is treated as delivered (the sentinel verified
924
989
  // those 23 were all normally delivered). Accepted trade-off: any
925
990
  // genuine pre-deploy orphan is pardoned once - signal > archaeology.
926
- if (!s.deliveredResultsInit) {
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) {
927
998
  s.deliveredResultsInit = true;
928
999
  for (const task of Object.values(state0.tasks ?? {})) {
929
1000
  if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
@@ -932,25 +1003,204 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
932
1003
  }
933
1004
  auditDirty = true;
934
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);
935
1013
  for (const task of Object.values(state0.tasks ?? {})) {
936
1014
  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;
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;
938
1022
  // #5738: once-per-task gate; the audit now persists its own
939
1023
  // mutations in the same pass (auditDirty save below), so the gate
940
1024
  // survives the next 20s disk reload instead of re-alarming.
941
1025
  const lastAlarmAt = s.orphanResultAlarms[task.id];
942
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;
943
1030
  // #5736: delivered-source is the DURABLE ledger (entry present OR
944
1031
  // recorded at prune time) - never the activity ring, which rolls in
945
1032
  // 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]);
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);
947
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
+ }
948
1127
  s.orphanResultAlarms[task.id] = Date.now();
949
1128
  auditDirty = true;
950
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)` });
951
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
952
1136
  }
953
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
+ }
954
1204
  if (Object.keys(s.orphanResultAlarms).length > 200) {
955
1205
  const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
956
1206
  for (const [k] of entries.slice(0, entries.length - 100)) delete s.orphanResultAlarms[k];
@@ -1105,20 +1355,70 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1105
1355
  // Workers often commit themselves inside the worktree - deliver
1106
1356
  // whenever the branch carries commits beyond base, not only when
1107
1357
  // commitAll just added new ones.
1108
- 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));
1109
1363
  if (deliverable) {
1110
- const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
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
+ });
1111
1369
  if (push.alreadyDelivered) {
1112
1370
  // #stale-base follow-up: a previous incarnation already
1113
1371
  // delivered this branch (PR merged). Skip PR creation and
1114
1372
  // the retry ladder - the task's work is on the remote.
1115
1373
  body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
1116
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)`;
1117
1380
  } 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)}`);
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) {
1119
1418
  entry.prUrl = pr.url;
1120
1419
  body = `${body}\n\nDelivered as PR: ${pr.url}`;
1121
1420
  recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1421
+ }
1122
1422
  }
1123
1423
  }
1124
1424
  await sync.removeTaskWorktree(repoId, task.id);
@@ -1132,6 +1432,12 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1132
1432
  // two comments 2s apart. Fail atomically instead: the entry
1133
1433
  // keeps its failed state + backoff and replays BOTH steps
1134
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
+ }
1135
1441
  prDeliveryFailed = true;
1136
1442
  }
1137
1443
  }
@@ -1139,6 +1445,23 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1139
1445
  continue;
1140
1446
  }
1141
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) {
1142
1465
  // #5725 / #5660 parity: the worker may have posted the same body
1143
1466
  // directly during its execution window (takeOwnership legs deliver
1144
1467
  // an ownership-wrap comment themselves). Posting again duplicates;
@@ -1174,16 +1497,33 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1174
1497
  // feedback (reviews + comments, whitespace-normalized): an exact
1175
1498
  // match means delivery already happened through the other
1176
1499
  // channel - mark done and record the skip.
1177
- const normalized = body.replace(/\s+/g, " ").trim();
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);
1178
1518
  const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => [] as string[]);
1179
- if (existing.includes(normalized)) {
1519
+ if (existing.some((b) => stripCollapsedFooter(b) === normalized)) {
1180
1520
  entry.doneAt = Date.now();
1181
1521
  entry.inFlightAt = undefined;
1182
1522
  writebackDone = true;
1183
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` });
1184
1524
  logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
1185
1525
  } else {
1186
- await client.postPullReviewComment(owner, name, entry.targetId, body);
1526
+ await client.postPullReviewComment(owner, name, entry.targetId, postBody);
1187
1527
  entry.doneAt = Date.now();
1188
1528
  entry.inFlightAt = undefined;
1189
1529
  writebackDone = true;
@@ -1288,9 +1628,17 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1288
1628
  // Without this, every normally-delivered task alarms as an orphan once
1289
1629
  // its entry is pruned and its ok line rolls off the ring.
1290
1630
  s.deliveredResults ??= {};
1631
+ s.prDeliveries ??= {};
1291
1632
  for (const w of s.writebacks) {
1292
1633
  if (w.doneAt) {
1293
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
+ }
1294
1642
  }
1295
1643
  }
1296
1644
  const deliveredEntries = Object.entries(s.deliveredResults);
@@ -1316,7 +1664,10 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1316
1664
  // withStoreLock. Public entry takes the lock; the sweep transaction calls
1317
1665
  // the *Unlocked core directly because IT already holds the lock (the
1318
1666
  // promise-chain mutex is NOT re-entrant - nesting would deadlock).
1319
- await withStoreLock(() => registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey));
1667
+ await withStoreLock(async () => {
1668
+ await reloadStoreUnlocked(); // #5792: fresh handle under the lock
1669
+ return registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey);
1670
+ });
1320
1671
  }
1321
1672
 
1322
1673
  async function registerWritebackUnlocked(taskId: string, action: "issueComment" | "prComment" | "createIssue" | "createPR", repoId: string, targetId: number | null, cycleKey?: string): Promise<void> {
@@ -1324,14 +1675,24 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1324
1675
  if (s.writebacks.some((w) => w.taskId === taskId)) {
1325
1676
  return;
1326
1677
  }
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.
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).
1333
1694
  if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1334
- return;
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)` });
1335
1696
  }
1336
1697
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1337
1698
  await saveTeamAutoStore(s);
@@ -1388,7 +1749,21 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1388
1749
  const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
1389
1750
  login = (await client.getAuthenticatedUser()).login;
1390
1751
  const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
1391
- const external = comments.filter((c) => c.user !== login);
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
+ });
1392
1767
  if (external.length > 0) {
1393
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` });
1394
1769
  return { claimed: false, reason: "external activity" };
@@ -1404,17 +1779,24 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1404
1779
  // caller swallows rejections - so record the audit line here and return
1405
1780
  // a non-retrying result.
1406
1781
  try {
1782
+ let claimNote = "";
1407
1783
  try {
1408
1784
  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)` });
1785
+ claimNote = `claimed issue #${issueNumber} as @${login} (at dequeue)`;
1410
1786
  } catch {
1411
1787
  // Fallback: a visible claim comment carries the same placeholder
1412
1788
  // semantics when the App lacks the assignees write surface.
1413
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.`);
1414
- recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)` });
1790
+ claimNote = `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)`;
1415
1791
  }
1416
- const s = await ensureStore();
1417
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 });
1418
1800
  const freshRepo = s.repos.find((r) => r.id === repoId);
1419
1801
  if (freshRepo) {
1420
1802
  // +60s guard: our own write (assign or comment) bumps updated_at.
@@ -1462,17 +1844,22 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1462
1844
  return;
1463
1845
  }
1464
1846
  const { login } = await client.getAuthenticatedUser();
1847
+ let claimNote = "";
1465
1848
  try {
1466
1849
  await client.assignIssue(owner, name, candidate.number, login);
1467
- 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}`;
1468
1851
  } catch {
1469
1852
  // Fallback: a visible claim comment carries the same placeholder
1470
1853
  // semantics when the App lacks the assignees write surface.
1471
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.`);
1472
- 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)`;
1473
1856
  }
1474
- const s = await ensureStore();
1475
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 });
1476
1863
  const freshRepo = s.repos.find((r) => r.id === repo.id);
1477
1864
  if (freshRepo) {
1478
1865
  // +60s guard: our own write (assign or comment) bumps updated_at;
@@ -1507,6 +1894,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1507
1894
  if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1508
1895
  continue;
1509
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
+ }
1510
1905
  if (s.failedClaimRecovery[taskId]) {
1511
1906
  continue;
1512
1907
  }
@@ -1688,8 +2083,14 @@ export function createTeamAutoScheduler(deps: TeamAutoSchedulerDeps) {
1688
2083
  ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1689
2084
  : "";
1690
2085
  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);
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
+ });
1693
2094
  logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1694
2095
  }
1695
2096
  } catch (err) {