@teamclaws/teamclaw 2026.11.5 → 2026.11.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/README.md +17 -11
  2. package/dist/src/config.js +3 -3
  3. package/dist/src/controller/config-routes.js +7 -3
  4. package/dist/src/controller/controller-service.js +12 -1
  5. package/dist/src/controller/http-server.js +2 -2
  6. package/dist/src/controller/managed-gateway-process.js +17 -1
  7. package/dist/src/controller/provisioning/container-shared.js +6 -1
  8. package/dist/src/controller/provisioning/docker.js +1 -1
  9. package/dist/src/controller/provisioning/kubernetes.js +1 -1
  10. package/dist/src/controller/provisioning/process-supervisor.js +23 -1
  11. package/dist/src/controller/provisioning-config.js +8 -0
  12. package/dist/src/controller/route-table.js +2 -2
  13. package/dist/src/controller/security.js +30 -15
  14. package/dist/src/controller/task-assignment.js +126 -2
  15. package/dist/src/controller/task-results.js +34 -3
  16. package/dist/src/controller/task-routes.js +63 -3
  17. package/dist/src/controller/tunnel-manager.js +11 -0
  18. package/dist/src/controller/tunnel-routes.js +11 -0
  19. package/dist/src/controller/worker-provisioning.js +35 -0
  20. package/dist/src/controller/worker-routes.js +21 -6
  21. package/dist/src/controller/workspace-routes.js +16 -2
  22. package/dist/src/openclaw-workspace.js +39 -20
  23. package/dist/src/task-executor.js +44 -3
  24. package/dist/src/teamauto/github-client.js +107 -5
  25. package/dist/src/teamauto/repo-sync.js +172 -26
  26. package/dist/src/teamauto/scanner.js +22 -1
  27. package/dist/src/teamauto/scheduler.js +988 -190
  28. package/dist/src/teamauto/store.js +171 -3
  29. package/dist/src/teamauto/write-payload-guard.js +209 -0
  30. package/dist/src/types.js +11 -3
  31. package/dist/src/ui/app.js +2 -2
  32. package/dist/src/worker/tools.js +5 -0
  33. package/dist/src/worker/worker-service.js +13 -1
  34. package/dist/src/workspace-browser.js +14 -0
  35. package/openclaw.plugin.json +5 -5
  36. package/package.json +4 -2
  37. package/src/config.ts +3 -3
  38. package/src/controller/config-routes.ts +7 -3
  39. package/src/controller/controller-service.ts +12 -1
  40. package/src/controller/http-server.ts +2 -2
  41. package/src/controller/managed-gateway-process.ts +17 -1
  42. package/src/controller/provisioning/backend-contract.ts +4 -0
  43. package/src/controller/provisioning/container-shared.ts +6 -1
  44. package/src/controller/provisioning/docker.ts +1 -1
  45. package/src/controller/provisioning/kubernetes.ts +1 -1
  46. package/src/controller/provisioning/process-supervisor.ts +23 -1
  47. package/src/controller/provisioning-config.ts +9 -0
  48. package/src/controller/route-table.ts +2 -2
  49. package/src/controller/security.ts +30 -15
  50. package/src/controller/task-assignment.ts +128 -1
  51. package/src/controller/task-results.ts +33 -3
  52. package/src/controller/task-routes.ts +64 -2
  53. package/src/controller/tunnel-manager.ts +12 -1
  54. package/src/controller/tunnel-routes.ts +11 -0
  55. package/src/controller/worker-provisioning.ts +35 -0
  56. package/src/controller/worker-routes.ts +21 -7
  57. package/src/controller/workspace-routes.ts +17 -2
  58. package/src/openclaw-workspace.ts +43 -23
  59. package/src/task-executor.ts +46 -3
  60. package/src/teamauto/github-client.ts +103 -5
  61. package/src/teamauto/repo-sync.ts +158 -23
  62. package/src/teamauto/scanner.ts +23 -2
  63. package/src/teamauto/scheduler.ts +883 -113
  64. package/src/teamauto/store.ts +205 -3
  65. package/src/teamauto/write-payload-guard.ts +222 -0
  66. package/src/types.ts +30 -7
  67. package/src/ui/app.js +2 -2
  68. package/src/worker/tools.ts +5 -0
  69. package/src/worker/worker-service.ts +15 -1
  70. package/src/workspace-browser.ts +15 -0
@@ -7,9 +7,11 @@ import { getActiveDefaultRole, validateActiveRoleId } from "../profile-loader.js
7
7
  import { createGithubClient } from "./github-client.js";
8
8
  import { learnNorms, renderNormsBlock } from "./norms.js";
9
9
  import { createRepoSync, teamAutoProjectDir } from "./repo-sync.js";
10
+ import { ENVELOPE_LEAK_MARKER } from "./write-payload-guard.js";
10
11
  import { nextFireMs } from "./schedule.js";
11
12
  import { resolveTeamAutoPaths } from "./store.js";
12
13
  import { advanceCursors, sweepRepo } from "./scanner.js";
14
+ import { withStoreLock } from "./store.js";
13
15
  import { consumeDailyBudget, defaultCursors, defaultPolicy, loadTeamAutoStore, pushTeamAutoActivity, saveTeamAutoStore, pushSweepRecord, } from "./store.js";
14
16
  /**
15
17
  * TeamAuto scheduler: per-repo cron sweeps -> TeamClaw tasks -> GitHub
@@ -175,9 +177,26 @@ export function createTeamAutoScheduler(deps) {
175
177
  entry.error = message;
176
178
  entry.inFlightAt = undefined; // #269: failed dispatch releases the intent
177
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;
178
187
  entry.lastErrorAt = Date.now();
179
188
  entry.nextAttemptAt = writebackRetryDueAt(entry.attempts, entry.lastErrorAt);
180
- const gaveUp = options.terminal === true || entry.attempts >= TEAMAUTO_WRITEBACK_MAX_ATTEMPTS;
189
+ // #5651: a non-fast-forward push whose rebase self-heal also failed is
190
+ // deterministic - retrying the same push 6 more times just burns ~25min.
191
+ // Dead-letter immediately (the next sweep re-claims on a fresh branch).
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;
181
200
  if (gaveUp && !entry.doneAt) {
182
201
  entry.failedAt = Date.now();
183
202
  recordActivity(store, {
@@ -281,22 +300,38 @@ export function createTeamAutoScheduler(deps) {
281
300
  let store = null;
282
301
  let writebackTimer = null;
283
302
  let claimRecoveryTimer = null;
303
+ let gcTimer = null;
284
304
  async function ensureStore() {
285
305
  if (!store) {
286
306
  store = await loadTeamAutoStore();
287
307
  }
288
308
  return store;
289
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
+ }
290
329
  // ---------- public repo management ----------
291
330
  async function addRepo(repoId, options = {}) {
292
- const s = await ensureStore();
293
331
  const normalized = repoId.trim().replace(/^https:\/\/github\.com\//, "").replace(/\.git$/, "");
294
332
  if (!/^[\w.-]+\/[\w.-]+$/.test(normalized)) {
295
333
  throw new Error(`invalid repo id: ${repoId} (expected owner/repo)`);
296
334
  }
297
- if (s.repos.some((r) => r.id === normalized)) {
298
- throw new Error(`${normalized} is already bound`);
299
- }
300
335
  const [owner, name] = normalized.split("/");
301
336
  const info = await client.getRepoInfo(owner, name);
302
337
  if (!info.permissions.pull) {
@@ -304,6 +339,13 @@ export function createTeamAutoScheduler(deps) {
304
339
  }
305
340
  const schedule = options.schedule?.trim() || "*/30 * * * *";
