@teamclaws/teamclaw 2026.11.6 → 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 (41) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/http-server.js +2 -2
  4. package/dist/src/controller/managed-gateway-process.js +17 -1
  5. package/dist/src/controller/provisioning/process-supervisor.js +11 -0
  6. package/dist/src/controller/route-table.js +2 -2
  7. package/dist/src/controller/security.js +30 -15
  8. package/dist/src/controller/task-assignment.js +62 -1
  9. package/dist/src/controller/task-routes.js +39 -2
  10. package/dist/src/controller/tunnel-manager.js +11 -0
  11. package/dist/src/controller/tunnel-routes.js +11 -0
  12. package/dist/src/controller/workspace-routes.js +16 -2
  13. package/dist/src/teamauto/github-client.js +19 -0
  14. package/dist/src/teamauto/repo-sync.js +96 -22
  15. package/dist/src/teamauto/scheduler.js +458 -36
  16. package/dist/src/teamauto/store.js +125 -3
  17. package/dist/src/types.js +5 -3
  18. package/dist/src/ui/app.js +2 -2
  19. package/dist/src/worker/worker-service.js +13 -1
  20. package/dist/src/workspace-browser.js +14 -0
  21. package/openclaw.plugin.json +5 -5
  22. package/package.json +4 -2
  23. package/src/config.ts +3 -3
  24. package/src/controller/http-server.ts +2 -2
  25. package/src/controller/managed-gateway-process.ts +17 -1
  26. package/src/controller/provisioning/process-supervisor.ts +11 -0
  27. package/src/controller/route-table.ts +2 -2
  28. package/src/controller/security.ts +30 -15
  29. package/src/controller/task-assignment.ts +58 -1
  30. package/src/controller/task-routes.ts +39 -1
  31. package/src/controller/tunnel-manager.ts +12 -1
  32. package/src/controller/tunnel-routes.ts +11 -0
  33. package/src/controller/workspace-routes.ts +17 -2
  34. package/src/teamauto/github-client.ts +21 -1
  35. package/src/teamauto/repo-sync.ts +85 -21
  36. package/src/teamauto/scheduler.ts +434 -33
  37. package/src/teamauto/store.ts +133 -3
  38. package/src/types.ts +9 -7
  39. package/src/ui/app.js +2 -2
  40. package/src/worker/worker-service.ts +15 -1
  41. package/src/workspace-browser.ts +15 -0