306
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
+ }
307
349
  const repo = {
308
350
  id: normalized,
309
351
  enabled: true,
@@ -441,6 +483,11 @@ export function createTeamAutoScheduler(deps) {
441
483
  return "sweep already in progress";
442
484
  }
443
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;
444
491
  const sweepStartedAt = Date.now();
445
492
  const etagBefore = client.etagStats();
446
493
  try {
@@ -452,6 +499,10 @@ export function createTeamAutoScheduler(deps) {
452
499
  for (let attempt = 1; attempt <= SWEEP_INPLACE_RETRIES; attempt++) {
453
500
  try {
454
501
  swept = await sweepRepo(repo, client);
502
+ // #5706 (ggcode): sweep observability - "no new work" is ambiguous
503
+ // between an empty fetch (etag 304 / API silence) and full filter
504
+ // rejection. Log the funnel so starvation diagnoses itself.
505
+ logger.info(`TeamAuto: scan funnel ${repo.id}: fetched ${swept.issues.length} issue(s)/${swept.pulls.length} pull(s) -> ${swept.candidates.length} candidate(s) (since=${repo.cursors.lastIssueSince ? new Date(repo.cursors.lastIssueSince).toISOString() : "unset"})`);
455
506
  break;
456
507
  }
457
508
  catch (err) {
@@ -478,79 +529,120 @@ export function createTeamAutoScheduler(deps) {
478
529
  // -> still zero candidates -> dryRunDone never set).
479
530
  repo.dryRunDone = true;
480
531
  }
481
- if (!dryRun) {
482
- // Advance only for acting sweeps: a dry-run must leave the cursors
483
- // untouched so the reported actions are actually performed next time
484
- // instead of being marked as already-seen.
485
- advanceCursors(repo, issues, pulls, Date.now(), commits);
486
- }
487
- // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
488
- // pull candidates, so a busy repo would otherwise starve them forever
489
- // (cap filled every sweep, lastFullReviewAt never advancing). They are
490
- // at most one cycle (3 sections) per interval, so this stays bounded.
491
- const fullReviews = candidates.filter((c) => c.kind === "fullReview");
492
- const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
493
- const capped = [...fullReviews, ...regular];
494
- let created = 0;
495
- const summary = [`found ${candidates.length} candidate(s)`];
496
- // #265: surface the commits delta so the third signal source is
497
- // observable in sweep summaries (was silently dead before).
498
- if (newCommits.length > 0) {
499
- summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
500
- }
501
- if (capped.length && dryRun) {
502
- summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
503
- repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
504
- }
505
- else if (capped.length) {
506
- if (!consumeDailyBudget(s, capped.length)) {
507
- summary.push("skipped: daily task budget exhausted");
532
+ // #5712 (ggcode) / teamclaw#274: the ENTIRE sweep store transaction -
533
+ // cursor/seen advance, budget consume, task activity, write-back
534
+ // registrations, summary, sweep record, and the commit save - is one
535
+ // read-modify-write section. It previously raced the (locked) 20s
536
+ // write-back reconcile: reconcile's disk reload + tail save clobbered
537
+ // the sweep's writes (live: 20:30 batch lost summary/budget/activity
538
+ // while later claim/write-back saves survived). registerWriteback
539
+ // inside uses the *Unlocked core - the promise-chain mutex is NOT
540
+ // re-entrant.
541
+ let created = 0; // #5712: outside the lock scope - read after commit
542
+ let sweepSummary = null; // #5792: read after the commit
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;
553
+ if (!dryRun) {
554
+ // Advance only for acting sweeps: a dry-run must leave the cursors
555
+ // untouched so the reported actions are actually performed next time
556
+ // instead of being marked as already-seen.
557
+ advanceCursors(repo, issues, pulls, Date.now(), commits);
508
558
  }
509
- else {
510
- for (const candidate of capped) {
511
- const taskId = enqueueCandidate(repo, candidate);
512
- if (taskId === "dead-lettered") {
513
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
559
+ // Joint full reviews bypass the per-sweep cap: they append AFTER issue/
560
+ // pull candidates, so a busy repo would otherwise starve them forever
561
+ // (cap filled every sweep, lastFullReviewAt never advancing). They are
562
+ // at most one cycle (3 sections) per interval, so this stays bounded.
563
+ const fullReviews = candidates.filter((c) => c.kind === "fullReview");
564
+ const regular = candidates.filter((c) => c.kind !== "fullReview").slice(0, Math.max(0, repo.policy.maxTasksPerSweep - fullReviews.length));
565
+ const capped = [...fullReviews, ...regular];
566
+ const summary = [`found ${candidates.length} candidate(s)`];
567
+ // #265: surface the commits delta so the third signal source is
568
+ // observable in sweep summaries (was silently dead before).
569
+ if (newCommits.length > 0) {
570
+ summary.push(`${newCommits.length} new commit(s) (HEAD ${newCommits[0].sha.slice(0, 7)})`);
571
+ }
572
+ if (capped.length && dryRun) {
573
+ summary.push(...capped.map((c) => `DRY-RUN would ${c.kind}: ${c.title}`));
574
+ repo.lastSweepSummary = `dry-run: ${summary.join("; ")}`;
575
+ }
576
+ else if (capped.length) {
577
+ if (!consumeDailyBudget(s, capped.length)) {
578
+ summary.push("skipped: daily task budget exhausted");
579
+ }
580
+ else {
581
+ for (const candidate of capped) {
582
+ const taskId = enqueueCandidate(repo, candidate);
583
+ if (taskId === "dead-lettered") {
584
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `dead-lettered after ${TEAMAUTO_DEAD_LETTER_ATTEMPTS} failed attempts: ${candidate.kind}: ${candidate.title}` });
585
+ }
586
+ else if (taskId) {
587
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
588
+ // #claim-dequeue (user 2026-11-15): claiming at ENQUEUE locked a
589
+ // string of issues behind the one-writer-per-repo queue while
590
+ // they waited - and blindly claimed issues where external
591
+ // collaborators had started working in the scan-to-claim gap.
592
+ // Claiming now happens at DEQUEUE (claimTaskAtDequeue, called
593
+ // from the task assignment path) after a fresh conflict check.
594
+ const action = candidate.kind === "prReview"
595
+ ? "prComment"
596
+ : candidate.kind === "fullReview"
597
+ ? "createIssue"
598
+ : candidate.kind === "prRework"
599
+ ? "prComment"
600
+ : "issueComment";
601
+ await registerWritebackUnlocked(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
602
+ created++;
603
+ }
514
604
  }
515
- else if (taskId) {
516
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "task", text: `${candidate.kind}: ${candidate.title}` });
517
- claimIssue(repo, candidate); // #268: visible claim at enqueue time
518
- const action = candidate.kind === "prReview"
519
- ? "prComment"
520
- : candidate.kind === "fullReview"
521
- ? "createIssue"
522
- : "issueComment";
523
- registerWriteback(taskId, action, repo.id, candidate.number || null, candidate.cycle !== undefined ? String(candidate.cycle) : undefined);
524
- created++;
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
+ }
613
+ const failedSince = repo.failedTasksSinceLastSweep ?? 0;
614
+ repo.failedTasksSinceLastSweep = 0;
615
+ repo.lastSweepSummary = `created ${created}/${capped.length} task(s)${failedSince > 0 ? `; FAILED ${failedSince} since last sweep` : ""}`;
616
+ if (capped.some((c) => c.kind === "fullReview")) {
617
+ repo.cursors.lastFullReviewAt = Date.now();
525
618
  }
526
- }
527
- repo.lastSweepSummary = `created ${created}/${capped.length} task(s)`;
528
- if (capped.some((c) => c.kind === "fullReview")) {
529
- repo.cursors.lastFullReviewAt = Date.now();
530
619
  }
531
620
  }
532
- }
533
- else {
534
- repo.lastSweepSummary = "no new work";
535
- }
536
- repo.lastSweepAt = Date.now();
537
- if (isAutoPause(repo.pausedReason)) {
538
- repo.pausedReason = null;
539
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
540
- }
541
- repo.sweepFailures = 0;
542
- repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
543
- const etagAfter = client.etagStats();
544
- 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) });
545
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: repo.lastSweepSummary ?? "sweep complete" });
546
- await saveTeamAutoStore(s);
621
+ else {
622
+ const failedSince0 = repo.failedTasksSinceLastSweep ?? 0;
623
+ repo.failedTasksSinceLastSweep = 0;
624
+ repo.lastSweepSummary = failedSince0 > 0 ? `no new work; FAILED ${failedSince0} since last sweep` : "no new work";
625
+ }
626
+ repo.lastSweepAt = Date.now();
627
+ if (isAutoPause(repo.pausedReason)) {
628
+ repo.pausedReason = null;
629
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: "sweep recovered, auto-pause cleared" });
630
+ }
631
+ repo.sweepFailures = 0;
632
+ repo.lastAttemptAt = Date.now(); // #266: success is also an attempt
633
+ const etagAfter = client.etagStats();
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) });
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
637
+ await saveTeamAutoStore(s);
638
+ }); // withStoreLock: sweep transaction
547
639
  if (created > 0) {
548
640
  await deps.onTasksCreated().catch((err) => {
549
641
  logger.warn(`TeamAuto: auto-assign trigger failed: ${String(err)}`);
550
642
  });
551
643
  }
552
- logger.info(`TeamAuto: sweep ${repo.id} -> ${repo.lastSweepSummary}`);
553
- return repo.lastSweepSummary ?? "sweep complete";
644
+ logger.info(`TeamAuto: sweep ${repo.id} -> ${sweepSummary}`);
645
+ return sweepSummary ?? "sweep complete";
554
646
  }
555
647
  catch (err) {
556
648
  const message = err instanceof Error ? err.message : String(err);
@@ -558,15 +650,22 @@ export function createTeamAutoScheduler(deps) {
558
650
  // pause a repo FOREVER - teamclaw sat auto-paused 15h on one "fetch
559
651
  // failed". Auto-pauses are cooldowns now: the timer retries after the
560
652
  // backoff below, and a success clears the state in the block above.
561
- repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
562
- repo.lastSweepErrorAt = Date.now();
563
- repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
564
- const failClass = classifySweepError(err);
565
- repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
566
- const etagAfter = client.etagStats();
567
- pushSweepRecord(repo, { at: Date.now(), ok: false, summary: `sweep failed[${failClass}]: ${message}`, failClass, durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
568
- recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
569
- await saveTeamAutoStore(s).catch(() => { });
653
+ // #5712: failure bookkeeping is a store RMW too - same lock.
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;
659
+ repo.sweepFailures = (repo.sweepFailures ?? 0) + 1;
660
+ repo.lastSweepErrorAt = Date.now();
661
+ repo.lastAttemptAt = repo.lastSweepErrorAt; // #266: failures must be visible without inferring from lastSweepErrorAt
662
+ const failClass = classifySweepError(err);
663
+ repo.pausedReason = `sweep failed[${failClass}]: ${message}`;
664
+ const etagAfter = client.etagStats();
665
+ pushSweepRecord(repo, { at: Date.now(), ok: false, summary: `sweep failed[${failClass}]: ${message}`, failClass, durationMs: Date.now() - sweepStartedAt, etagCalls: Math.max(0, etagAfter.calls - etagBefore.calls), etag304Hits: Math.max(0, etagAfter.hits - etagBefore.hits) });
666
+ recordActivity(s, { at: Date.now(), repoId: repo.id, kind: "sweep", text: `sweep failed[${failClass}] (auto-retry in ~${sweepBackoffMinutesFor(failClass, repo.sweepFailures)}min): ${message}` });
667
+ await saveTeamAutoStore(s).catch(() => { });
668
+ }); // withStoreLock: failure bookkeeping
570
669
  logger.warn(`TeamAuto: sweep failed for ${repo.id}: ${message}`);
571
670
  return `error: ${message}`;
572
671
  }
@@ -737,6 +836,24 @@ export function createTeamAutoScheduler(deps) {
737
836
  }
738
837
  }
739
838
  async function doReconcileWritebacks() {
839
+ // #2677: the WHOLE read-modify-write section holds the store lock -
840
+ // an unlocked reload+save here clobbered a concurrently-registered
841
+ // write-back entry (see store.ts withStoreLock).
842
+ await withStoreLock(async () => {
843
+ await doReconcileWritebacksLocked();
844
+ }).catch((err) => {
845
+ // #5677 ask: never swallow a delivery-pass crash silently - a lost
846
+ // entry with zero trace is invisible; surface it in the log AND the
847
+ // activity feed so the failure class is diagnosable.
848
+ const msg = err instanceof Error ? err.message : String(err);
849
+ logger.warn(`TeamAuto: write-back pass CRASHED (entries may retry next tick): ${msg}`);
850
+ void ensureStore().then((s) => {
851
+ recordActivity(s, { at: Date.now(), repoId: "*", kind: "writeback", text: `delivery pass crashed: ${msg.slice(0, 140)}` });
852
+ return saveTeamAutoStore(s);
853
+ }).catch(() => { });
854
+ });
855
+ }
856
+ async function doReconcileWritebacksLocked() {
740
857
  // #269 recurrence: re-read the store from disk EVERY pass - the
741
858
  // closure cache is a startup snapshot that never sees another
742
859
  // process's persisted inFlightAt/doneAt, which is exactly how the
@@ -758,12 +875,282 @@ export function createTeamAutoScheduler(deps) {
758
875
  if (dead) {
759
876
  logger.warn(`TeamAuto: dropping dead write-back ${w.taskId} (${t ? "task failed without result" : "task missing"})`);
760
877
  deadOnes.push(w);
878
+ // #5641: the 3-day architect-leg outage was invisible because a
879
+ // failed-without-result task produced NO activity line and the next
880
+ // sweep summary still said "created 3/3". Record both surfaces.
881
+ recordActivity(s, { at: Date.now(), repoId: w.repoId, kind: "task", text: `task failed without result, write-back dropped: ${w.taskId}${t?.error ? ` (${String(t.error).slice(0, 120)})` : ""}` });
882
+ const failedRepo = s.repos.find((r) => r.id === w.repoId);
883
+ if (failedRepo) {
884
+ failedRepo.failedTasksSinceLastSweep = (failedRepo.failedTasksSinceLastSweep ?? 0) + 1;
885
+ }
761
886
  }
762
887
  return !dead;
763
888
  });
764
889
  if (s.writebacks.length !== before) {
765
890
  await saveTeamAutoStore(s);
766
891
  }