@@ -177,12 +177,26 @@ export function createTeamAutoScheduler(deps) {
177
177
  entry.error = message;
178
178
  entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
179
179
  entry.attempts = (entry.attempts ?? 0) + 1;
180
+ // #5815: identical-error-text circuit breaker. The same message three
181
+ // ladder runs in a row is a structural dead end (zero-diff 422s burned
182
+ // six runs live) - stop early instead of burning the full ladder.
183
+ const sameText = entry.lastErrorText !== undefined && message.slice(0, 120) === entry.lastErrorText.slice(0, 120);
184
+ entry.lastErrorText = message.slice(0, 200);
185
+ entry.lastErrorStreak = sameText ? (entry.lastErrorStreak ?? 0) + 1 : 1;
186
+ const deterministicStreak = (entry.lastErrorStreak ?? 0) >= 3;
180
187
  entry.lastErrorAt = Date.now();
181
188
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
182
189
  // #5651: a non-fast-forward push whose rebase self-heal also failed is
183
190
  // deterministic - retrying the same push 6 more times just burns ~25min.
184
191
  // Dead-letter immediately (the next sweep re-claims on a fresh branch).
185
- const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS || /push rejected \(non-fast-forward\) and rebase self-heal failed/.test(message);
192
+ // #5767 (ggcode, 2026-11-18): deterministic hook/environment failures are
193
+ // not transient - a repo pre-commit calling bash4+ builtins on a bash3.2
194
+ // host ("mapfile: command not found") retried 6 times for 33 minutes
195
+ // before dying. Same fail-fast as the #5651 non-fast-forward signature:
196
+ // hook-not-found / command-not-found / not-executable signatures are
197
+ // structural, every retry is a guaranteed repeat.
198
+ const deterministicHookFailure = /(?:hooks?\/[^:]*: line \d+: \w+: command not found|hook declined|cannot run hook|exited with error before)/.test(message);
199
+ 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;
186
200
  if (gaveUp && !entry.doneAt) {
187
201
  entry.failedAt = Date.now();
188
202
  recordActivity(store, {
@@ -293,16 +307,31 @@ export function createTeamAutoScheduler(deps) {
293
307
  }
294
308
  return store;
295
309
  }
310
+ /**
311
+ * #5792 (ggcode, 2026-11-19): one fresh handle per locked transaction.
312
+ * The 20s reconcile pass reassigns the closure `store` from disk on EVERY
313
+ * pass; a section that captured `ensureStore()` BEFORE that flip and saves
314
+ * AFTER it re-writes a stale snapshot, erasing everything persisted in
315
+ * between. Live shape (the #5792 zero-fire regression): the sweep captured
316
+ * its handle before the unlocked network phase; registerWritebackUnlocked -
317
+ * called inside the sweep's locked tx - re-resolved the flipped closure, so
318
+ * the entry was pushed and saved onto the NEW object while the tx tail
319
+ * re-saved the OLD handle: "created 2/2" logged, writebacks[] empty on
320
+ * disk, zero ladder rows, orphan alarms ~10min after completion, 100% of
321
+ * tasks after the 3b1a175 deploy restart re-based the tick grid onto the
322
+ * sweep window. Every load->mutate->save section that spans an await
323
+ * boundary must take its handle UNDER the lock via this helper.
324
+ */
325
+ async function reloadStoreUnlocked() {
326
+ store = await loadTeamAutoStore();
327
+ return store;
328
+ }
296
329
  // ---------- public repo management ----------
297
330
  async function addRepo(repoId, options = {}) {
298
- const s = await ensureStore();
299
331
  const normalized = repoId.trim().replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, "");
300
332
  if (!/^[\w.-]+\/[\w.-]+$/.test(normalized)) {
301
333
  throw new Error(`invalid repo id: ${repoId} (expected owner/repo)`);
302
334
  }
303
- if (s.repos.some((r) => r.id === normalized)) {
304
- throw new Error(`${normalized} is already bound`);
305
- }
306
335
  const [owner, name] = normalized.split("/");
307
336
  const info = await client.getRepoInfo(owner, name);
308
337
  if (!info.permissions.pull) {
@@ -310,6 +339,13 @@ export function createTeamAutoScheduler(deps) {
310
339
  }
311
340
  const schedule = options.schedule?.trim() || "*/30 * * * *";
312
341
  nextFireMs(schedule); // validates: throws ScheduleParseError for unsupported expressions
342
+ // #5792: captured AFTER the network await - a capture before
343
+ // getRepoInfo could be orphaned by a reconcile reload and the bind
344
+ // save would then erase concurrent writeback registrations.
345
+ const s = await ensureStore();
346
+ if (s.repos.some((r) => r.id === normalized)) {
347
+ throw new Error(`${normalized} is already bound`);
348
+ }
313
349
  const repo = {
314
350
  id: normalized,
315
351
  enabled: true,
@@ -447,6 +483,11 @@ export function createTeamAutoScheduler(deps) {
447
483
  return "sweep already in progress";
448
484
  }
449
485
  sweeping.add(repo.id);
486
+ // #5792: frozen identity for the under-lock rebind below - the repo node
487
+ // used inside the tx must come from the FRESH store handle, not this
488
+ // possibly-orphaned snapshot.
489
+ const repoOuter = repo;
490
+ const repoOuterId = repo.id;
450
491
  const sweepStartedAt = Date.now();
451
492
  const etagBefore = client.etagStats();
452
493
  try {
@@ -498,7 +539,17 @@ export function createTeamAutoScheduler(deps) {
498
539
  // inside uses the *Unlocked core - the promise-chain mutex is NOT
499
540
  // re-entrant.
500
541
  let created = 0; // #5712: outside the lock scope - read after commit
542
+ let sweepSummary = null; // #5792: read after the commit
501
543
  await withStoreLock(async () => {
544
+ // #5792 (ggcode): bind ONE fresh handle (and repo node) under the
545
+ // lock. The outer `s` was captured before the unlocked network phase;
546
+ // a 20s reconcile reload during sweepRepo orphaned it, and the tail
547
+ // save below then erased the writeback registrations that
548
+ // registerWritebackUnlocked had just persisted onto the reloaded
549
+ // closure ("created 2/2" logged, writebacks[] empty on disk, zero
550
+ // ladder rows - the #5792 zero-fire regression).
551
+ const s = await reloadStoreUnlocked();
552
+ const repo = s.repos.find((r) => r.id === repoOuterId) ?? repoOuter;
502
553
  if (!dryRun) {
503
554
  // Advance only for acting sweeps: a dry-run must leave the cursors
504
555
  // untouched so the reported actions are actually performed next time
@@ -551,6 +602,14 @@ export function createTeamAutoScheduler(deps) {
551
602
  created++;
552
603
  }
553
604
  }
605
+ // #5824: the admission check consumed capped.length UP FRONT,
606
+ // but duplicate-active (or dead-letter) skips never enqueue - the
607
+ // budget burned on nothing (live: created 0/2, budget 11->13).
608
+ // Refund the difference so the ledger tracks CREATED tasks only;
609
+ // the capped.length admission gate above still bounds the batch.
610
+ if (created < capped.length) {
611
+ s.budget.tasksToday = Math.max(0, s.budget.tasksToday - (capped.length - created));
612
+ }
554
613
  const failedSince = repo.failedTasksSinceLastSweep ?? 0;
555
614
  repo.failedTasksSinceLastSweep = 0;
556
615
  repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
@@ -574,6 +633,7 @@ export function createTeamAutoScheduler(deps) {
574
633
  const etagAfter = client.etagStats();
575
634
  pushSweepRecord(repo, { at: Date.now(), ok: true, summary: repo.lastSweepSummary ?? "sweep complete", durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
576
635
  recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
636
+ sweepSummary = repo.lastSweepSummary; // #5792: post-commit readers use the tx-scoped repo
577
637
  await saveTeamAutoStore(s);
578
638
  }); // withStoreLock: sweep transaction
579
639
  if (created > 0) {
@@ -581,8 +641,8 @@ export function createTeamAutoScheduler(deps) {
581
641
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
582
642
  });
583
643
  }
584
- logger.info(`TeamAuto: sweep ${repo.id} -> ${repo.lastSweepSummary}`);
585
- return repo.lastSweepSummary ?? "sweep complete";
644
+ logger.info(`TeamAuto: sweep ${repo.id} -> ${sweepSummary}`);
645
+ return sweepSummary ?? "sweep complete";
586
646
  }
587
647
  catch (err) {
588
648
  const message = err instanceof Error ? err.message : String(err);
@@ -592,6 +652,10 @@ export function createTeamAutoScheduler(deps) {
592
652
  // backoff below, and a success clears the state in the block above.
593
653
  // #5712: failure bookkeeping is a store RMW too - same lock.
594
654
  await withStoreLock(async () => {
655
+ // #5792: fresh handle under the lock (same stale-snapshot class as
656
+ // the sweep transaction above).
657
+ const s = await reloadStoreUnlocked();
658
+ const repo = s.repos.find((r) => r.id === repoOuterId) ?? repoOuter;
595
659
  repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
596
660
  repo.lastSweepErrorAt = Date.now();
597
661
  repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
@@ -843,7 +907,13 @@ export function createTeamAutoScheduler(deps) {
843
907
  // window at init time is treated as delivered (the sentinel verified
844
908
  // those 23 were all normally delivered). Accepted trade-off: any
845
909
  // genuine pre-deploy orphan is pardoned once - signal > archaeology.
846
- if (!s.deliveredResultsInit) {
910
+ // #5770: gate the one-time migration on an EMPTY table, not just the
911
+ // flag - a generation-window store clobber can wipe the flag while
912
+ // the table survives (or vice versa), and a re-run re-stamps
913
+ // completedAt as deliveredAt for the current window, forging delivery
914
+ // records that mask genuine orphans (live: 57cc2770/e975ddac stamped
915
+ // at the exact completion millisecond, audit went silent).
916
+ if (!s.deliveredResultsInit && Object.keys(s.deliveredResults).length === 0) {
847
917
  s.deliveredResultsInit = true;
848
918
  for (const task of Object.values(state0.tasks ?? {})) {
849
919
  if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
@@ -852,10 +922,23 @@ export function createTeamAutoScheduler(deps) {
852
922
  }
853
923
  auditDirty = true;
854
924
  }
925
+ let alarmedThisPass = 0; // #5772: at most ONE orphan alarm per settle pass
926
+ // #5777: tasks whose direct-send delivery lands AFTER completion
927
+ // (live: delivered 5m21s post-completed, zero ladder/ledger trail)
928
+ // would alarm at the first tick. Grace period first; at grace
929
+ // expiry the audit checks the GitHub surface ONCE for a teamclaw
930
+ // marker comment and back-fills the ledger when the product exists.
931
+ const ghClient = createGithubClient(auth);
855
932
  for (const task of Object.values(state0.tasks ?? {})) {
856
933
  if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-"))
857
934
  continue;
858
- if (task.completedAt && Date.now() - task.completedAt > 24 * 3600_000)
935
+ // #5772: 24h -> 6h audit window. A restart replays the audit over
936
+ // HISTORICAL completed tasks whose write-back entries are long
937
+ // pruned and whose ledger truth died in a generation-window clobber
938
+ // - that population is exactly the false-alarm storm (14 healthy
939
+ // tasks at once, live). Genuine orphans surface within hours; the
940
+ // remaining tail is not worth storm-shaped noise.
941
+ if (task.completedAt && Date.now() - task.completedAt > 6 * 3600_000)
859
942
  continue;
860
943
  // #5738: once-per-task gate; the audit now persists its own
861
944
  // mutations in the same pass (auditDirty save below), so the gate
@@ -863,16 +946,198 @@ export function createTeamAutoScheduler(deps) {
863
946
  const lastAlarmAt = s.orphanResultAlarms[task.id];
864
947
  if (lastAlarmAt)
865
948
  continue;
949
+ // #5777: direct-send grace - do not judge before a slow worker
950
+ // direct-post has had its chance.
951
+ if (task.completedAt && Date.now() - task.completedAt < 10 * 60_000)
952
+ continue;
866
953
  // #5736: delivered-source is the DURABLE ledger (entry present OR
867
954
  // recorded at prune time) - never the activity ring, which rolls in
868
955
  // hours and made every normal delivery a false orphan.
869
- const hasEntry = s.writebacks.some((w) => w.taskId === task.id) || Boolean(s.deliveredResults[task.id]);
956
+ // #5770: a REAL delivery happens >= one reconcile tick (20s) after
957
+ // completion; a ledger stamp within 2s of completedAt is a migration
958
+ // artifact, not evidence of delivery - do not let it silence the
959
+ // orphan audit.
960
+ const deliveredAt = s.deliveredResults[task.id];
961
+ const ledgerIsArtifact = deliveredAt !== undefined && task.completedAt !== undefined && Math.abs(deliveredAt - task.completedAt) < 2000;
962
+ const hasEntry = s.writebacks.some((w) => w.taskId === task.id) || (deliveredAt !== undefined && !ledgerIsArtifact);
870
963
  if (!hasEntry) {
964
+ // #5777: grace expired and still no books - verify the GitHub
965
+ // surface ONCE for a teamclaw marker comment (worker direct-send
966
+ // shape) before declaring an orphan. A marker hit back-fills the
967
+ // ledger; only a genuinely bare issue alarms.
968
+ // #5781: channel-aware verification - a prReview task's product
969
+ // lives on the PR review surface (reviews + PR conversation
970
+ // comments), which getIssueCommentBodies cannot see (live:
971
+ // d7152fe0 delivered two COMMENTED reviews, issue-surface check
972
+ // matched zero, false orphan). Route by target type: PR number
973
+ // -> feedback bodies (reviews + comments), issue number ->
974
+ // issue comments.
975
+ const prNumMatch = /(?:PR|pull request) #(\d+)/i.exec(`${task.title}`);
976
+ const numMatch = prNumMatch ?? /issue #(\d+)/.exec(`${task.title}`);
977
+ const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(`${task.description}`);
978
+ // #5783 contract 5b: the fetched bodies must stay visible BELOW the
979
+ // evidence check - the self-heal gate distinguishes "surface
980
+ // completely silent" (rescue re-delivery) from "surface carries
981
+ // bare/foreign bodies that match no evidence" (orphan alarm).
982
+ let targetBodies = [];
983
+ if (numMatch && repoMatch) {
984
+ const [o, n] = repoMatch[1].split("/");
985
+ const targetNum = Number(numMatch[1]);
986
+ targetBodies = prNumMatch
987
+ ? await ghClient.getPullFeedbackBodies(o, n, targetNum).catch(() => [])
988
+ : await ghClient.getIssueCommentBodies(o, n, targetNum).catch(() => []);
989
+ // #5780: workers deliver in more shapes than the ladder marker -
990
+ // narrative bodies ("Fix delivered ... via TeamClaw autonomous")
991
+ // and branch-reference footers carry no [teamclaw:] prefix and
992
+ // zeroed the evidence check (live: 8fdf5efd false-alarmed).
993
+ // #5730/23da7606 sharpening: exotic bodies with ZERO teamclaw
994
+ // references exist too (first wild case, mk:false on all
995
+ // three predicates). The universal fallback: a direct-send
996
+ // body IS the task result - fingerprint match on its first
997
+ // 60 chars catches every shape, marker or not.
998
+ const resultFingerprint = task.result.replace(/\s+/g, " ").trim().slice(0, 60);
999
+ 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)));
1000
+ if (ghEvidence) {
1001
+ // #5785 reconciliation (rebase of #284 onto the 085fc67
1002
+ // chain): the undelivered-PR self-check now lives in the
1003
+ // dedicated PR-face settle audit below - a REST probe via
1004
+ // listPullsByHead plus the durable prDeliveries ledger. This
1005
+ // inline local-evidence variant (085fc67/e882af2) is removed
1006
+ // so a WRITE task with issue-face evidence but a missing PR
1007
+ // leg has exactly ONE alarm path, not two competing ones.
1008
+ s.deliveredResults[task.id] = Date.now();
1009
+ auditDirty = true;
1010
+ 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)` });
1011
+ await saveTeamAutoStore(s).catch(() => { });
1012
+ continue;
1013
+ }
1014
+ }
1015
+ // #5792 self-heal (ggcode): the registration was lost in
1016
+ // flight (live: the sweep transaction's stale tail-save erased
1017
+ // it - "created 2/2" logged, zero ladder rows). Re-register from
1018
+ // the already-parsed target so the ladder re-delivers the result
1019
+ // instead of only alarming: prReview bodies have NO direct-send
1020
+ // surface, so without this the review verdict (e.g. a REQUEST
1021
+ // CHANGES on a live PR) is lost forever.
1022
+ // #5783 contract 5b gate: the rescue is for a COMPLETELY SILENT
1023
+ // surface only. When the surface already carries bodies that
1024
+ // match no evidence (live shape: a bare worker direct-post or a
1025
+ // foreign/human review), the audit must take the verdict the
1026
+ // evidence predicate hands it - the alarm. Re-registering there
1027
+ // swallowed the alarm (5b regression after bb09e1e) and would
1028
+ // re-post a duplicate beside the unverified body.
1029
+ // #5785 reconciliation: WRITE tasks are ALSO out of scope - their
1030
+ // lost registration is the PR-face settle audit's jurisdiction
1031
+ // (listPullsByHead probe + prDeliveries ledger below). A healed
1032
+ // issueComment entry here would sit in s.writebacks and mask
1033
+ // that audit exactly like the live incident's comment-shaped
1034
+ // evidence did, or re-deliver a comment beside an unknown
1035
+ // push/PR state - the double-delivery hazard #5785 documents.
1036
+ if (numMatch && repoMatch && targetBodies.length === 0 && task.writeMode !== "write") {
1037
+ const healTargetNum = Number(numMatch[1]);
1038
+ await registerWritebackUnlocked(task.id, prNumMatch ? "prComment" : "issueComment", repoMatch[1], healTargetNum);
1039
+ if (s.writebacks.some((w) => w.taskId === task.id)) {
1040
+ 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` });
1041
+ logger.warn(`TeamAuto: orphan self-heal re-registered ${prNumMatch ? "prComment" : "issueComment"} #${healTargetNum} for ${task.id}`);
1042
+ auditDirty = true;
1043
+ await saveTeamAutoStore(s).catch(() => { });
1044
+ if (++alarmedThisPass >= 1)
1045
+ break; // storm cap: one audit ACTION per pass
1046
+ continue;
1047
+ }
1048
+ // Re-registration was skipped (e.g. another task's OPEN entry
1049
+ // owns this target) - fall through to the alarm below.
1050
+ }
871
1051
  s.orphanResultAlarms[task.id] = Date.now();
872
1052
  auditDirty = true;
873
1053
  recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `orphan result alarm: task ${task.id} completed with a result but has NO write-back entry and no delivery record (registration lost - ladder redundancy silently absent)` });
874
1054
  logger.warn(`TeamAuto: orphan completed task ${task.id} without write-back entry`);
1055
+ // #5772: persist the gate IMMEDIATELY on the alarming branch -
1056
+ // deferring to the block-tail save lost the write to a
1057
+ // restart-timeline clobber once already (#5738 regression).
1058
+ await saveTeamAutoStore(s).catch(() => { });
1059
+ if (++alarmedThisPass >= 1)
1060
+ break; // storm cap: one per pass
1061
+ }
1062
+ }
1063
+ // #5785 (ggcode, 2026-11-18): undelivered-PR audit - the PR-face
1064
+ // sibling of the orphan-result audit above. A completed WRITE task
1065
+ // delivers on TWO faces: the issue/review comment (verified above)
1066
+ // and the push+createPR leg, which per the WRITE collaboration
1067
+ // contract ONLY the write-back ladder performs. The orphan audit is
1068
+ // comment-shaped: a worker direct-post on the issue face back-fills
1069
+ // deliveredResults and silences it, while the PR face never came
1070
+ // into existence (live: branch pushed, zero PR across a 10m42s
1071
+ // three-probe window, writebacks [] throughout, gate silent - the
1072
+ // issue-face delivery masked the missing PR face entirely).
1073
+ // Contract: a completed WRITE task inside the audit window must
1074
+ // (a) still own a write-back entry (the ladder owns its PR face;
1075
+ // delivery failures surface via the retry ladder and the
1076
+ // "completed task delivery LOST" alarm), or (b) carry a durable
1077
+ // PR-face record (prDeliveries - stamped at prune time from
1078
+ // entry.prUrl), or (c) show a PR (any state) whose head is its task
1079
+ // branch. None of the three => ONE undelivered-PR alarm line.
1080
+ let prAlarmedThisPass = 0;
1081
+ for (const task of Object.values(state0.tasks ?? {})) {
1082
+ if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-"))
1083
+ continue;
1084
+ // Same shape predicate as the delivery path's isTeamAutoWrite:
1085
+ // only dispatched WRITE tasks carry the PR-face contract.
1086
+ if (task.writeMode !== "write" || !task.projectDir?.includes("__task-"))
1087
+ continue;
1088
+ // The window math needs completedAt (the task system stamps it on
1089
+ // completion); tasks without it are not judgeable here.
1090
+ if (!task.completedAt)
1091
+ continue;
1092
+ if (Date.now() - task.completedAt > 6 * 3600_000)
1093
+ continue;
1094
+ if (s.undeliveredPrAlarms?.[task.id])
1095
+ continue;
1096
+ // Same #5777 grace as the orphan audit: a slow ladder delivery (or
1097
+ // a manual push+PR) gets its window before judgement.
1098
+ if (Date.now() - task.completedAt < 10 * 60_000)
1099
+ continue;
1100
+ if (s.writebacks.some((w) => w.taskId === task.id))
1101
+ continue;
1102
+ if (s.prDeliveries?.[task.id])
1103
+ continue;
1104
+ const prRepoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(`${task.description}`);
1105
+ const taskBranch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
1106
+ let prFaceUrl = null;
1107
+ if (prRepoMatch) {
1108
+ const [prOwner, prName] = prRepoMatch[1].split("/");
1109
+ // Distinguish fetch FAILURE (null -> retry next settle pass; a
1110
+ // blip must not gate the check permanently) from a definitive
1111
+ // empty list (-> alarm).
1112
+ const pulls = await ghClient.listPullsByHead(prOwner, prName, taskBranch).catch(() => null);
1113
+ if (pulls === null)
1114
+ continue;
1115
+ const hit = pulls.find((p) => p.htmlUrl) ?? pulls[0];
1116
+ if (hit)
1117
+ prFaceUrl = hit.htmlUrl || `#${hit.number}`;
1118
+ }
1119
+ s.undeliveredPrAlarms ??= {};
1120
+ s.undeliveredPrAlarms[task.id] = Date.now();
1121
+ auditDirty = true;
1122
+ if (prFaceUrl) {
1123
+ s.prDeliveries ??= {};
1124
+ s.prDeliveries[task.id] = prFaceUrl;
1125
+ 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)` });
1126
+ }
1127
+ else {
1128
+ 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)` });
1129
+ logger.warn(`TeamAuto: undelivered PR for completed WRITE task ${task.id} (branch ${taskBranch})`);
1130
+ // Same #5738 discipline as the orphan alarm: persist the gate on
1131
+ // the alarming branch, not only at the block tail.
1132
+ await saveTeamAutoStore(s).catch(() => { });
875
1133
  }
1134
+ if (++prAlarmedThisPass >= 1)
1135
+ break; // storm cap: one per pass
1136
+ }
1137
+ if (s.undeliveredPrAlarms && Object.keys(s.undeliveredPrAlarms).length > 200) {
1138
+ const prGateEntries = Object.entries(s.undeliveredPrAlarms).sort((a, b) => a[1] - b[1]);
1139
+ for (const [k] of prGateEntries.slice(0, prGateEntries.length - 100))
1140
+ delete s.undeliveredPrAlarms[k];
876
1141
  }
877
1142
  if (Object.keys(s.orphanResultAlarms).length > 200) {
878
1143
  const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
@@ -1029,21 +1294,75 @@ export function createTeamAutoScheduler(deps) {
1029
1294
  // Workers often commit themselves inside the worktree - deliver
1030
1295
  // whenever the branch carries commits beyond base, not only when
1031
1296
  // commitAll just added new ones.
1032
- const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch));
1297
+ // #5815: compare against the REMOTE base tip, not the stale
1298
+ // local baseline - a stale checkout makes a zero-commit branch
1299
+ // look deliverable and the PR dies on a deterministic 422
1300
+ // (zero diff) six times in a row.
1301
+ const deliverable = committed || (await sync.branchHasCommits(wtDir, info.defaultBranch, info.cloneUrl));
1033
1302
  if (deliverable) {
1034
- const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
1303
+ const push = await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch, (pushErr) => {
1304
+ // #5788: dedicated push-failure activity line - symmetric
1305
+ // with the createPR ladder rows.
1306
+ 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` });
1307
+ });
1035
1308
  if (push.alreadyDelivered) {
1036
1309
  // #stale-base follow-up: a previous incarnation already
1037
1310
  // delivered this branch (PR merged). Skip PR creation and
1038
1311
  // the retry ladder - the task's work is on the remote.
1039
1312
  body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
1040
1313
  recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `already delivered on ${branch} - skipped duplicate push/PR` });
1314
+ // #5785: this shape delivered a PR in a previous
1315
+ // incarnation - record the PR face so the settle audit
1316
+ // does not re-verify it against GitHub forever after.
1317
+ s.prDeliveries ??= {};
1318
+ s.prDeliveries[task.id] = `branch:${branch} (previous delivery)`;
1041
1319
  }
1042
1320
  else {
1043
- const pr = await client.createPullRequest(repoId.split("/")[0], repoId.split("/")[1], branch, info.defaultBranch, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 120), `${task.result.trim()}\n${MARKER_FOOTER(role)}`);
1044
- entry.prUrl = pr.url;
1045
- body = `${body}\n\nDelivered as PR: ${pr.url}`;
1046
- recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1321
+ let pr;
1322
+ let prSkippedForZeroDiff = false;
1323
+ try {
1324
+ 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)}`);
1325
+ }
1326
+ catch (prErr) {
1327
+ // #5788: a 422 on a freshly-pushed head almost always
1328
+ // means the push NEVER LANDED (live: two stranded legs,
1329
+ // generic "Validation Failed" masked it). Probe the head
1330
+ // and disambiguate the failure text before rethrowing.
1331
+ const pmsg = prErr instanceof Error ? prErr.message : String(prErr);
1332
+ if (/422|Validation Failed/i.test(pmsg)) {
1333
+ const probe = await sync.branchExistsRemotely(wtDir, branch).catch(() => false);
1334
+ if (!probe) {
1335
+ throw new Error(`createPR 422 with head branch ABSENT on remote - the PUSH never landed for ${branch} (see push-failure activity; local-only branch)`);
1336
+ }
1337
+ // #5815: branch IS present but PR still 422 - the zero-
1338
+ // diff shape (head is an ancestor of base: the task
1339
+ // completed with analysis-only output / misplaced-repo
1340
+ // verdict). NOT retriable: every ladder run is the same
1341
+ // 422. Deliver the result as the comment directly with
1342
+ // an analysis note, like the #5719 failed-write path.
1343
+ const zeroDiff = await sync.branchIsAncestorOfRemoteBase(wtDir, branch, info.defaultBranch).catch(() => false);
1344
+ if (zeroDiff) {
1345
+ body = `${body}\n\nNo code changes (analysis-only completion - no PR needed).`;
1346
+ 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)` });
1347
+ prDeliveryFailed = false;
1348
+ prSkippedForZeroDiff = true;
1349
+ }
1350
+ if (!prSkippedForZeroDiff)
1351
+ throw prErr;
1352
+ }
1353
+ else {
1354
+ throw prErr;
1355
+ }
1356
+ }
1357
+ if (prSkippedForZeroDiff) {
1358
+ // fall through to the comment delivery below with the
1359
+ // analysis-amended body - no PR to attach.
1360
+ }
1361
+ else if (pr) {
1362
+ entry.prUrl = pr.url;
1363
+ body = `${body}\n\nDelivered as PR: ${pr.url}`;
1364
+ recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
1365
+ }
1047
1366
  }
1048
1367
  }
1049
1368
  await sync.removeTaskWorktree(repoId, task.id);
@@ -1058,6 +1377,12 @@ export function createTeamAutoScheduler(deps) {
1058
1377
  // two comments 2s apart. Fail atomically instead: the entry
1059
1378
  // keeps its failed state + backoff and replays BOTH steps
1060
1379
  // (PR first, then comment) on the next attempt.
1380
+ // #5767: a COMPLETED task whose delivery exhausts is the worst
1381
+ // outcome (work done, product lost, owner unaware) - surface it
1382
+ // as its own alarm line, not just the retry-ladder failure row.
1383
+ if (task.status === "completed") {
1384
+ 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` });
1385
+ }
1061
1386
  prDeliveryFailed = true;
1062
1387
  }
1063
1388
  }
@@ -1065,6 +1390,24 @@ export function createTeamAutoScheduler(deps) {
1065
1390
  continue;
1066
1391
  }
1067
1392
  if (entry.action === "issueComment" && entry.targetId) {
1393
+ // #5818 defense-in-depth: the target may have been closed since
1394
+ // enqueue/dequeue - commenting on a closed issue pollutes the
1395
+ // resolution record. Re-check state first; closed -> skip with a
1396
+ // visible line (the result stays in the task record for manual
1397
+ // retrieval if ever needed).
1398
+ try {
1399
+ const targetIssue = await client.getIssue(owner, name, entry.targetId);
1400
+ if (targetIssue.state !== "open") {
1401
+ entry.doneAt = Date.now();
1402
+ entry.inFlightAt = undefined;
1403
+ writebackDone = true;
1404
+ 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)` });
1405
+ logger.info(`TeamAuto: write-back ${entry.taskId} skipped - target issue #${entry.targetId} closed`);
1406
+ }
1407
+ }
1408
+ catch { /* state check failed - attempt delivery anyway */ }
1409
+ }
1410
+ if (entry.action === "issueComment" && entry.targetId && !writebackDone) {
1068
1411
  // #5725 / #5660 parity: the worker may have posted the same body
1069
1412
  // directly during its execution window (takeOwnership legs deliver
1070
1413
  // an ownership-wrap comment themselves). Posting again duplicates;
@@ -1102,9 +1445,26 @@ export function createTeamAutoScheduler(deps) {
1102
1445
  // feedback (reviews + comments, whitespace-normalized): an exact
1103
1446
  // match means delivery already happened through the other
1104
1447
  // channel - mark done and record the skip.
1105
- const normalized = body.replace(/\s+/g, " ").trim();
1448
+ // #5783: the prComment channel shipped BARE worker results - no
1449
+ // MARKER_FOOTER - so the evidence predicate (#5777-#5781 chain)
1450
+ // never matched its own deliveries and every prReview leg
1451
+ // false-alarmed. Append the footer like every other channel.
1452
+ // #5783 residual (same day): the shared body construction above
1453
+ // ALREADY appends one MARKER_FOOTER for every channel, so the
1454
+ // extra append here shipped the marker TWICE; and
1455
+ // getPullFeedbackBodies returns whitespace-COLLAPSED bodies, so
1456
+ // a "\n---\n[teamclaw:]" strip can never match the existing
1457
+ // side - a footered worker direct-post still double-delivered.
1458
+ // Post exactly ONE footer (stripping any footer blocks the
1459
+ // worker echoed into its result) and dedupe footer-agnostic
1460
+ // AFTER collapsing, so bare, footered and twice-footered shapes
1461
+ // all compare equal on both sides.
1462
+ const collapse = (t) => t.replace(/\s+/g, " ").trim();
1463
+ const stripCollapsedFooter = (t) => collapse(t).replace(/ ?--- ?\[teamclaw:[^\]]+\].*$/, "").trim();
1464
+ const postBody = `${body.replace(/\n?---\n\[teamclaw:[^\]]+\][^\n]*/g, "").trimEnd()}\n${MARKER_FOOTER(role)}`;
1465
+ const normalized = stripCollapsedFooter(body);
1106
1466
  const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => []);
1107
- if (existing.includes(normalized)) {
1467
+ if (existing.some((b) => stripCollapsedFooter(b) === normalized)) {
1108
1468
  entry.doneAt = Date.now();
1109
1469
  entry.inFlightAt = undefined;
1110
1470
  writebackDone = true;
@@ -1112,7 +1472,7 @@ export function createTeamAutoScheduler(deps) {
1112
1472
  logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
1113
1473
  }
1114
1474
  else {
1115
- await client.postPullReviewComment(owner, name, entry.targetId, body);
1475
+ await client.postPullReviewComment(owner, name, entry.targetId, postBody);
1116
1476
  entry.doneAt = Date.now();
1117
1477
  entry.inFlightAt = undefined;
1118
1478
  writebackDone = true;
@@ -1216,9 +1576,17 @@ export function createTeamAutoScheduler(deps) {
1216
1576
  // Without this, every normally-delivered task alarms as an orphan once
1217
1577
  // its entry is pruned and its ok line rolls off the ring.
1218
1578
  s.deliveredResults ??= {};
1579
+ s.prDeliveries ??= {};
1219
1580
  for (const w of s.writebacks) {
1220
1581
  if (w.doneAt) {
1221
1582
  s.deliveredResults[w.taskId] = w.doneAt;
1583
+ // #5785: PR-face delivery must be durable too - the entry (and its
1584
+ // prUrl) dies at the prune below, and the undelivered-PR audit needs
1585
+ // to tell "PR opened, entry pruned" apart from "registration never
1586
+ // happened" without re-probing GitHub for every healthy task.
1587
+ if (w.prUrl) {
1588
+ s.prDeliveries[w.taskId] = w.prUrl;
1589
+ }
1222
1590
  }
1223
1591
  }
1224
1592
  const deliveredEntries = Object.entries(s.deliveredResults);
@@ -1244,21 +1612,34 @@ export function createTeamAutoScheduler(deps) {
1244
1612
  // withStoreLock. Public entry takes the lock; the sweep transaction calls
1245
1613
  // the *Unlocked core directly because IT already holds the lock (the
1246
1614
  // promise-chain mutex is NOT re-entrant - nesting would deadlock).
1247
- await withStoreLock(() => registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey));
1615
+ await withStoreLock(async () => {
1616
+ await reloadStoreUnlocked(); // #5792: fresh handle under the lock
1617
+ return registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey);
1618
+ });
1248
1619
  }
1249
1620
  async function registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey) {
1250
1621
  const s = await ensureStore();
1251
1622
  if (s.writebacks.some((w) => w.taskId === taskId)) {
1252
1623
  return;
1253
1624
  }
1254
- // #269 per-target dedupe (enqueue side): a second registration for
1255
- // the SAME target + action with no doneAt yet is a duplicate in the
1256
- // making - the delivery pass would fan out two comments onto one
1257
- // target. Skip it; the pending original still delivers the content.
1258
- // targetId null (create* actions) cannot be target-deduped pre-delivery
1259
- // and is excluded by the taskId check above.
1625
+ // #5785 (ggcode, 2026-11-18): the enqueue-side per-target dedupe is
1626
+ // REMOVED. It skipped a registration whenever ANY pending entry aimed at
1627
+ // the same target + action, on the assumption "the pending original
1628
+ // still delivers the content" - but write-back content is per-task
1629
+ // (task.result): a different task's entry delivers ITS OWN result,
1630
+ // never this one. Live shape: a later leg on the same issue enrolled
1631
+ // while an earlier leg's entry was still pending; the later task's
1632
+ // registration was silently swallowed, so its completed WRITE result
1633
+ // never entered the ladder - the branch sat on the remote with no PR
1634
+ // (writebacks [] across the whole 10m42s observation window) and only
1635
+ // the worker's issue-face direct-post kept the orphan audit quiet.
1636
+ // Duplicate protection is fully covered by the other three guards:
1637
+ // (1) same-taskId idempotency above (a re-registration of ONE task),
1638
+ // (2) the #269 delivery-side per-target cap (ONE entry per target key
1639
+ // per pass - co-target rows serialize across 20s passes), and
1640
+ // (3) exact-body dedupe at post time (worker direct-posts).
1260
1641
  if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1261
- return;
1642
+ 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)` });
1262
1643
  }
1263
1644
  s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1264
1645
  await saveTeamAutoStore(s);
@@ -1313,7 +1694,22 @@ export function createTeamAutoScheduler(deps) {
1313
1694
  const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
1314
1695
  login = (await client.getAuthenticatedUser()).login;
1315
1696
  const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
1316
- const external = comments.filter((c) => c.user !== login);
1697
+ // #5819: same-account multi-seat blindness. Filtering purely by
1698
+ // account excludes ALL seats sharing the bot account - a sibling seat
1699
+ // claiming the same issue ([claim master_coordinator] ...) was
1700
+ // invisible and both seats implemented it (live: #5812 double
1701
+ // delivery). Content-aware: same-account comments carrying a SEAT
1702
+ // declaration ([claim X]/[done X]) count as external UNLESS X is one
1703
+ // of teamauto's own roles (those are this pipeline's own prior legs -
1704
+ // retry legs must not stand down on their own history).
1705
+ const seatDecl = /\[(claim|done)\s+([a-z_-]+)\s*\]/i;
1706
+ const teamautoRoles = new Set(["developer", "qa", "architect", "security-engineer", "security-engineer-role"]);
1707
+ const external = comments.filter((c) => {
1708
+ if (c.user !== login)
1709
+ return true;
1710
+ const m = seatDecl.exec(String(c.body ?? ""));
1711
+ return Boolean(m && !teamautoRoles.has(m[2].toLowerCase()));
1712
+ });
1317
1713
  if (external.length > 0) {
1318
1714
  recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: ${external.length} external comment(s) since enqueue on issue #${issueNumber} (latest by @${external[external.length - 1]?.user}) - standing down` });