892
+ // #5725 (ggcode): settle self-audit. A COMPLETED teamauto task with a
893
+ // textual result whose write-back entry is absent AND whose ok line is
894
+ // missing from the activity feed means the registration (or the whole
895
+ // entry) was lost - the ladder redundancy channel silently failed.
896
+ // Alarm once per task so the observability contract survives entry loss.
897
+ let auditDirty = false;
898
+ if (state0) {
899
+ s.orphanResultAlarms ??= {};
900
+ s.deliveredResults ??= {};
901
+ // #5738 (ggcode, 2026-11-17): ONE-TIME migration. The #5736 backfill
902
+ // only stamped entries still present in the write-back array at
903
+ // deploy time - historically delivered legs were already pruned, so
904
+ // they all re-entered the alarm domain on the first settled pass
905
+ // (23 tasks, 99 lines in 80s). Seed the ledger once from the task
906
+ // state itself: everything completed with a result inside the audit
907
+ // window at init time is treated as delivered (the sentinel verified
908
+ // those 23 were all normally delivered). Accepted trade-off: any
909
+ // genuine pre-deploy orphan is pardoned once - signal > archaeology.
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) {
917
+ s.deliveredResultsInit = true;
918
+ for (const task of Object.values(state0.tasks ?? {})) {
919
+ if (task?.id && task.status === "completed" && task.result && task.id.startsWith("teamauto-") && task.completedAt && Date.now() - task.completedAt <= 24 * 3600_000) {
920
+ s.deliveredResults[task.id] = task.completedAt;
921
+ }
922
+ }
923
+ auditDirty = true;
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);
932
+ for (const task of Object.values(state0.tasks ?? {})) {
933
+ if (!task?.id || task.status !== "completed" || !task.result || !task.id.startsWith("teamauto-"))
934
+ continue;
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)
942
+ continue;
943
+ // #5738: once-per-task gate; the audit now persists its own
944
+ // mutations in the same pass (auditDirty save below), so the gate
945
+ // survives the next 20s disk reload instead of re-alarming.
946
+ const lastAlarmAt = s.orphanResultAlarms[task.id];
947
+ if (lastAlarmAt)
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;
953
+ // #5736: delivered-source is the DURABLE ledger (entry present OR
954
+ // recorded at prune time) - never the activity ring, which rolls in
955
+ // hours and made every normal delivery a false orphan.
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);
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
+ }
1051
+ s.orphanResultAlarms[task.id] = Date.now();
1052
+ auditDirty = true;
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)` });
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(() => { });
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];
1141
+ }
1142
+ if (Object.keys(s.orphanResultAlarms).length > 200) {
1143
+ const entries = Object.entries(s.orphanResultAlarms).sort((a, b) => a[1] - b[1]);
1144
+ for (const [k] of entries.slice(0, entries.length - 100))
1145
+ delete s.orphanResultAlarms[k];
1146
+ }
1147
+ // #5738: the gate lives on disk - persist audit mutations in the SAME
1148
+ // pass that makes them, or the next 20s reload resets the gate and
1149
+ // re-alarms everything (99 lines / 23 tasks live).
1150
+ if (auditDirty) {
1151
+ await saveTeamAutoStore(s);
1152
+ }
1153
+ }
767
1154
  // Live-verified gap (mw5aun1l, 2026-11-07): this drop path fires for
768
1155
  // failed-without-result tasks BEFORE the pending loop below, so the
769
1156
  // terminal worktree cleanup there never ran for them - the single
@@ -795,7 +1182,9 @@ export function createTeamAutoScheduler(deps) {
795
1182
  for (const w of s.writebacks) {
796
1183
  if (w.error && !w.doneAt && !w.failedAt && state0) {
797
1184
  const t = state0.tasks[w.taskId];
798
- if (t && t.status === "completed" && t.result && (w.nextAttemptAt ?? 0) <= Date.now()) {
1185
+ // #5719: a FAILED task WITH a result is deliverable too (the result is
1186
+ // the work product - analysis/diagnostic legs). Same backoff reset.
1187
+ if (t && t.result && (t.status === "completed" || t.status === "failed") && (w.nextAttemptAt ?? 0) <= Date.now()) {
799
1188
  w.error = null;
800
1189
  }
801
1190
  }
@@ -832,25 +1221,35 @@ export function createTeamAutoScheduler(deps) {
832
1221
  return;
833
1222
  }
834
1223
  for (const entry of pending) {
1224
+ // #5685 (ggcode, 2026-11-16): gate on a TERMINAL task BEFORE touching
1225
+ // the entry. The old order stamped inFlightAt first and `continue`d
1226
+ // for still-running tasks, leaving the sticky intent to wedge the
1227
+ // entry out of pendingAll until the 600s stale reset - a completed
1228
+ // task's write-back was deliverable in exactly one 20s window every
1229
+ // ~10 minutes (live: the 02:30 fullReview legs delivered 8m42s-9m51s
1230
+ // after completion, long misread as deliberate "slow release"). The
1231
+ // intent stamp now happens only when the pass is about to dispatch.
1232
+ const task = state.tasks[entry.taskId];
1233
+ if (!task || (task.status !== "completed" && task.status !== "failed")) {
1234
+ continue;
1235
+ }
835
1236
  // #269 intent-first: persist the dispatch intent BEFORE any await so
836
1237
  // an overlapping pass (or a future guard-less caller) filters this
837
1238
  // entry out instead of re-delivering it.
838
1239
  entry.inFlightAt = Date.now();
839
1240
  await saveTeamAutoStore(s);
840
- const task = state.tasks[entry.taskId];
841
- if (!task || (task.status !== "completed" && task.status !== "failed")) {
842
- continue;
843
- }
844
1241
  const repo = s.repos.find((r) => r.id === entry.repoId);
845
1242
  const [owner, name] = entry.repoId.split("/");
846
1243
  try {
847
- if (task.status === "failed" || !task.result) {
848
- // Undeliverable in every future pass: a failed task never gains a
849
- // result, and "completed without result" cannot recover either.
850
- // Mark terminal (issue #24) so the entry is counted, surfaced via
851
- // activity/stats, and never pointlessly retried. Failed-without-
852
- // result entries are additionally dropped by the dead-letter pass
853
- // on the next reconcile.
1244
+ if (!task.result) {
1245
+ // Undeliverable in every future pass: "completed without result"
1246
+ // cannot recover. #5719 (ggcode, 2026-11-16): a FAILED task WITH a
1247
+ // textual result is NOT in this class - the result is the
1248
+ // deliverable (analysis/diagnostic work products). It now falls
1249
+ // through to normal delivery with an error footer; only
1250
+ // result-less entries (failed or completed) stay terminal.
1251
+ // Failed-without-result entries are additionally dropped by the
1252
+ // dead-letter pass on the next reconcile.
854
1253
  markWritebackFailure(s, entry, task.status === "failed" ? (task.error ?? "task failed") : "task completed without a textual result", { terminal: true });
855
1254
  // Terminal write task: its dispatch-time worktree has no delivery
856
1255
  // path left - remove it when the worker never produced deliverable
@@ -870,28 +1269,101 @@ export function createTeamAutoScheduler(deps) {
870
1269
  else {
871
1270
  const role = (task.assignedRole ?? "qa");
872
1271
  let body = `${task.result.trim()}\n${MARKER_FOOTER(role)}`;
1272
+ // #5719: a failed-with-result task delivers its result (the work
1273
+ // product) with the failure context appended - never silently
1274
+ // dropped as before.
1275
+ if (task.status === "failed" && task.error) {
1276
+ body = `${body}\n\n---\n[task reported failed: ${task.error.slice(0, 300)}]`;
1277
+ }
873
1278
  let writebackDone = false;
874
1279
  // WRITE TASKS (collaboration contract): commit the task worktree,
875
1280
  // push its branch, open a PR, and attach the link to the reply.
876
1281
  const repoId = entry.repoId;
877
1282
  const isTeamAutoWrite = task.writeMode === "write" && task.projectDir?.includes("__task-");
878
1283
  let prDeliveryFailed = false;
879
- if (isTeamAutoWrite) {
1284
+ if (isTeamAutoWrite && task.status !== "failed") {
1285
+ // #5719: a FAILED write task's worktree carries no deliverable by
1286
+ // construction (that is usually WHY it failed) - the PR step just
1287
+ // burns retries against an empty worktree. Deliver the result
1288
+ // comment directly; the worktree is cleaned by the terminal pass.
880
1289
  try {
881
1290
  const info = await client.getRepoInfo(repoId.split("/")[0], repoId.split("/")[1]);
882
- const wtDir = await sync.ensureTaskWorktree(repoId, task.id);
1291
+ const wtDir = await sync.ensureTaskWorktree(repoId, task.id, info.defaultBranch, info.cloneUrl);
883
1292
  const committed = await sync.commitAll(wtDir, `[teamclaw:${role}] ${task.title.replace(/^\[[^\]]+\]\s*/, "")}`.slice(0, 200), `teamclaw-${role}`, `teamclaw-${role}@users.noreply.github.com`);
884
1293
  const branch = `teamclaw/task-${task.id.replace(/[^\w-]/g, "")}`;
885
1294
  // Workers often commit themselves inside the worktree - deliver
886
1295
  // whenever the branch carries commits beyond base, not only when
887
1296
  // commitAll just added new ones.
888
- 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));
889
1302
  if (deliverable) {
890
- await sync.pushBranch(repoId, wtDir, info.cloneUrl, branch);
891
- 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)}`);
892
- entry.prUrl = pr.url;
893
- body = `${body}\n\nDelivered as PR: ${pr.url}`;
894
- recordActivity(s, { at: Date.now(), repoId, kind: "writeback", text: `PR opened: ${pr.url}` });
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
+ });
1308
+ if (push.alreadyDelivered) {
1309
+ // #stale-base follow-up: a previous incarnation already
1310
+ // delivered this branch (PR merged). Skip PR creation and
1311
+ // the retry ladder - the task's work is on the remote.
1312
+ body = `${body}\n\nWork for this task was already delivered on branch \`${branch}\` (previous delivery).`;
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)`;
1319
+ }
1320
+ else {
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
+ }
1366
+ }
895
1367
  }
896
1368
  await sync.removeTaskWorktree(repoId, task.id);
897
1369
  }
@@ -905,6 +1377,12 @@ export function createTeamAutoScheduler(deps) {
905
1377
  // two comments 2s apart. Fail atomically instead: the entry
906
1378
  // keeps its failed state + backoff and replays BOTH steps
907
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
+ }
908
1386
  prDeliveryFailed = true;
909
1387
  }
910
1388
  }
@@ -912,10 +1390,44 @@ export function createTeamAutoScheduler(deps) {
912
1390
  continue;
913
1391
  }
914
1392
  if (entry.action === "issueComment" && entry.targetId) {
915
- await client.postIssueComment(owner, name, entry.targetId, body);
916
- entry.doneAt = Date.now();
917
- entry.inFlightAt = undefined;
918
- writebackDone = true;
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) {
1411
+ // #5725 / #5660 parity: the worker may have posted the same body
1412
+ // directly during its execution window (takeOwnership legs deliver
1413
+ // an ownership-wrap comment themselves). Posting again duplicates;
1414
+ // skipping silently breaks the observability contract. Exact
1415
+ // whitespace-normalized match -> mark done + record the skip.
1416
+ const normalizedBody = body.replace(/\s+/g, " ").trim();
1417
+ const existingBodies = await client.getIssueCommentBodies(owner, name, entry.targetId);
1418
+ if (existingBodies.some((b) => b.replace(/\s+/g, " ").trim() === normalizedBody)) {
1419
+ entry.doneAt = Date.now();
1420
+ entry.inFlightAt = undefined;
1421
+ writebackDone = true;
1422
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `dedupe-skipped: identical body already on issue #${entry.targetId} (worker direct-post) - ladder posting skipped` });
1423
+ logger.info(`TeamAuto: write-back ${entry.taskId} issueComment deduped - identical body already on issue #${entry.targetId}`);
1424
+ }
1425
+ else {
1426
+ await client.postIssueComment(owner, name, entry.targetId, body);
1427
+ entry.doneAt = Date.now();
1428
+ entry.inFlightAt = undefined;
1429
+ writebackDone = true;
1430
+ }
919
1431
  // Our own comment bumps the issue's updatedAt, which the scanner