1319
1715
  return { claimed: false, reason: "external activity" };
@@ -1330,18 +1726,25 @@ export function createTeamAutoScheduler(deps) {
1330
1726
  // caller swallows rejections - so record the audit line here and return
1331
1727
  // a non-retrying result.
1332
1728
  try {
1729
+ let claimNote = "";
1333
1730
  try {
1334
1731
  await client.assignIssue(owner, name, issueNumber, login);
1335
- recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} as @${login} (at dequeue)` });
1732
+ claimNote = `claimed issue #${issueNumber} as @${login} (at dequeue)`;
1336
1733
  }
1337
1734
  catch {
1338
1735
  // Fallback: a visible claim comment carries the same placeholder
1339
1736
  // semantics when the App lacks the assignees write surface.
1340
1737
  await client.postIssueComment(owner, name, issueNumber, `TeamClaw (teamclaw/developer, @${login}) has taken ownership of this issue and is implementing it autonomously - a PR will follow.`);
1341
- recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)` });
1738
+ claimNote = `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)`;
1342
1739
  }
1343
- const s = await ensureStore();
1344
1740
  await withStoreLock(async () => {
1741
+ // #5792: one fresh handle under the lock. The old shape captured
1742
+ // `s` before the claim writes (network awaits) and saved it inside
1743
+ // the lock - a reconcile reload in between orphaned the handle and
1744
+ // the save wiped concurrent registrations; the claim activity note
1745
+ // also only persisted when it rode the same (possibly stale) object.
1746
+ const s = await reloadStoreUnlocked();
1747
+ recordActivity(s, { at: Date.now(), repoId, kind: "claim", text: claimNote });
1345
1748
  const freshRepo = s.repos.find((r) => r.id === repoId);
1346
1749
  if (freshRepo) {
1347
1750
  // +60s guard: our own write (assign or comment) bumps updated_at.
@@ -1389,18 +1792,23 @@ export function createTeamAutoScheduler(deps) {
1389
1792
  return;
1390
1793
  }
1391
1794
  const { login } = await client.getAuthenticatedUser();
1795
+ let claimNote = "";
1392
1796
  try {
1393
1797
  await client.assignIssue(owner, name, candidate.number, login);
1394
- recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} as @${login}` });
1798
+ claimNote = `claimed issue #${candidate.number} as @${login}`;
1395
1799
  }