920
1432
  // treats as new activity - advance the seen cursor so we do not
921
1433
  // re-trigger a review of an object we just replied to. External
@@ -926,10 +1438,45 @@ export function createTeamAutoScheduler(deps) {
926
1438
  }
927
1439
  }
928
1440
  else if (entry.action === "prComment" && entry.targetId) {
929
- await client.postPullReviewComment(owner, name, entry.targetId, body);
930
- entry.doneAt = Date.now();
931
- entry.inFlightAt = undefined;
932
- writebackDone = true;
1441
+ // #5660 (ggcode, 2026-11-15): the worker already posted the same
1442
+ // review body directly during its execution window; the ladder
1443
+ // then delivered the IDENTICAL text 20s later - readers got the
1444
+ // review twice. Before posting, check the target's existing
1445
+ // feedback (reviews + comments, whitespace-normalized): an exact
1446
+ // match means delivery already happened through the other
1447
+ // channel - mark done and record the skip.
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);
1466
+ const existing = await client.getPullFeedbackBodies(owner, name, entry.targetId).catch(() => []);
1467
+ if (existing.some((b) => stripCollapsedFooter(b) === normalized)) {
1468
+ entry.doneAt = Date.now();
1469
+ entry.inFlightAt = undefined;
1470
+ writebackDone = true;
1471
+ 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` });
1472
+ logger.info(`TeamAuto: write-back ${entry.taskId} prComment deduped - identical body already on PR #${entry.targetId}`);
1473
+ }
1474
+ else {
1475
+ await client.postPullReviewComment(owner, name, entry.targetId, postBody);
1476
+ entry.doneAt = Date.now();
1477
+ entry.inFlightAt = undefined;
1478
+ writebackDone = true;
1479
+ }
933
1480
  const prRepo = s.repos.find((r) => r.id === entry.repoId);
934
1481
  if (prRepo) {
935
1482
  prRepo.cursors.seen[`${entry.repoId}#pr-${entry.targetId}`] = Date.now();
@@ -940,18 +1487,49 @@ export function createTeamAutoScheduler(deps) {
940
1487
  // (first completed section creates it, the rest post as comments).
941
1488
  const sectionBody = `### ${role} section\n\n${task.result.trim()}\n${MARKER_FOOTER(role)}`;
942
1489
  if (entry.cycleKey) {
943
- const peers = s.writebacks.filter((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
944
- const umbrella = peers[0];
945
- if (umbrella && umbrella.targetId != null) {
946
- await client.postIssueComment(owner, name, umbrella.targetId, sectionBody);
947
- entry.targetId = umbrella.targetId;
1490
+ // #5685 (ggcode, 2026-11-16): the umbrella pointer must survive
1491
+ // the end-of-pass pruning of done write-back entries (and
1492
+ // process restarts). The old lookup only saw peers delivered
1493
+ // in the SAME pass, so every cross-pass section minted its own
1494
+ // duplicate umbrella - live: cycle 20772 produced issues
1495
+ // #5686/#5687/#5688 (three "Joint full review" umbrellas,
1496
+ // zero section comments). The store map is the durable
1497
+ // pointer; an in-pass done peer remains as a fallback for
1498
+ // stores written before this fix.
1499
+ const cycleKey = `${entry.repoId}|${entry.cycleKey}`;
1500
+ s.fullReviewUmbrellas = s.fullReviewUmbrellas ?? {};
1501
+ const peerEntry = s.writebacks.find((w) => w.repoId === entry.repoId && w.cycleKey === entry.cycleKey && w.taskId !== entry.taskId && w.targetId != null && w.doneAt);
1502
+ const umbrellaNumber = s.fullReviewUmbrellas[cycleKey] ?? peerEntry?.targetId ?? null;
1503
+ if (umbrellaNumber != null) {
1504
+ // Crash-retry guard: this entry may BE the creator whose
1505
+ // createIssue + umbrella-map write persisted but whose doneAt
1506
+ // did not. The umbrella body already carries its section, so
1507
+ // a creator retry completes silently instead of re-posting.
1508
+ if (entry.targetId !== umbrellaNumber) {
1509
+ await client.postIssueComment(owner, name, umbrellaNumber, sectionBody);
1510
+ }
1511
+ entry.targetId = umbrellaNumber;
1512
+ s.fullReviewUmbrellas[cycleKey] = umbrellaNumber;
948
1513
  entry.doneAt = Date.now();
949
1514
  entry.inFlightAt = undefined;
950
1515
  writebackDone = true;
1516
+ entry.deliveryNote = "section-appended-to-umbrella";
951
1517
  }
952
1518
  else if (entry.targetId == null) {
953
1519
  const number = await client.createIssue(owner, name, `[teamclaw:fullreview] Joint full review - ${entry.repoId}`, `Joint multi-role full review (cycle ${entry.cycleKey}). Each role appends its section as a comment below.\n\n${sectionBody}`, ["teamclaw", "teamclaw:fullreview"]);
954
1520
  entry.targetId = number;
1521
+ s.fullReviewUmbrellas[cycleKey] = number;
1522
+ entry.deliveryNote = "umbrella-created";
1523
+ // Persist the umbrella pointer immediately: done entries are
1524
+ // pruned at end-of-pass, and a crash between create and the
1525
+ // tail save must not lose the only record of the umbrella.
1526
+ const umbrellaKeys = Object.keys(s.fullReviewUmbrellas);
1527
+ if (umbrellaKeys.length > 100) {
1528
+ for (const staleKey of umbrellaKeys.slice(0, umbrellaKeys.length - 100)) {
1529
+ delete s.fullReviewUmbrellas[staleKey];
1530
+ }
1531
+ }
1532
+ await saveTeamAutoStore(s);
955
1533
  entry.doneAt = Date.now();
956
1534
  entry.inFlightAt = undefined;
957
1535
  writebackDone = true;
@@ -974,36 +1552,213 @@ export function createTeamAutoScheduler(deps) {
974
1552
  // does not linger in the errored/failed stats (issue #24).
975
1553
  entry.error = null;
976
1554
  entry.failedAt = null;
977
- recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok (${task.id}${entry.attempts ? `, after ${entry.attempts} failed attempt(s)` : ""})` });
1555
+ // #5735: distinguish created-vs-appended so umbrella cycles stop
1556
+ // reading as double-creates (two "createIssue #N ok" lines for
1557
+ // one issue is by design: first creates, peers append sections).
1558
+ recordActivity(s, { at: Date.now(), repoId: entry.repoId, kind: "writeback", text: `${entry.action} #${entry.targetId ?? "-"} ok${entry.deliveryNote ? ` [${entry.deliveryNote}]` : ""} (${task.id}${entry.attempts ? `, after ${entry.attempts} failed attempt(s)` : ""})` });
978
1559
  }
979
1560
  }
980
1561
  }
981
1562
  catch (err) {
982
- markWritebackFailure(s, entry, err instanceof Error ? err.message : String(err));
1563
+ const message = err instanceof Error ? err.message : String(err);
1564
+ markWritebackFailure(s, entry, message, {
1565
+ // #5704: an envelope-frame rejection is deterministic corruption -
1566
+ // the payload cannot change between attempts. Fail terminally
1567
+ // instead of burning the retry ladder re-posting the same frame.
1568
+ terminal: message.includes(ENVELOPE_LEAK_MARKER),
1569
+ });
983
1570
  }
984
1571
  void repo;
985
1572
  }
1573
+ // #5736 (ggcode): record deliveries into the durable ledger BEFORE the
1574
+ // done-entry prune - the write-back array and the tiny activity ring are
1575
+ // both short-lived, but the orphan audit runs for 24h after completion.
1576
+ // Without this, every normally-delivered task alarms as an orphan once
1577
+ // its entry is pruned and its ok line rolls off the ring.
1578
+ s.deliveredResults ??= {};
1579
+ s.prDeliveries ??= {};
1580
+ for (const w of s.writebacks) {
1581
+ if (w.doneAt) {
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
+ }
1590
+ }
1591
+ }
1592
+ const deliveredEntries = Object.entries(s.deliveredResults);
1593
+ if (deliveredEntries.length > 2000) {
1594
+ deliveredEntries.sort((a, b) => a[1] - b[1]);
1595
+ for (const [k] of deliveredEntries.slice(0, deliveredEntries.length - 1500))
1596
+ delete s.deliveredResults[k];
1597
+ }
986
1598
  s.writebacks = s.writebacks.filter((w) => !w.doneAt).slice(-500);
987
1599
  await saveTeamAutoStore(s);
988
1600
  }
989
1601
  // Register the write-back intent when a task lands in the task store.
990
- function registerWriteback(taskId, action, repoId, targetId, cycleKey) {
991
- void ensureStore().then((s) => {
992
- if (s.writebacks.some((w) => w.taskId === taskId)) {
993
- return;
1602
+ // #5643 (user report 2026-11-15): this used to be fire-and-forget
1603
+ // (void ensureStore().then(...).catch(() => {})) - the push+save raced the
1604
+ // sweep's own awaited store save AND swallowed its own errors. The 11-15
1605
+ // 02:00 batch lost ALL THREE fullReview write-back entries that way
1606
+ // (tasks + activity + "created 3/3" persisted; the entries did not), so
1607
+ // completed reviews delivered nothing, silently. Registration is now part
1608
+ // of the sweep transaction: the caller awaits it before the sweep's own
1609
+ // save, and failures propagate instead of vanishing.
1610
+ async function registerWriteback(taskId, action, repoId, targetId, cycleKey) {
1611
+ // #5712 (ggcode) / teamclaw#274: every store read-modify-write must hold
1612
+ // withStoreLock. Public entry takes the lock; the sweep transaction calls
1613
+ // the *Unlocked core directly because IT already holds the lock (the
1614
+ // promise-chain mutex is NOT re-entrant - nesting would deadlock).
1615
+ await withStoreLock(async () => {
1616
+ await reloadStoreUnlocked(); // #5792: fresh handle under the lock
1617
+ return registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey);
1618
+ });
1619
+ }
1620
+ async function registerWritebackUnlocked(taskId, action, repoId, targetId, cycleKey) {
1621
+ const s = await ensureStore();
1622
+ if (s.writebacks.some((w) => w.taskId === taskId)) {
1623
+ return;
1624
+ }
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).
1641
+ if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
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)` });
1643
+ }
1644
+ s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1645
+ await saveTeamAutoStore(s);
1646
+ }
1647
+ // #claim-dequeue (user report 2026-11-15): claim at DEQUEUE time, not
1648
+ // enqueue. Enqueue-time claims locked a whole queue of issues behind the
1649
+ // one-writer-per-repo serialization while they waited; and a blind claim
1650
+ // over issues where external collaborators had begun working (comments,
1651
+ // assignees) only produced conflicts. At dequeue we re-check FRESH state:
1652
+ // - any assignee -> stand down (a human or another bot owns it)
1653
+ // - any external comment posted after the task was enqueued -> stand
1654
+ // down (someone is actively working; our own bot's comments excluded)
1655
+ // Only a quiet, unowned issue gets claimed (assign, comment fallback),
1656
+ // with the existing seen+60s self-bump guard.
1657
+ async function claimTaskAtDequeue(task) {
1658
+ const kindMatch = /^\[([^\]]+)\]/.exec(task.title);
1659
+ if (!kindMatch || kindMatch[1] !== "takeOwnership")
1660
+ return { claimed: false, reason: "not a takeOwnership task" };
1661
+ const numMatch = /issue #(\d+)/.exec(task.title);
1662
+ if (!numMatch)
1663
+ return { claimed: false, reason: "no issue number" };
1664
+ const issueNumber = Number(numMatch[1]);
1665
+ const repoMatch = /TeamAuto autonomous work for ([\w./-]+)\./.exec(task.description);
1666
+ if (!repoMatch)
1667
+ return { claimed: false, reason: "no repo in description" };
1668
+ const repoId = repoMatch[1];
1669
+ const [owner, name] = repoId.split("/");
1670
+ if (!owner || !name)
1671
+ return { claimed: false, reason: "bad repo id" };
1672
+ const client = createGithubClient(auth);
1673
+ // #5740 (ggcode, 2026-11-17): eligibility CHECK failures (fetch failed on
1674
+ // getIssue/getAuthenticatedUser/getIssueCommentsSince) must NOT let the
1675
+ // task run unclaimed - the conflict check is the core #claim-dequeue
1676
+ // contract. Only the WRITE phase (assign/comment) may continue
1677
+ // unclaimed on failure (original 2026-11-15 semantics). The caller
1678
+ // reverts the assignment on retryEligibility so the next auto-assign
1679
+ // pass re-checks; a network blip delays execution by ~20s, an outage
1680
+ // loops at assignment cadence instead of silently bypassing the gate.
1681
+ let login;
1682
+ try {
1683
+ const fresh = await client.getIssue(owner, name, issueNumber);
1684
+ if (fresh.state !== "open") {
1685
+ return { claimed: false, reason: "issue closed" };
994
1686
  }
995
- // #269 per-target dedupe (enqueue side): a second registration for
996
- // the SAME target + action with no doneAt yet is a duplicate in the
997
- // making - the delivery pass would fan out two comments onto one
998
- // target. Skip it; the pending original still delivers the content.
999
- // targetId null (create* actions) cannot be target-deduped pre-delivery
1000
- // and is excluded by the taskId check above.
1001
- if (targetId != null && s.writebacks.some((w) => w.targetId === targetId && w.repoId === repoId && w.action === action && !w.doneAt)) {
1002
- return;
1687
+ const s0 = await ensureStore();
1688
+ const repo0 = s0.repos.find((r) => r.id === repoId);
1689
+ if ((repo0?.policy.skipAssignedToHumans ?? true) && fresh.assignees.length > 0) {
1690
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `deferred claim: issue #${issueNumber} has assignee(s) ${fresh.assignees.join(",")} at dequeue - standing down` });
1691
+ return { claimed: false, reason: "assignees present" };
1692
+ }
1693
+ // External-work check: comments posted after the task was ENQUEUED.
1694
+ const sinceIso = new Date(task.createdAt ?? Date.now()).toISOString();
1695
+ login = (await client.getAuthenticatedUser()).login;
1696
+ const comments = await client.getIssueCommentsSince(owner, name, issueNumber, sinceIso);
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
+ });
1713
+ if (external.length > 0) {
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` });
1715
+ return { claimed: false, reason: "external activity" };
1716
+ }
1717
+ }
1718
+ catch (err) {
1719
+ const msg = err instanceof Error ? err.message : String(err);
1720
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue ELIGIBILITY CHECK failed for issue #${issueNumber}: ${msg.slice(0, 120)} - reverting assignment, will retry` });
1721
+ return { claimed: false, reason: "eligibility-check-failed", retryEligibility: true };
1722
+ }
1723
+ // #5740 (ggcode, 2026-11-17): the WRITE phase keeps the original
1724
+ // 2026-11-15 "continue unclaimed" semantics when it fails (the
1725
+ // eligibility checks DID pass), but it must not vanish silently - the
1726
+ // caller swallows rejections - so record the audit line here and return
1727
+ // a non-retrying result.
1728
+ try {
1729
+ let claimNote = "";
1730
+ try {
1731
+ await client.assignIssue(owner, name, issueNumber, login);
1732
+ claimNote = `claimed issue #${issueNumber} as @${login} (at dequeue)`;
1003
1733
  }
1004
- s.writebacks.push({ taskId, action, repoId, targetId, doneAt: null, prUrl: null, error: null, cycleKey });
1005
- void saveTeamAutoStore(s);
1006
- }).catch(() => { });
1734
+ catch {
1735
+ // Fallback: a visible claim comment carries the same placeholder
1736
+ // semantics when the App lacks the assignees write surface.
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.`);
1738
+ claimNote = `claimed issue #${issueNumber} via comment (assign unavailable, at dequeue)`;
1739
+ }
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 });
1748
+ const freshRepo = s.repos.find((r) => r.id === repoId);
1749
+ if (freshRepo) {
1750
+ // +60s guard: our own write (assign or comment) bumps updated_at.
1751
+ freshRepo.cursors.seen[`${repoId}#issue-${issueNumber}`] = Date.now() + 60_000;
1752
+ await saveTeamAutoStore(s);
1753
+ }
1754
+ });
1755
+ return { claimed: true };
1756
+ }
1757
+ catch (err) {
1758
+ const msg = err instanceof Error ? err.message : String(err);
1759
+ recordActivity(await ensureStore(), { at: Date.now(), repoId, kind: "claim", text: `claim-at-dequeue WRITE failed for issue #${issueNumber}: ${msg.slice(0, 120)} - continuing unclaimed` });
1760
+ return { claimed: false, reason: "claim write failed" };
1761
+ }
1007
1762
  }