1396
1800
  catch {
1397
1801
  // Fallback: a visible claim comment carries the same placeholder
1398
1802
  // semantics when the App lacks the assignees write surface.
1399
1803
  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.`);
1400
- recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1804
+ claimNote = `claimed issue #${candidate.number} via comment (assign unavailable)`;
1401
1805
  }
1402
- const s = await ensureStore();
1403
1806
  await withStoreLock(async () => {
1807
+ // #5792: one fresh handle under the lock (same stale-snapshot class
1808
+ // as the sweep transaction - the capture used to predate the claim
1809
+ // network writes).
1810
+ const s = await reloadStoreUnlocked();
1811
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "claim", text: claimNote });
1404
1812
  const freshRepo = s.repos.find((r) => r.id === repo.id);
1405
1813
  if (freshRepo) {
1406
1814
  // +60s guard: our own write (assign or comment) bumps updated_at;
@@ -1435,6 +1843,14 @@ export function createTeamAutoScheduler(deps) {
1435
1843
  if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1436
1844
  continue;
1437
1845
  }
1846
+ // #5823-loop: "Cancelled: ..." terminal states (#5818 closed / #5823
1847
+ // stand-down) are VERDICTS, not failures - recovering them re-opens the
1848
+ // issue, the next leg re-verdicts the same way, and the pair loops
1849
+ // forever burning a leg per sweep (live: #5827/#5829 two-loop at
1850
+ // 11:32/11:47). #claim-recovery is for real execution failures only.
1851
+ if (typeof task.error === "string" && task.error.startsWith("Cancelled:")) {
1852
+ continue;
1853
+ }
1438
1854
  if (s.failedClaimRecovery[taskId]) {
1439
1855
  continue;
1440
1856
  }
@@ -1618,8 +2034,14 @@ export function createTeamAutoScheduler(deps) {
1618
2034
  ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1619
2035
  : "";
1620
2036
  const stalePart = stale ? `, stale ${stale}` : "";
1621
- recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1622
- await saveTeamAutoStore(s);
2037
+ await withStoreLock(async () => {
2038
+ // #5792: fresh handle under the lock - the capture predates the
2039
+ // (long) gcTaskWorktrees git awaits and could be orphaned by a
2040
+ // reconcile reload; saving it wiped concurrent registrations.
2041
+ const sGc = await reloadStoreUnlocked();
2042
+ recordActivity(sGc, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
2043
+ await saveTeamAutoStore(sGc);
2044
+ });
1623
2045
  logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1624
2046
  }
1625
2047
  }