1008
1763
  /** #268: make a takeOwnership claim VISIBLE on the issue itself. Until now
1009
1764
  * assignIssue was dead code and registerWriteback had no assign action, so
@@ -1037,24 +1792,31 @@ export function createTeamAutoScheduler(deps) {
1037
1792
  return;
1038
1793
  }
1039
1794
  const { login } = await client.getAuthenticatedUser();
1795
+ let claimNote = "";
1040
1796
  try {
1041
1797
  await client.assignIssue(owner, name, candidate.number, login);
1042
- 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}`;
1043
1799
  }
1044
1800
  catch {
1045
1801
  // Fallback: a visible claim comment carries the same placeholder
1046
1802
  // semantics when the App lacks the assignees write surface.
1047
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.`);
1048
- recordActivity(await ensureStore(), { at: Date.now(), repoId: repo.id, kind: "claim", text: `claimed issue #${candidate.number} via comment (assign unavailable)` });
1049
- }
1050
- const s = await ensureStore();
1051
- const freshRepo = s.repos.find((r) => r.id === repo.id);
1052
- if (freshRepo) {
1053
- // +60s guard: our own write (assign or comment) bumps updated_at;
1054
- // see helper doc.
1055
- freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1056
- await saveTeamAutoStore(s);
1804
+ claimNote = `claimed issue #${candidate.number} via comment (assign unavailable)`;
1057
1805
  }
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 });
1812
+ const freshRepo = s.repos.find((r) => r.id === repo.id);
1813
+ if (freshRepo) {
1814
+ // +60s guard: our own write (assign or comment) bumps updated_at;
1815
+ // see helper doc.
1816
+ freshRepo.cursors.seen[candidate.key] = Date.now() + 60_000;
1817
+ await saveTeamAutoStore(s);
1818
+ }
1819
+ });
1058
1820
  }
1059
1821
  catch (err) {
1060
1822
  logger.warn(`TeamAuto: claim for ${repo.id}#${candidate.number} failed (task continues unclaimed): ${err instanceof Error ? err.message : String(err)}`);
@@ -1081,6 +1843,14 @@ export function createTeamAutoScheduler(deps) {
1081
1843
  if (task?.status !== "failed" || typeof task.description !== "string" || !task.description.includes("Idempotency-Key:")) {
1082
1844
  continue;
1083
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
+ }
1084
1854
  if (s.failedClaimRecovery[taskId]) {
1085
1855
  continue;
1086
1856
  }
@@ -1199,60 +1969,85 @@ export function createTeamAutoScheduler(deps) {
1199
1969
  void recoverFailedClaims();
1200
1970
  }, 60_000);
1201
1971
  claimRecoveryTimer.unref?.();
1202
- // Boot reconciliation: heal leftover task worktrees whose task is
1203
- // terminal (or gone entirely) - the pre-cleanup backlog never shrinks
1204
- // on its own. Safety-checked: undelivered work is kept and logged.
1205
- void (async () => {
1206
- try {
1207
- // #173 follow-up 3: with getTeamState() === null the isTerminal
1208
- // predicate below classifies EVERY task as terminal - boot GC must
1209
- // not run blind over an unloaded team state (fails toward skip).
1210
- if (!deps.getTeamState()) {
1211
- logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1212
- return;
1213
- }
1214
- let removed = 0;
1215
- let retained = 0;
1216
- let stale = 0;
1217
- const retainedDetails = [];
1218
- for (const repo of s.repos) {
1219
- if (!repo.enabled)
1220
- continue;
1221
- const isTerminal = (taskId) => {
1222
- const t = deps.getTeamState()?.tasks[taskId];
1223
- if (t && t.status !== "completed" && t.status !== "failed")
1224
- return false;
1225
- // Review F1: a terminal task with a pending write-back (push
1226
- // ok / PR failed, 20s-retry window) still needs its worktree -
1227
- // the retry delivers the PR from the surviving branch. Do not
1228
- // GC until the write-back settles (doneAt or dropped). Issue
1229
- // #24: terminally failed write-backs (failedAt) count as settled
1230
- // too - safeRemoveTaskWorktree still retains unpushed work.
1231
- return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
1232
- };
1233
- const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle);
1234
- removed += r.removed.length;
1235
- retained += r.retained.length;
1236
- stale += r.stale;
1237
- retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1238
- }
1239
- if (removed || retained || stale) {
1240
- // #173 follow-up 4: per-task retain reasons recorded as activity
1241
- // (PR #167 promised "outcome logged + recorded as activity"); the
1242
- // stale count surfaces dir-gone-but-branch-kept leaks too.
1243
- const detail = retainedDetails.length
1244
- ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
1245
- : "";
1246
- const stalePart = stale ? `, stale ${stale}` : "";
1247
- recordActivity(s, { at: Date.now(), repoId: "*", kind: "task", text: `worktree GC: removed ${removed}, retained ${retained} (undelivered${detail})${stalePart}` });
1248
- await saveTeamAutoStore(s);
1249
- logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
1250
- }
1972
+ // #gc-periodic: worktree GC used to be boot-only with an enabled-repo
1973
+ // filter - two defects (live-instance audit 2026-11-14): (a) a disabled
1974
+ // repo ("do no NEW work") never got cleaned at all; (b) the single boot
1975
+ // pass ran before the device-flow auth warmed up, so every targetClosed
1976
+ // oracle call failed toward keep and closed-target orphans stayed (4
1977
+ // confirmed misretains). Now a recurring pass: first run delayed 60s
1978
+ // (auth warm), then every 6h - transient oracle failures self-heal on
1979
+ // the next pass.
1980
+ const gcDelay = setTimeout(() => {
1981
+ void runGcPass();
1982
+ gcTimer = setInterval(() => {
1983
+ void runGcPass();
1984
+ }, 6 * 60 * 60_000);
1985
+ gcTimer.unref?.();
1986
+ }, 60_000);
1987
+ gcDelay.unref?.();
1988
+ }
1989
+ /** #gc-periodic: one full worktree GC pass over ALL bound repos (enabled
1990
+ * or not - GC is hygiene, not new work). Shared by the boot-delayed first
1991
+ * run and the 6h recurrence. */
1992
+ async function runGcPass() {
1993
+ try {
1994
+ // #173 follow-up 3: with getTeamState() === null the isTerminal
1995
+ // predicate below classifies EVERY task as terminal - GC must not run
1996
+ // blind over an unloaded team state (fails toward skip).
1997
+ if (!deps.getTeamState()) {
1998
+ logger.warn("TeamAuto: worktree GC skipped (team state unavailable)");
1999
+ return;
1251
2000
  }
1252
- catch (err) {
1253
- logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
2001
+ const s = await ensureStore();
2002
+ let removed = 0;
2003
+ let retained = 0;
2004
+ let stale = 0;
2005
+ const retainedDetails = [];
2006
+ for (const repo of s.repos) {
2007
+ const isTerminal = (taskId) => {
2008
+ const t = deps.getTeamState()?.tasks[taskId];
2009
+ if (t && t.status !== "completed" && t.status !== "failed")
2010
+ return false;
2011
+ // Review F1: a terminal task with a pending write-back (push
2012
+ // ok / PR failed, 20s-retry window) still needs its worktree -
2013
+ // the retry delivers the PR from the surviving branch. Do not
2014
+ // GC until the write-back settles (doneAt or dropped). Issue
2015
+ // #24: terminally failed write-backs (failedAt) count as settled
2016
+ // too - safeRemoveTaskWorktree still retains unpushed work.
2017
+ return !s.writebacks.some((w) => w.taskId === taskId && !w.doneAt && !w.failedAt);
2018
+ };
2019
+ // #gc3: no task record anywhere in team-state -> the owner ruled
2020
+ // outright deletion (2026-11-14, "全删") - such worktrees can never
2021
+ // be judged by any oracle and were retained forever.
2022
+ const isUnknownTask = (taskId) => !deps.getTeamState()?.tasks?.[taskId];
2023
+ const r = await sync.gcTaskWorktrees(repo.id, isTerminal, squashDeliveryOracle, targetClosedOracle, isUnknownTask);
2024
+ removed += r.removed.length;
2025
+ retained += r.retained.length;
2026
+ stale += r.stale;
2027
+ retainedDetails.push(...r.retained.map((x) => `${x.taskId}: ${x.reason}`));
1254
2028
  }
1255
- })();
2029
+ if (removed || retained || stale) {
2030
+ // #173 follow-up 4: per-task retain reasons recorded as activity
2031
+ // (PR #167 promised "outcome logged + recorded as activity"); the
2032
+ // stale count surfaces dir-gone-but-branch-kept leaks too.
2033
+ const detail = retainedDetails.length
2034
+ ? `; ${retainedDetails.slice(0, 10).join("; ")}${retainedDetails.length > 10 ? `; +${retainedDetails.length - 10} more` : ""}`
2035
+ : "";
2036
+ const stalePart = stale ? `, stale ${stale}` : "";
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
+ });
2045
+ logger.warn(`TeamAuto: worktree GC removed ${removed}, retained ${retained}${stalePart}`);
2046
+ }
2047
+ }
2048
+ catch (err) {
2049
+ logger.warn(`TeamAuto: worktree GC failed: ${err instanceof Error ? err.message : String(err)}`);
2050
+ }
1256
2051
  }
1257
2052
  async function stop() {
1258
2053
  running = false;
@@ -1265,6 +2060,9 @@ export function createTeamAutoScheduler(deps) {
1265
2060
  if (claimRecoveryTimer) {
1266
2061
  clearInterval(claimRecoveryTimer);
1267
2062
  }
2063
+ if (gcTimer) {
2064
+ clearInterval(gcTimer);
2065
+ }
1268
2066
  writebackTimer = null;
1269
2067
  }
1270
2068
  }
@@ -1279,7 +2077,7 @@ export function createTeamAutoScheduler(deps) {
1279
2077
  const s = await ensureStore();
1280
2078
  return (s.activity ?? []).slice().reverse();
1281
2079
  }
1282
- return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
2080
+ return { addRepo, removeRepo, setRepoEnabled, updateRepo, runSweepNow, registerWriteback, reconcileWritebacks, claimTaskAtDequeue, start, stop, getStatus, getActivity, ensureWriteWorktree, removeWriteWorktree, proposeManual };
1283
2081
  /** Collaboration contract: dispatch asks for a task-scoped worktree dir (rel to projects root). */
1284
2082
  async function ensureWriteWorktree(repoId, taskId) {
1285
2083
  const wtAbs = await sync.ensureTaskWorktree(repoId, taskId);